如果一行返回非零结果,我过去使用的每个系统都会继续我的简单bash脚本.一些新的Ubuntu LTS 14.x系统现在在第一次失败时退出.我用了
echo $-
Run Code Online (Sandbox Code Playgroud)
并且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
}
Run Code Online (Sandbox Code Playgroud)
在脚本中使用 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
Run Code Online (Sandbox Code Playgroud)
如果您尝试启动不存在的命令(non_existent_command在示例中)或退出状态不为 0 的命令,陷阱将激活error_handler包含 exit 命令的函数exit 0。在上面的示例中,输出将是:
>START
>./new.sh: line 8: non_existent_command: command not found
>ERROR: ./new.sh: line 8: last command exit status: 127
Run Code Online (Sandbox Code Playgroud)
请注意,打印“START”但不打印“END”。