【发布时间】:2012-12-10 01:36:19
【问题描述】:
我如何判断 git clone 在 bash 脚本中是否有错误?
git clone git@github.com:my-username/my-repo.git
如果有错误,我只想简单地exit 1;
【问题讨论】:
我如何判断 git clone 在 bash 脚本中是否有错误?
git clone git@github.com:my-username/my-repo.git
如果有错误,我只想简单地exit 1;
【问题讨论】:
以下是一些常见的形式。哪个是最好的选择取决于你做什么。您可以在单个脚本中使用它们的任何子集或组合,而不会造成不良风格。
if ! failingcommand
then
echo >&2 message
exit 1
fi
failingcommand
ret=$?
if ! test "$ret" -eq 0
then
echo >&2 "command failed with exit status $ret"
exit 1
fi
failingcommand || exit "$?"
failingcommand || { echo >&2 "failed with $?"; exit 1; }
【讨论】:
exit时,不带args的exit和exit $?一样。
echo 本身来修改。所以一个简单的exit 会以零状态退出。
你可以这样做:
git clone git@github.com:my-username/my-repo.git || exit 1
或者执行它:
exec git clone git@github.com:my-username/my-repo.git
后者将允许shell进程被克隆操作接管,如果失败则返回错误。您可以了解有关 exec here 的更多信息。
【讨论】:
exit 1?我试过:|| echo "ERROR message here" && exit 1 但它总是退出,即使成功。谢谢。
failingcommand || { echo message && exit 1; },因为&& 的绑定不强于||。然后你最好使用failingcommand || { echo message; exit 1; }
方法一:
git clone git@github.com:my-username/my-repo.git || exit 1
方法二:
if ! (git clone git@github.com:my-username/my-repo.git) then
exit 1
# Put Failure actions here...
else
echo "Success"
# Put Success actions here...
fi
【讨论】: