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.