Shell – find -exec exit 1 \; Doesn’t work neither does find -exec sh -c exit 1 \;

execfindshell

Using Enterprise Linux 5/6, Bash 4.x I want this type of logic:

# IF temp file exists, exit because we are restarting already     
find /tmp/restarting_server -mmin -10 -exec exit 1

lsof -i TCP:1234 || declare Server_is_down=TRUE
    if ! [ -z $Server_is_down ]; then restart_server
    fi
# Restart Server Function
restart_server() {
    touch /tmp/restarting_server 
    service server restart
    rm -f /tmp/restarting_server 
}

The problem is find's -exec doesn't like builtins it seems. I know I can do an if then statement to check for the file and exit there, but I want to know how to do this in a find -exec (or I'd settle for a good xargs solution).

Best Answer

while [ -f /tmp/restarting_server ] ; do {
    [ $((i=i+1)) -ge 10 ] && exit 1
    sleep 1 
} ; done

You dont need find if you know already the exact filename, pathname, and conditions under which a file should be acceptably found.

So the other problem - exiting your script from your -exec statement - is maybe not the problem you consider it to be. find doesn't build in an option for killing its parent shell because the shell already provides it.

find … -exec sh -c kill\ $$ \;

Consider also that you can use this construct for signalling based on existing paths even if you're not certain before hand where they'll be:

trap 'stuff to do' USR1    
… #later… 
find … -exec sh -c kill\ -USR1\ $$ \;

And this opens a lot of other options to you as well:

find … -exec sh -c exec… 

EDIT:

I've just thought of other options involving parameter expansion to make your shell exit without find's -exec at all that could be used in other ways:

hold_file="$(find . -name file)"
${hold_file:+false} : || exit 1

or

N= ; hold_file="$(find . -name file)"
${hold_file:+${N:?lock file remains, exiting...}}

Both of these will only cause an exit if the variable to which you assign find's stdout is neither null or unset. And of course, should you desire to fail based on an empty find, you can do the same with :- instead of :+ and omitting the $Null value variable entirely.

Or just to alter find's exit status:

$(find . -name file -exec echo false \; ) : || exit 1
Related Question