获取后台进程/子shell的退出代码

获取后台进程/子shell的退出代码

我想知道以下之间是否有任何区别:

long_running.sh & 
pid=$!

(
  long_running.sh
) & 

pid=$!

在这两种情况下都会一致地捕获 pid,还是会有一些差异?

最终,我想通过以下方式捕获有意义的退出代码:

wait ${pid} || { echo "damn"; exit 1; };

答案1

一点测试表明我之前的评论是错误的:

$ cat long_running.sh 
#!/bin/bash
sleep 3
echo "long_running: $$"
pstree -ps $$
status=$((RANDOM % 2))
echo "exiting with status $status"
exit $status

$ ./long_running.sh
long_running: 6599
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(6599)───pstree(6601)
exiting with status 1

$ ( ./long_running.sh )
long_running: 6618
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(6618)───pstree(6621)
exiting with status 0

没有“中间人”shell,所以我认为 bash 会生成一个子 shell 并exec执行命令。

要捕获退出状态,您做了正确的事情

$ ( ./long_running.sh ) & pid=$!; wait $pid && echo ok || echo damn
[1] 7439
long_running: 7439
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(7439)───pstree(7441)
exiting with status 0
[1]+  Done                    ( ./long_running.sh )
ok

$ ( ./long_running.sh ) & pid=$!; wait $pid && echo ok || echo damn
[1] 7457
long_running: 7457
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(7457)───pstree(7461)
exiting with status 1
[1]+  Exit 1                  ( ./long_running.sh )
damn

相关内容