Often we need to delete old file on Linux or Unix which are old (say 30 days or more). Here are some commands which can help delete old files.
List files older than 30 days
Linux/Unix command to just list old files. This may be useful as dryrun for testing cron, bash scrits, etc.
find /path/to/dir -mtime +30 -type f -exec ls -l {} \;
Delete files older than 30 days
Here we’ll delete old files and print what got deleted (-v). Printing what got deleted may be useful for auditing purpose.
find /path/to/dir -mtime +30 -type f -exec rm -v {} \;In case you want to capture what got deleted in a file, you can use the following bash code:
DATE=$(date +"%Y%m%d-%H%m%S") find /tmp/data -mtime +30 -type f -exec rm -v {} \; > deleted_list.$DATE
This will generate a file like deleted_list.20160128-040142 for each run.