Search code examples
bashexit-code

How to write process ID and get exit code of the next to last command


I want to run a command, write the process id instantly to a file when the command started and afterwards get the exit status of the command. This means, while the process id has to be written instantly, I want the exit status only when the initial command has finished.

The following statement will unfortunately run the command, write the process id instantly but it won't wait for the command to be finished. Furthermore I will only get the exit status of the echo command, not of the initial command

command in my case is rdiff-backup.

How do I need to modify the statement?

<command> & echo $! > "/pid_file"
RESULT=$?
if [ "$RESULT" -ne "0" ]; then
  echo "Finished with errors"
fi

Solution

  • You need to wait on the background process to get its exit status:

    _command_for_background_ & echo $! > pid_file
    : ... do other things, if any ...
    #
    # it is better to grab $? on the same line to prevent any
    # future modifications inadvertently breaking the strict sequence
    #
    wait $(< pid_file); child_status=$?
    if [[ $child_status != 0 ]]; then
      echo "Finished with errors"
    fi