【问题标题】:How to detect if a git clone failed in a bash script如何检测 git clone 在 bash 脚本中是否失败
【发布时间】:2012-12-10 01:36:19
【问题描述】:

我如何判断 git clone 在 bash 脚本中是否有错误?

git clone git@github.com:my-username/my-repo.git

如果有错误,我只想简单地exit 1;

【问题讨论】:

    标签: linux git bash shell


    【解决方案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; }
    

    【讨论】:

    • 您可以考虑将 >&2 附加到 echo 命令以将其发送到 stderr 而不是 stdout。否则完美的答案。 +1
    • 调用exit时,不带args的exit和exit $?一样。
    • @jordanm - 除了这些例子,$?将通过调用echo 本身来修改。所以一个简单的exit 会以零状态退出。
    【解决方案2】:

    你可以这样做:

    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; }
    【解决方案3】:

    方法一:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2011-07-16
      相关资源
      最近更新 更多