Shell Script – Delete Old Files

For housekeeping the backup files on a server, we can write a shell script to remove files which were created some days ago and scheduled it by cron job.

The following code is an example to remove backup files which were created 90 days ago. Please note that the target folder is just the same as the .sh file location and the .sh file is excluded in the command.

# Add housekeeping which only keeps 90 days backup files

echo "Housekeeping starts"

# Delete backup files which are more than 90days old 
find ./ -mtime +89 -daystart -type f \( ! -iname "*.sh" \) -exec rm "{}" \;

echo "Housekeeping finished"

Enjoy =)

One thought on “Shell Script – Delete Old Files”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.