Answers:
首先,恐怕http://explainshell.com所提供的-o
选项解释并不完全正确。
鉴于这set
是一个bulit-in命令,我们可以help
通过执行来查看其文档help set
:
-o option-name
Set the variable corresponding to option-name:
allexport same as -a
braceexpand same as -B
emacs use an emacs-style line editing interface
errexit same as -e
errtrace same as -E
functrace same as -T
hashall same as -h
histexpand same as -H
history enable command history
ignoreeof the shell will not exit upon reading EOF
interactive-comments
allow comments to appear in interactive commands
keyword same as -k
monitor same as -m
noclobber same as -C
noexec same as -n
noglob same as -f
nolog currently accepted but ignored
notify same as -b
nounset same as -u
onecmd same as -t
physical same as -P
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
posix change the behavior of bash where the default
operation differs from the Posix standard to
match the standard
privileged same as -p
verbose same as -v
vi use a vi-style line editing interface
xtrace same as -x
如您所见,它-o pipefail
意味着:
管道的返回值是最后一个以非零状态退出的命令的状态,如果没有命令以非零状态退出,则返回零
但是它没有说: Write the current settings of the options to standard output in an unspecified format.
现在,它-x
已用于调试,如您所知,-e
它将在脚本中的第一个错误后停止执行。考虑这样的脚本:
#!/usr/bin/env bash
set -euxo pipefail
echo hi
non-existent-command
echo bye
使用时,该echo bye
行将永远不会执行,-e
因为
non-existent-command
它不会返回0:
+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
没有-e
最后一行将被打印,因为即使发生错误,我们也没有告诉Bash
自动退出:
+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
+ echo bye
bye
set -e
通常将其放在脚本的顶部,以确保在遇到第一个错误时将停止脚本-例如,如果下载文件失败,则提取该文件是没有意义的。
set -e
这将导致脚本错误终止。在您的示例中,它只是和的众多选择之一-uxo pipefail
。
e
参数。
0
在成功时返回,而在失败时返回非零,则-e
很有用,但在使用其他所有命令时都应谨慎使用。
set -uxo pipefail
)。