1

I'm trying to get the result of this call

TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
M=$?

Unfortunately, if /mydir/ doesn't exist, the result of $? is still '0', like there was not problem. I'd like to get something not '0' if find returns nothing.

How should I do?

Olivier Pons
  • 15,363
  • 26
  • 117
  • 213
  • the `-f` on your `rm` cmd is probably overriding any reporting on "error-ish" conditions. Good luck. – shellter Jul 19 '13 at 14:14
  • 2
    dupe of http://stackoverflow.com/questions/14923387/is-there-a-way-to-catch-a-failure-in-piped-commands which itself is dupe of http://stackoverflow.com/questions/1550933/catching-error-codes-in-a-shell-pipe – Carlos Campderrós Jul 19 '13 at 14:27

3 Answers3

2

due to link:

bash version 3 introduced an option which changes the exit code behavior of pipelines and reports the exit code of the pipeline as the exit code of the last program to return a non-zero exit code. So long as none of the programs following the test program report a non-zero exit code, the pipeline will report its exit code to be that of the test program. To enable this option, simply execute:

set -o pipefail

Then

TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
M=$?

will behave differently and recognize the error. See also a previous post on StackOverflow

Best,

Jack.

Community
  • 1
  • 1
Jakob Kroeker
  • 333
  • 2
  • 15
1

You can enable bash's pipefail option. Documentation (from help set):

 pipefail     the return value of a pipeline is the status of
              the last command to exit with a non-zero status,
              or zero if no command exited with a non-zero status

So, you could write as:

set -o pipefail
TMP=$(find /mydir/ -type f -mmin +1440 | xargs --no-run-if-empty rm -f)
M=$?
set +o pipefail

Also, why are you executing your find command inside $( ... )? If you don't want it to output errors, redirect STDERR to /dev/null, and also it is good practice to use the -r or --no-run-if-empty flag to xargs, to avoid running the command if it does not receive any input from the pipe.

Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
0

Check if a directory exists in bash:

if [ ! -d "mydir" ]; then
    exit 1 #or whatever you want, control will stop here
fi
TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
...
Osmium USA
  • 1,751
  • 19
  • 37