Skip to content

How to Execute Commands with find in Linux

January 26, 2023
Linux

This blog post will teach you how to Execute commands with find on files and directories in Linux. You will learn how to use the -exec option to specify the command to execute, and how to use various search criteria to select the files and directories to operate on

  • Commands can be executed on found files
    • command must be preceded with -exec or -ok
      • -ok prompts before acting on each file
    • Command must end with Space\;
    • Can use {} as a filename placeholder
    • find -size +100M -ok mv {} /tmp/largefiles/ \;

Using the -exec or -ok options with find will cause find to execute a command once for each file that matches the given criteria. This is commonly used for things like removing files or renaming files to have a certain extension. Be extremely careful when using -exec because it may perform the action on many files (remember that find recourses through subdirectories) and it does not ask for confirmation. Remember that running the search without -exec will list all matches, thus allowing you to preview which files will be acted upon. Alternately you can use the -ok option, which causes find to ask for each file.

The reason that the commands given with -exec and -ok must end in a \; is because find uses ; as the delimiting character. Unfortunately ; is also a delimiting character for the shell so we must prevent bash from interpreting it. When a character is prepended with a backslash (\), bash is instructed to treat it literally, so typing \; at the bash command prompt will send ; to find after bash has done its interpretation.

Find Execution Examples: –

  • Back up configuration files, adding a .orig extension
    $ find -name '*.conf' -exec cp {} {}.orig \;
  • Prompt to remove joe’s tmp files that are over 3 days old
    $ find /tmp -ctime +3 -user joe -ok rm {} \;
  • Fix other-writable files in your home directory
    $ find ~ -perm -002 -exec chmod o-w {} \;
  • Do an ls -l style listing of all directories in /home/
    $ find /home -type d -ls
  • Find files that end in .sh but are not executable by anyone. For each file, ask to make it executable by everyone
    $ find -not -perm +111 -name ‘*.sh’ -ok chmod 755 {} \;

You can use find to execute any command you would like, and if you use the {} as filename place holders, the find command will put the file name of a file it has found in place of {} and execute the command.