我知道调试脚本的主要方法是添加-x
到 shabang ( #!/bin/bash -x
)。
我最近遇到了一种新方法,set -euxo pipefail
在 shabang 下添加,如下所示:
#!/bin/bash
set -euxo pipefail
Run Code Online (Sandbox Code Playgroud)
两种调试方式的主要区别是什么?有时您会更喜欢一个吗?
作为一个大一新生,读到这里,我无法得出这样的结论。
Ark*_*zyk 25
首先,恐怕对http://explainshell.com 提供的-o
选项的解释并不完全正确。
鉴于这set
是一个内置命令,我们可以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
Run Code Online (Sandbox Code Playgroud)
如您所见,-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
Run Code Online (Sandbox Code Playgroud)
该echo bye
行在使用时永远不会执行,-e
因为
non-existent-command
不返回 0:
+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
Run Code Online (Sandbox Code Playgroud)
没有-e
最后一行将被打印,因为即使发生错误我们也没有告诉Bash
自动退出:
+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
+ echo bye
bye
Run Code Online (Sandbox Code Playgroud)
set -e
通常放在脚本的顶部,以确保在遇到第一个错误时停止脚本 - 例如,如果下载文件失败,则提取它没有意义。