1819817 Members
3158 Online
109607 Solutions
New Discussion юеВ

Help in script

 
SOLVED
Go to solution
Waqar Razi
Regular Advisor

Help in script

Can some one help me in writing a script with the following functionality.

Every time the script runs, it makes a directory naming config.mmddyy and stores configuration information in it. I have made a script upto this point.
Now I want to keep only the latest 5 directories and delete the diectories other than them with the information in them .
4 REPLIES 4
Tim Nelson
Honored Contributor
Solution

Re: Help in script

How about something like.

find /config.* - type d -mtime +5 |while read list
do
rm -r $list
done

(I would be carefull about rm -r, maybe even build a file list and rm $list then rmdir the directory.) If your list returns just "/" you will be bumming.

If you try to use each name mmddyy + 5 days you will run into the always difficult roll at EOM.

James R. Ferguson
Acclaimed Contributor

Re: Help in script

Hi Wagar:

# ls -lt|grep ^d|tail +5|awk '{print $NF}'|xargs rmdir

...assuming that the directories are ones immediately beneath the current working directory and that they are empty. If they are not empty, but you want to delete them and their contents, then:

# ls -lt|grep ^d|tail +5|awk '{print $NF}'|xargs rm -rf

Regards!

...JRF...
Steven Schweda
Honored Contributor

Re: Help in script

> [...] config.mmddyy [...]

If you used a naming scheme like yymmdd
instead of mmddyy, it would be easier to sort
the names chronologically, so techniques like
piping "ls" output into "head" or "tail"
could do useful things (easily).
Dennis Handly
Acclaimed Contributor

Re: Help in script

You could create 5 symlinks that point to the last 5 directories. Then when you create a new one, you shuffle them down.
To remove what the symlink points to, you can use: rm -rf symlink01/

To shuffle them down, you would have to parse the output of ll(1) to get the link target.