Bash – make `find` return with a non-zero exit code if error occured

bashfindshell-script

Why am I seeing the following:

$ find  -not -exec bash -c 'foo' \; -quit
bash: foo: command not found
$ echo $?
0

This is a reduced version of the actual script I am using which I post at the end of the question (if you really want to know).

So the question is how do I make find execute a shell using exec bash -c on a bunch of find results and exit at the first one that fails and also return a non-zero exit code that I can inspect later in my script?

* actual script *

#!/usr/bin/env bash
find path-a path-b path-c \
  -iname build.xml -not -exec bash -c 'echo -n "building {} ..." && ant -f {} build && echo "success" || (echo "failure" && exit 1)' \; -quit
RESULT=$?
echo "result was $RESULT"

Best Answer

This would sort of do it:

#!/bin/bash
RESULT=0
while IFS= read -r -u3 -d $'\0' file; do
        echo -n "building $file ..."
        ant -f "$file" build &&
           echo "success" ||
           { echo "failure" ; RESULT=1 ; break; }
done 3< <(find path-a path-b path-c  -print0)

echo "result was $RESULT"

Note that it mixes find with a bash loop as showed here.

It does not use $? but instead it directly uses the variable $RESULT.

If everything goes fine $RESULT is 0, else it is 1. The loop breaks as soon as an error is encountered.

It should be hopefully safe against malicious file names (because of the use of -print0).