Bash检查脚本是否成功运行(退出代码不工作)

Bash检查脚本是否成功运行(退出代码不工作),bash,shell,Bash,Shell,我有以下bash脚本: echo one echo two cd x echo three 它在第3行失败,因为没有名为x的目录。但是,在运行脚本之后,当我执行$?时,返回0,即使脚本有错误。如何检测脚本是否成功运行?您应该以exit语句结束 echo one echo two cd x exitCode=$? echo three exit $exitCode; 然后 一, 检查脚本语句中目录存在的条件: [ -d x ] && cd x || { echo "no suc

我有以下bash脚本:

echo one
echo two
cd x
echo three

它在第3行失败,因为没有名为
x
的目录。但是,在运行脚本之后,当我执行
$?
时,返回0,即使脚本有错误。如何检测脚本是否成功运行?

您应该以exit语句结束

echo one
echo two
cd x
exitCode=$?
echo three
exit $exitCode;
然后

一,


检查脚本语句中目录存在的条件:

[ -d x ] && cd x || { echo "no such directory"; exit 1; }
或将
set-e
放在shebang行之后:

#!/bin/bash
set -e
echo one
echo two
cd x
echo three

您想在出现第一个错误时立即退出还是继续运行脚本中的其他行?
-e
是我想要的选项!
#!/bin/bash
set -e
echo one
echo two
cd x
echo three