bash : run command on find results

Unix find command allows user to execute a command on the results by using -exec command. For example see below. {} get replaced by filename, Make sure to escape {} and ;.

find . -type f -exec ls -l {} ;

This triggers ls -l on all the files that were found. I used this with -maxdepth (how deep directory structure to examine) and -mtime (last modified time) to cleanup old files as below.

find /var/log -type f -mtime +30 -maxdepth 0 -exec rm -f {} ;

Now exec is not a very efficient. Basically here we are directing the find command to execute a command for each matching file (or directory, based on the filter). xargs could be used to combine the output of find and then passing on to a single command. That way we can limit the number of execs performed. But it comes with a warning. xargs has a command line length limit. So if the input to xargs grows bigger (e.g. a very deep directory structure or too many files), xargs has the tendency to fail. This limit can be found from manpages of xargs and is usually higher than other generic Unix commands (like ls, rm etc)

find /var/log -type f -mtime +30 -maxdepth 0 | xargs rm -f

Per man page of find

       -exec command ;
              Execute  command;  true  if 0 status is returned.  All following
              arguments to find are taken to be arguments to the command until
              an  argument  consisting of `;' is encountered.  The string `{}'
              is replaced by the current file name being processed  everywhere
              it occurs in the arguments to the command, not just in arguments
              where it is alone, as in some versions of find.  Both  of  these
              constructions might need to be escaped (with a `') or quoted to
              protect them from expansion by the shell.  See the EXAMPLES sec‐
              tion for examples of the use of the -exec option.  The specified
              command is run once for each matched file.  The command is  exe‐
              cuted  in  the starting directory.   There are unavoidable secu‐
              rity problems surrounding use of the -exec  action;  you  should
              use the -execdir option instead.