如何打印导致脚本失败的失败命令?

Ali*_*aka 4 bash command exit-status

我正在使用-e旗帜。

用法:

#!/bin/bash -e
Run Code Online (Sandbox Code Playgroud)

解释:

-e      Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status
Run Code Online (Sandbox Code Playgroud)

当脚本中的某个命令失败时,脚本退出并且不会继续执行其余命令,这正是我想要的。

但是,失败仅包含失败命令选择公开的信息。

有时失败的命令非常复杂,例如带有许多标头的卷曲。

如何打印失败的命令?我的意思是,在失败后立即。

我知道我可以使用-xbash 标志,但它会打印所有已执行的命令。我只想看看失败的那个。

roa*_*ima 5

您可以使用 atrap来识别失败的命令(及其行号)。这是一个例子

\n
#!/bin/bash -e\n# This script can be used to fail intentionally and exit\n\n# Declare an error handler\ntrapERR() {\n    ss=$? bc="$BASH_COMMAND" ln="$BASH_LINENO"\n    echo ">> Failing command is '$bc' on line $ln and status is $ss <<" >&2\n    exit $ss\n}\n\n# Arrange to call trapERR when an error is raised\ntrap trapERR ERR    \n\n# Start here\ndate\necho 'hello, world'\n#sleep rt    # Remove the leading comment to \necho 'all done'\nexit 0\n
Run Code Online (Sandbox Code Playgroud)\n

成功完成:

\n
23 Jan 2023 15:58:03\nhello, world\nall done\n
Run Code Online (Sandbox Code Playgroud)\n

去掉前面的注释sleep,以免引入错误

\n
23 Jan 2023 15:58:34\nhello, world\nsleep: invalid time interval \xe2\x80\x98rt\xe2\x80\x99\nTry 'sleep --help' for more information.\n>> Failing command is 'sleep rt' on line 12 and status is 1 <<\n
Run Code Online (Sandbox Code Playgroud)\n