Find and remove old files
Hi all,
trying to remove older files more than 90 days old. Want to make sure if below command is the right one to do that job. (i could have tested this but on test machine i don't have files older than 90 days and on the prod machine i want to make sure this works before applying it) and also can somebody explain what {} \ will do at the end ? Code:
find . -name "*.txt" -mtime +90 -exec rm -rf {} \; |
Seems almost valid for your goal.
The {} is a placeholder for each of the files find finds. The \; is an escaped ; because the shell would, otherwise, expect another command to execute sequentially after find ends (e.g: cmdA; cmdB executes first cmdA then cmdB when cmdA ends). Given that you just want to remove the files you could use the -delete command instead of -exec and rm: Code:
find . -name "*.txt" -mtime +90 -delete |
Quote:
Quote:
|
Hi 414N and unSpawn, thanks for the replies.
If i use the following code, will it search in all directories under the path recursively to find ".txt" files and remove ? Code:
find /Test -type f -name "*.txt" -mtime +90 -delete I want to run this as a cron job. Thanks in advance! |
Of course. Like unSpawn already said, you should always test the command inside a test directory before putting it inside a cron job. Be aware that using -delete implies -depth, so all the sub-directories inside the specified path will be searched too.
If an error occurs during deletion, find prints an error message that you could log in a way like this: Code:
find [...] &>> /path/where/to/log/file To log the files that got successfully deleted you can't use the -delete command anymore because it only prints a message when something goes wrong, but you could use something like this: Code:
find /Test -type f -name "*.txt" -mtime +90 -exec rm -vf {} &>> /path/where/to/log/file \; The -r rm option you previously specified is useless in this context because you're searching for regular files, not directories. |
Thank you 414N,
I tried below just to make sure it redirects the output to a file but ended with an error. Code:
# find . -type f -name "*.txt" -exec ls -ltrh {} &>> /root/listoffiles.txt \; |
Put your \; before your >>
|
Code:
find . -type f -name "*.txt" -exec ls -ltrh {} \; &>> /root/listoffiles.txt |
Heres your cron for you(I Got bored).
Add the following to your /etc/logrotate.conf modifying the rotate number variable to the number of days you want to maintain logs for: Code:
/var/log/listofoldfiles.log { Code:
#!/bin/bash/ |
All times are GMT -5. The time now is 08:05 PM. |