Beyond Searching
The Linux find command is exceptionally good at locating specific files based on names, permissions, and dates. However, simply printing a list of files to the terminal screen is rarely the final goal. Usually, once you find the files, you want to do something with them—like delete them, change their permissions, or move them to a backup folder. Instead of manually typing out a secondary command for every single file the search engine returns, you can force the find command to directly execute a Bash command on every file it discovers.
Using the find Command with -exec
The -exec flag allows you to append a standard Linux command directly to your search string.
- Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
- To locate all files ending in
.bakinside the/var/www/directory and immediately delete them, type the following command exactly:sudo find /var/www/ -type f -name "*.bak" -exec rm {} \; - Press Enter and provide your administrator password.
Syntax Breakdown
The syntax for the -exec flag is highly specific and must be typed perfectly. The empty curly braces {} act as a placeholder; the search engine will automatically replace the braces with the actual file path of the discovered file before running the command. The command must absolutely be terminated with an escaped semicolon \; so the Bash interpreter knows where the execution loop ends. Warning: The -exec rm command will delete files instantly without asking for confirmation. Always run the find command without the -exec portion first to verify exactly which files you are about to destroy.