Otorrinolaringologista -man Otorrinolaringologista -man - 1 year ago 106
Bash Question

Shell stop script if find command fails

Good day.

In a script of fine i have the following find command:

find -maxdepth 1 \! -type d -name "some_file_name_*" -name "*.txt" -name "*_${day_month}_*" -exec cp {} /FILES/directory1/directory2/directory3/ +

I want to know how to stop the script if the command does't find anything.

Answer Source

Use GNU xargs with the -r switch and a pipeline to ensure the output of find is passed to cp only if its non-empty.

find -maxdepth 1 \! -type d -name "some_file_name_*" -name "*.txt" -name "*_${day_month}_*" \
       | xargs -r I{} cp "{}" /FILES/directory1/directory2/directory3/

I{} is a place-holder for the output from the find command which is passed to cp,

The flags, -r and I{} represent the following according to the man xargs page,

-r, --no-run-if-empty
      If the standard input does not contain any nonblanks, do not run
      the command.  Normally, the command is run once even if there is
      no input.  This option is a GNU extension.

-I replace-str
       Replace occurrences of replace-str in the initial-arguments with
       names  read  from  standard input.  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download