make find fail when nothing was found

5,193

Solution 1

If your grep supports reading NUL-delimited lines (like GNU grep with -z), you can use it to test if anything was output by find:

find /some/path -print0 | grep -qz .

To pipe the data to another command, you can remove the -q option, letting grep pass on the data unaltered while still reporting an error if nothing came through:

find /some/path -print0 | grep -z . | ...

Specifically, ${PIPESTATUS[1]} in bash should hold the exit status of grep.

If your find doesn't support -print0, the use grep without -z and hope that newlines in filenames don't cause problems:

find ... | grep '^' | ...

In this case, using ^ instead of . might be safer. If output has consecutive newlines, ^ will pass them by, but . won't.

Solution 2

You ask specifically for a return code... which I don't see in options. But this is how I solved it (because grep -z is not on Mac port):

Gives code 0 if 1 line was found

test 1 == `find */.kitchen/ -name private_key | wc -l`

So...

if [ 0 == `find */.kitchen/ -name my-file.txt | wc -l` ] ; then
   echo "Nothing found"; exit;
fi

Also, as a generic solution, this might be useful:

Check if pipe is empty and run a command on the data if it isn't

Share:
5,193

Related videos on Youtube

XZS
Author by

XZS

Updated on September 18, 2022

Comments

  • XZS
    XZS almost 2 years

    When find is invoked to find nothing, it still exits with code 0. Is there a way to make it return an exit code indicating failure when no file was found?

    • Admin
      Admin about 9 years
      My grep is gnu grep so it supports this nice idea. Unfortunately, I also need the find output to be piped somewhere and I cannot replace the pipe with -exec.
    • Admin
      Admin about 9 years
      I'm making something.
    • Admin
      Admin about 9 years
      @XZS you can skip the -q, then grep will simply pass through the data, while still breaking the pipeline and reporting a failure if nothing comes through.
    • Admin
      Admin about 9 years
      @muru A do-nothing grep guarding the pipe, very elegant. Turn this into an answer and it will be accepted.
  • CherryDT
    CherryDT over 6 years
    Grep's -z is a GNU extension. Do you have something for more Posixy?