12-22-2008
3,
0
Join Date: Dec 2008
Last Activity: 12 April 2012, 11:09 PM EDT
Posts: 3
Thanks Given: 0
Thanked 0 Times in 0 Posts
regarding a script
Hello any body,
I am looking for a help in writing a script to delete a directory as below scenario.
I have a directory called builds in that many directories are there named say 12343,45686,76543(number named )and other name like changelist,maven,logs ,name.txt,and other .sh files etc. I am looking a script which should keep all directories and 4 latest numbered directories.i.e I need to delete numbered directories and keeping latest 4 directories at any time.I have written a script which keeps 4 latest directories or files at any point of time.please look my script. I should modify such a way tht it should not deleted any files or directories other than numbered directory and at the same time I need to have 4 latest numbered directories (it may be 1 months old or what ever) oldest from fifth directory should be removed.
#!/bin/bash
# Scans a directory and deletes all and retains user specfied directory
#Usage: remov.sh /path/ dir number of files to keep
if [ $# -ne 2 ]; then
echo 1>&2 "Usage: $0 dir_path number of files to keep=4 "
exit 1
fi
cd $1
files_in_dir=`ls | wc -l`
files_to_delete=`expr $files_in_dir - $2`
if [ $files_to_delete -gt 0 ]; then
ls -t | tail -n $files_to_delete | xargs rm -rf
#ls -t will list files based on date and tail -n tails the list
#xargs will break the list of arguments into sublists small enough to be acceptable
if [ $? -ne 0 ]; then
echo “An error ocurred deleting the files”
exit 1
else
echo “$files_to_delete file deleted.”
fi
else
echo “Nothing to delete!”
fi