用你的话说:“ 每个命令都取决于每个先前的命令。如果任何命令失败,则整个脚本都应该失败 ”,我认为您不需要任何特殊功能来处理错误。
您所需要做的就是将命令与&&
operator和||
operator链接起来,这与您编写的内容完全相同。
例如,如果先前的任何命令中断,则此链将中断并打印“出问题了” (bash从左到右读取)
cd foo && rm a && cd bar && rm b || echo "something went wrong"
真实示例(我为真实演示创建了dir foo,文件a,目录栏和文件b):
gv@debian:/home/gv/Desktop/PythonTests$ cd foo && rm a && cd bar && rm bb || echo "something is wrong"
rm: cannot remove 'bb': No such file or directory
something is wrong #mind the error in the last command
gv@debian:/home/gv/Desktop/PythonTests$ cd foo && rm aa && cd bar && rm b || echo "something is wrong"
rm: cannot remove 'aa': No such file or directory
something is wrong #mind the error in second command in the row
最后,如果所有命令都已成功执行(退出代码0),则脚本继续运行:
gv@debian:/home/gv/Desktop/PythonTests$ cd foo && rm a && cd bar && rm b || echo "something is wrong"
gv@debian:/home/gv/Desktop/PythonTests/foo/bar$
# mind that the error message is not printed since all commands were successful.
要记住的重要一点是,如果前一个命令以代码0退出(对于bash表示成功),则执行&& next命令。
如果链中有任何命令出错,则命令/脚本/后面的内容|| 将被执行。
仅作记录,如果需要根据中断的命令执行不同的操作,则还可以使用经典脚本来执行此操作,方法是监视$?
报告上一命令的退出代码的值(如果命令成功执行,则返回零)或其他正数(如果命令失败)
例:
for comm in {"cd foo","rm a","cd bbar","rm b"};do #mind the error in third command
eval $comm
if [[ $? -ne 0 ]];then
echo "something is wrong in command $comm"
break
else
echo "command $comm executed succesful"
fi
done
输出:
command cd foo executed succesfull
command rm a executed succesfull
bash: cd: bbar: No such file or directory
something is wrong in command cd bbar
提示:您可以通过应用以下消息取消显示“ bash:cd:bbar:No such file ...”消息 eval $comm 2>/dev/null