find
is a program of its own. The argument to -exec
is another command. When a command like find … -exec foo {} \;
is executed, the shell has find
as a subprocess, and each instance of foo
is a subprocess of find
. The command exit
exists only as a shell builtin, not as an independent command; an exit
program would be impossible since it would have to make its parent process exit.
The solution to your immediate problem is thus to make find
report whether it found a file or not, and make the shell exit if there was a match. You can't use the return status of find
, because it considers the absence of any match to be a success reason. Instead, test the output.
if [ -n "$(find /tmp/restarting_server -mmin -10)" ]; then exit; fi
Here, the file should be a regular file if it exists at all. However, in general, the file could be a directory, in which case find
would traverse it. So tell find
to stop when it finds a match.
if [ -n "$(find /tmp/restarting_server -mmin -10 -prune)" ]; then exit; fi
However, the resulting script is not reliable. You are not implementing a lock correctly. If two instances of the script start at almost the same time, it's possible to have, for example:
- Script 1 starts, sees no
restarting_server
file, and proceeds merrily.
- Script 2 starts, sees no
restarting_server
file, and proceeds merrily.
- Script 1 sees that the server is down and decides to restart it.
- Script 2 sees that the server is down and decides to restart it.
- Script 1 creates
/tmp/restarting_server
.
- Script 2 updates the timestamp on
/tmp/restarting_server
.
- Script 1 calls
service server restart
.
- Script 2 calls
service server restart
.
- Script 1 removes
/tmp/restarting_server
.
- Script 2 calls
rm -f /tmp/restarting_server
which does nothing.
Call flock
to implement proper locking.
(
lsof -i TCP:1234 >/dev/null ||
service server restart
) 3>/var/lock/maybe_restarting_server
You don't need a timeout to invalidate the lock across reboots, since the locking is held in-memory.
find
command or the script itself?find
's exit status, scroll down to the near the end ofman find
: "find exits with status 0 if all files are processed successfully,greater than 0 if errors occur." Not finding a match is not considered an error because the command actually ran correctly, it simply had no results. You'll get an error if you try searching in a directory that does not exist for example:find /hahagd/ ; echo $?
.find -exec
is running in a separate subshell and has no knowledge of the script. The way to exit is what l0b0 and devnull have suggested.