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