Bash脚本在第一个非零结果之后退出,即使在ENV中未设置-e
如果一行返回非零结果,我过去使用的每个系统都会继续我的简单bash脚本。一些新的UbuntuLTS14.x系统现在在第一次出现故障时退出。我曾经Bash脚本在第一个非零结果之后退出,即使在ENV中未设置-e,bash,exit,Bash,Exit,如果一行返回非零结果,我过去使用的每个系统都会继续我的简单bash脚本。一些新的UbuntuLTS14.x系统现在在第一次出现故障时退出。我曾经 echo $- 而e不出现在列表中。我还应该找什么 从评论中添加: $ declare -f command_not_found_handle command_not_found_handle () { if [ -x /usr/lib/command-not-found ]; then /usr/lib/command-no
echo $-
而e不出现在列表中。我还应该找什么
从评论中添加:
$ declare -f command_not_found_handle
command_not_found_handle ()
{
if [ -x /usr/lib/command-not-found ]; then
/usr/lib/command-not-found -- "$1";
return $?;
else
if [ -x /usr/share/command-not-found/command-not-found ]; then
/usr/share/command-not-found/command-not-found -- "$1";
return $?;
else
printf "%s: command not found\n" "$1" 1>&2;
return 127;
fi;
fi
}
在脚本中使用bash陷阱,请参见下面的bash脚本示例:
#!/usr/bin/bash
main() {
trap 'error_handler ${LINENO} $?' ERR
###### put your commands in the following
echo "START"
non_existent_command
echo "END"
}
error_handler() {
process="$0"
lastline="$1"
lasterr="$2"
printf 'ERROR: %s: line %s: last command exit status: %s \n' "$process" "$lastline" "$lasterr"
trap - ERR
exit 0
}
main
如果尝试启动不存在的命令(non\u existence\u command
,在本例中)或退出状态不同于0的命令,陷阱将激活包含退出命令exit 0
的error\u handler
功能。
在上述示例中,输出将为:
>START
>./new.sh: line 8: non_existent_command: command not found
>ERROR: ./new.sh: line 8: last command exit status: 127
请注意,“开始”是打印的,但“结束”不是。是否声明-f command_not_found_handle输出任何内容?是的,结果与预期的一样,我相信
command_not_found_handle(){if[-x/usr/lib/command not found];然后/usr/lib/command not found--“$1”;返回$?;否则如果[-x/usr/share/command not found/command not found];然后/usr/share/command not found/command not found--“$1”;return$?;else printf”%s:command not found\n“$1”1>&2;return 127;fi;fi}
因此,如果您试图使用任何无法找到的命令(其中一个脚本返回非零或两个脚本都找不到),您的脚本将退出。您的脚本退出时使用的退出代码是什么?在脚本中的什么点?set-x向您显示了什么?您还可以查看是否设置了错误陷阱。That应该显示在set-x
中。顺便说一下,不确定“in ENV”是什么意思。-e
标志不是环境的一部分。