如何在Bash脚本中检测Git克隆失败

26

如何在Bash脚本中判断git clone是否出错?

git clone git@github.com:my-username/my-repo.git
如果有错误,我只想简单地使用exit 1退出;
3个回答

35

以下是一些常见的表单。选择哪种最好取决于你做什么。你可以在单个脚本中使用它们的任何子集或组合,而不会出现不良样式。


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; }

你可以考虑在echo命令后添加">&2",将其发送到stderr而不是stdout。否则答案完美无缺。+1 - Nemo
1
在调用 exit 时,不带参数的 exitexit $? 是相同的。 - jordanm
@jordanm - 除了这些示例之外,$? 将被 echo 调用本身修改。因此,简单的 exit 将以零状态退出。 - Nemo

14

你可以这样做:

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的信息。


几乎可以工作,但是我该如何添加一个回显“ERROR message here”,然后运行exit 1?我尝试过:|| echo "ERROR message here" && exit 1,但它总是退出,即使成功了。谢谢。 - Justin
你需要使用 failingcommand || { echo message && exit 1; },因为 && 的优先级不如 ||。然后最好使用 failingcommand || { echo message; exit 1; } - Jo So

6

方法一:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接