How to use the ‘find’ command with the -exec option In Linux
In the previous method, we had to use an external command, the xargs command to change the output of the find command in a pipable form to the rm command. However, there exists another way to run the rm command with the output of the find command without using the xargs command; using the -exec option of the find command.
The -exec option allows the user to run a command with the output of the find command. The syntax is as follows:
Syntax:
find <other options> -exec <command> {} \;
Here,
- <command>: The <command> placeholder takes the command to be executed.
- :{}: The {} placeholder specifies the path files found by the find command.
- \: The \ indicates the end of the -exec option.
- ;: The; is required to indicate the end of the command as the terminal by default takes the \ as a newline character.
To use this to find and delete files older than x days (5 days in this example) we can change the command from method 1 to the following:
find /home/my_folder -type f -mtime +5 -exec rm {} \;
Output:
As we can see the files that were older than 5 days were removed from the specified folder.
How to automatically delete/remove files older than x days in Linux
Linux operating systems are widely used for web servers and other data-heavy tasks such as penetration testing etc. In these applications, there can be an accumulation of files that are not useful after a certain period. Now Linux, being an operating system used mostly for its automation functionalities, provides many ways to remove files older than a particular number of days automatically. In this article, we shall see ways to remove files older than x days automatically.
Contact Us