How to find and delete older files (older than 7 days) in a folder using a bash script? It's a folder in a server which contain automatic backups. Need to delete old ones automatically so there's space for new ones.
3 Answers
#!/bin/bash
ssh user@machine "find /path/to/files/ -mtime +7 -exec rm {} \;"
name the script as some_file_name.sh and give execute permissions.
chmod +x file_name.sh
Run it as ./file_name.sh
or bash file_name.sh
For a short and easy to remember version :-
find <directory path> -ctime +7 -delete
This will delete files older than 7 days
Using the below command, first confirm the file list:
find . -mtime +7
If the list is correct, using below the files can be deleted.
find . -mtime +7 -exec rm '{}' \;