How to get the proper exit code from nohup How to get the proper exit code from nohup unix unix

How to get the proper exit code from nohup


If your shell script runs the process with:

nohup perl myscript.pl &

you more or less forego the chance to collect the exit status from nohup. The command as a whole succeeds with 0 if the shell forked and fails with 1 if the shell fails to fork. In bash, you can wait for the background process to die and collect its status via wait:

nohup perl myscript.pl &oldpid=$!...do something else or this whole rigmarole is pointless...wait $oldpidecho $?

The echoed $? is usually the exit status of the specified PID (unless the specified PID had already died and been waited for).

If you run the process synchronously, you can detect the different exit statuses:

(nohup perl myscript.plecho "PID $! exited with status $?" >&2) &

And now you should be able to spot the different exit statuses from nohup (eg try different misspellings: nohup pearl myscript.pl, etc).

Note that the sub-shell as a whole is run in the background, but the nohup is run synchronously within the sub-shell.


As my understanding, the question was how to get the command status when it was running in nohup. As my experiences it was very little chance that you were able to get the COMMAND exit status even when it failed right away. Most time you just got the 'nohup COMMAND &' exit status unless you wait or synchronize as Jonathan mentioned. To check the COMMAND status right after nohup, I use:

   pid=`ps -eo pid,cmd | awk '/COMMAND/ {print $1}'`  if [ -z $pid ]; then     echo "the COMMAND failed"  else     echo "the COMMAND is running in nohup"  fi