如何写入进程 ID 并获取倒数第二个命令的退出代码

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

我想运行一个命令,在命令启动时立即将进程ID写入文件,然后获取命令的退出状态。这意味着,虽然进程 ID 必须立即写入,但我只希望在初始命令完成时退出状态。

不幸的是,下面的语句会运行命令,立即写入进程ID,但不会等待命令完成。此外,我只会获得 echo 命令的退出状态,而不是初始命令的退出状态

command 在我的例子中是 rdiff-backup。

我需要如何修改声明?

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

您需要wait在后台进程上获取其退出状态:

_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