Beyond Searching
The Linux find command is incredibly powerful for locating files based on size, permissions, or modification dates. However, simply printing a list of file paths to the terminal screen is rarely the final goal. Usually, once you find those specific files, you want to do something with them. For example, if you find 500 log files that are older than 30 days, you want to delete them. If you find 50 image files, you might want to change their permissions. Instead of manually copying and pasting the paths into a new command, you can instruct find to automatically execute a secondary command on every single file it discovers.
Using the find Command with -exec
You can chain commands together using the -exec (Execute) flag.
- Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
- To find all
.txtfiles in a directory and automatically change their permissions to 644, type the following command exactly: find ~/Documents/ -name "*.txt" -exec chmod 644 {} \;- Press Enter.
Understanding the Syntax
The syntax at the end of the command is critical and must be typed perfectly. The open and closed curly brackets {} act as a placeholder. Every time find locates a .txt file, it temporarily inserts the file’s exact path into those brackets and runs the chmod command. The backslash and semicolon \; simply tell the terminal that the execution command has finished, preventing syntax errors.