Gangmax Blog

Use "date" Command in File Name Filtering

Imagining the following scenario. You have a backup file created automatically each day. You want to have a cron job to remove the outdated backup files. A problem emerges: how to write a command to remove the outdated backup files and keep the ones which are not outdated?

The backup files are named with date like “backup-2024-03-26.tar.gz”. Then the problem becomes: how to select the files whose name matche the outdated pattern? The answer comes from the “date” command.

Let’s say the clean-up command runs in every 15th day of a month, and it removes the backup files created in the last month, which keeps the ones created in the current month. We just need to use the following “rm” command:

1
rm backup-$(date --date='1 month ago' +'%Y-%m')*.tar.gz

Note that the “date –date=’1 month ago’ +’%Y-%m’” part returns “2024-02” when the current date is “2024-03-xx”. So this command will just work as expected. More details about how to use the “date” command can be found here.

To make this command run every 15th day of a month, add the command line below after running “cronjob -e”:

1
2
3
# The cron schedule expresion below means "At 09:30 on day-of-month 15".
# From: https://crontab.guru/
30 9 15 * * rm /home/user/backups/backup-$(date --date='1 month ago' +'%Y-%m')*.tar.gz

Comments