Force exit status if file not found

Cameron Simpson cs at zip.com.au
Fri Mar 11 00:22:24 UTC 2011


On 07Mar2011 16:34, Kevin Martin <kevintm at ameritech.net> wrote:
| Strangely enough, if I'm in a directory and do a "find . -name e" (where e doesn't exist) I get *no* failed message and an exit code
| of 0.  I find that a bit odd as I would think that "find e" and "find . -name e" would be the same thing.  Perhaps that's something
| to do with the bash shell?

No, it just means that find has successfully searched your directory and
encountered no errors. Something like a directory it could not search
etc would evince a non-zero status.

One approach might be like this:

  find the-dir -name e >find.output
  if [ -s find.output ]
  then
    echo file found
  else
    echo file no found
  fi

Of course, you will often want to check that exactly one file was found,
etc. For example:

  nfiles=`wc -l <find.output`
  case $nfiles in
    0)  echo nothing found ;;
    1)  the_file=$(<find.output)
        echo found $the_file
        ;;
    *)  echo $nfiles files found
        ;;
  esac

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

We now return you to the previously scheduled counter-steering flame-fest
and under-clothing auction, after a few words about your sponsor, the DoD.
        - Denis McKeon <galway at chtm.eece.unm.edu>


More information about the users mailing list