Table of Contents
It’s always recommended to find and cleanup your old files which are no longer necessary after a certain period of time.
This will save you some disk space. This brief tutorial walks you through how to find and delete files older than X days in Linux and Unix-like operating systems.
Find Files Older Than X Days In Linux
First, let’s find out the files older than X days, for example 30 days.
The below command will find and display the older files which are older than 30 days in the current working directory.
find . -mtime +30 -print
- dot (.) – Represents the current directory.
- -mtime – Represents the file modification time and is used to find files older than 30 days.
- -print – Displays the older files
The files older than 30 days in the current directory.
[root@kms log]# find . -mtime +30 -print
./tallylog
./grubby_prune_debug
./samba
./samba/old
./secure-20220828
./tuned
./tuned/tuned.log
./audit
./audit/audit.log.2
./audit/audit.log.1
./audit/audit.log
If you want to search files in a specific directory, just replace the dot with the folder path. For example, to find out the files which are older than 30 days in nginx log directory /var/log/nginx.
find /var/log/nginx -mtime +30 -print
[root@kms log]# find /var/log/nginx -mtime +30 -print
/var/log/nginx/error.log-20220908.gz
/var/log/nginx/error.log-20220909.gz
/var/log/nginx/error.log-20220911.gz
/var/log/nginx/access.log-20220912.gz
/var/log/nginx/error.log-20220916.gz
/var/log/nginx/access.log-20220909.gz
/var/log/nginx/access.log-20220911.gz
/var/log/nginx/error.log-20220912.gz
Delete Files Older Than X Days In Linux
find /var/log/nginx -type f -mtime +30 | xargs rm -f
Once done, when you run the command to find the files older than 30 days in nginx log directory. There’s nothing returned.
Alternatively, you can use one of below commands to find then delete files older than 30 days in a directory in Linux.
find /var/log/nginx -mtime +30 -exec rm -f {} \;
find /var/log/nginx -mtime +30 -delete;
Conclusion
Delete old files periodically if they are not necessary at regular intervals, or backup them to any external drives and free up disk space. You can use the free space for any other useful purposes.