在shell脚本开头加上set -o pipefail
是什么意思?
man bash
说:
pipefail
如果设置,则管道的返回值是退出状态为非零的最后一个(最右边的)命令的值,如果管道中所有命令都成功退出,则返回零。此选项默认处于禁用状态。
这里的“管道”指的是:
command1 | command2 | command3
如果没有使用 pipefail
,管道的返回值就是管道中最后一个命令的退出状态码,无论之前的命令是否失败。
举例:
$ grep ^root /etc/passwd | cut -f 5 -d :
System Administrator
$ echo $?
0
$ grep ^nonexistant_user /etc/passwd | cut -f 5 -d :
$ echo $?
0
$ set -o pipefail
$ grep ^nonexistant_user /etc/passwd | cut -f 5 -d :
$ echo $?
1
pipefail
? - User123grep
- 如果没有找到,则返回1。但我想知道是否(统计上)默认更常见的是通过默认方式检测失败,而不是通过最后一个命令中的0来“吞没”它(特别是在脚本中)。个人而言,我在所有脚本中都启用了它,并通过显式检查退出代码来解决问题。我认为启用pipefail
是更明智的默认值。 - uvsmtidset -euo pipefail
会在子进程失败、尝试使用未设置的变量或管道失败时退出。 - NeilG