在 bash if-condition 上使用 wait process-id 返回错误代码 1 以成功终止进程

Using wait process-id on a bash if-condition returning error code 1 for successful process termination

我对 successful/failure 条件下的 bash return 代码略知一二,但我在 wait 上的几个脚本的后台进程上做了一些试验 if 条件,我很惊讶地看到 return 错误代码的行为 0 表示成功,非零表示失败。

我的脚本:-

$cat foo.sh
#!/bin/bash
sleep 5

$cat bar.sh
#!/bin/bash
sleep 10

$cat experiment.sh 
./foo.sh &
pid1=$!

./bar.sh &
pid2=$!

if  wait $pid1 && wait $pid2
then
    echo "Am getting screwed here!"
else
    echo "Am supposed to be screwed here!"
fi

运行 脚本原样,输出为 Am getting screwed here! 而不是 Am supposed to be screwed here!

$./experiment.sh
Am getting screwed here!

现在修改脚本以在 foo.shbar.sh

中使用 exit 强制 return 退出代码
$cat foo.sh
#!/bin/bash
sleep 5
exit 2

$cat bar.sh
#!/bin/bash
sleep 10
exit 17

并且很惊讶地看到输出为

$./experiment.sh
Am supposed to be screwed here!

对于详细 post 表示歉意,但感谢您的帮助。 供参考的手册页:- http://ss64.com/bash/wait.html

这是正确的行为。 wait 的退出状态(当使用单个进程 ID 调用时)是正在等待的进程的退出状态。由于它们中至少有一个具有非零退出状态,因此 && 列表失败并采用 else 分支。

基本原理是命令只有一种方式 (0) 成功,但有多种方式(任何非零整数)失败。不要将 bash 对退出状态的使用与 0 为假和非零为真的标准布尔解释混淆。 shell if 语句检查其命令是否成功。