1

I want to create a script that will delete any files older than 7 days on a specified list of directories, but wondering what would be the best way to go about it...

I want to perform the following command on all directories specified:

find DIRECTORY_PATH -type f -mtime +7 -exec rm {} \;

Maybe an array holding a list of directories, and loop through each element in the array performing the find command on that?

Any help/advice would be appreciated.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Shaw
  • 1,039
  • 3
  • 9
  • 18
  • 1
    Where do you have the list of paths? Because if it is in a file, you can loop through its lines and executing the `find` command. – fedorqui Mar 06 '14 at 15:03
  • 1
    Why not `find path1 path2 pathN `? – RedX Mar 06 '14 at 15:06
  • Currently within the script, as it's easier to maintain... But would it be easier to place in a separate file? – Shaw Mar 06 '14 at 15:08
  • It depends on how often you expect the list of directories to change. If never, then just hard-code them into the script. If frequently, it's good to shield changes in configuration from changes in the code. In between, it's a judgement call. – chepner Mar 06 '14 at 15:27
  • possible duplicate of [How to delete files older than X hours](http://stackoverflow.com/questions/249578/how-to-delete-files-older-than-x-hours) – l0b0 Mar 06 '14 at 16:03
  • Mmmm @l0b0 I disagree with the possible duplication: note that the OP's problem is how to loop through a list of dirs and perform the `find` command. – fedorqui Mar 06 '14 at 16:06

1 Answers1

2

You can directly store all the directories in a file, say dirs.txt and loop through it:

while read dir
do
  find "$dir" -type f -mtime +7 -exec rm {} \;
done < dirs.txt
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Quick question to add to that... How do I close the file (dirs.txt) once I have finished reading from it? – Shaw Mar 07 '14 at 14:52
  • You do not have to close it when doing the `while read ... do ... done < file` – fedorqui Mar 07 '14 at 14:53