i have a unix script in which a command needs to be executed repeatedly but the command can be run next time only when the previous one have completed successfully. I searched for the command that can tell that the script has finished execution but i couldnt find it. I am new in the unix scripting and started to love unix scripting.
2 Answers
In order for a command to execute only after the previous one has succeeded, you need to write the two as:
command1 && command2
To have this in a loop with a single command, you will need to check the return status of each invocation and exit the loop if it's not successful; the shortest form should be something like:
while your_command; do :; done
You could also insert a sleep instead of the NOOP :.
4 Comments
sleep <seconds>; but most likely I misunderstood your comment...: should be fine.You need to store PID (process id) of your background command in some file, so that your script can check if its still running next time it is started. For example:
if [ ! "kill -0 $(</var/run/myscript-command.pid) 2>/dev/null 1>&2" ]; then
somecommand&
$CMD_PID = $!
echo $CMD_PID >/var/run/myscript-command.pid
fi
For this to work somecommand needs to daemonize itself. If it does not, then call it like:
nohup ./somecommand 0<&- &>/dev/null &
command1starts a background job even if you run it in the foreground? Is there any way to prevent that? For example, some daemons have an option like--interactiveto run in the foreground.