I need a bash script that does the following:
I can get the pid but not the exit code:
$ executable >>$log 2>&1 & pid=`jobs -p`
Or, I can capture the exit code but not the pid:
$ executable >>$log; # blocked on previous line until process exits echo $0 >>$log;
How can I do all of these at the same time?
Checking Bash Exit Code Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.
The pid is in $!
, no need to run jobs
. And the return status is returned by wait
:
$executable >> $log 2>&1 & pid=$! wait $! echo $? # return status of $executable
EDIT 1
If I understand the additional requirement as stated in a comment, and you want the script to return immediately (without waiting for the command to finish), then it will not be possible to have the initial script write the exit status of the command. But it is easy enough to have an intermediary write the exit status as soon as the child finishes. Something like:
sh -c "$executable"' & echo pid=$! > pidfile; wait $!; echo $? > exit-status' &
should work.
EDIT 2
As pointed out in the comments, that solution has a race condition: the main script terminates before the pidfile is written. The OP solves this by doing a polling sleep loop, which is an abomination and I fear I will have trouble sleeping at night knowing that I may have motivated such a travesty. IMO, the correct thing to do is to wait until the child is done. Since that is unacceptable, here is a solution that blocks on a read until the pid file exists instead of doing the looping sleep:
{ sh -c "$executable > $log 2>&1 &"' echo $! > pidfile echo # Alert parent that the pidfile has been written wait $! echo $? > exit-status ' & } | read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With