Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get both the process id and the exit code from a bash script?

Tags:

bash

shell

I need a bash script that does the following:

  • Starts a background process with all output directed to a file
  • Writes the process's exit code to a file
  • Returns the process's pid (right away, not when process exits).
  • The script must exit

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?

like image 315
Bob B Avatar asked Feb 13 '12 13:02

Bob B


People also ask

How do I find exit code in bash?

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.


1 Answers

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 
like image 119
William Pursell Avatar answered Oct 05 '22 20:10

William Pursell