【问题标题】:Test to determine if git clone command succeeded测试以确定 git clone 命令是否成功
【发布时间】:2014-11-06 04:15:48
【问题描述】:

我尝试通过传递用户名、密码来克隆 git 存储库。那是成功的。

但我的意图是我想知道 git clone 命令是否执行。 如果没有,我想在 shell 脚本本身中处理此类错误。

我的工作 shell 脚本:

cd ..
git clone https://username:password@bitbucket.org/username/repositoryname.git
cd repositoryname
git checkout branchname1
cd ..
mv repositoryname newfoldername
git clone https://username:password@bitbucket.org/username/respositoryname.git
cd repositoryname
git checkout branchname2
cd ..
mv repositoryname newfoldername

如何在脚本中测试这些步骤是否成功?

【问题讨论】:

    标签: git bash bitbucket


    【解决方案1】:

    返回值存储在 $? 中。 0 表示成功,其他表示错误。

    some_command
    if [ $? -eq 0 ]; then
        echo OK
    else
        echo FAIL
    fi
    

    我没有用 git 尝试过,但我希望这能工作。

    【讨论】:

      【解决方案2】:
      if some_command
      then
        echo "Successful"
      fi
      

      示例

      if ! git clone http://example.com/repo.git
      then
        echo "Failed"
      else
        echo "Successful"
      fi
      

      How to detect if a git clone failed in a bash script

      【讨论】:

        【解决方案3】:

        这个应该可以(只要把你的脚本放在下面标有“---你的脚本在这里---”的地方):

        #!/bin/bash
        
        # call your script with set -e to stop on the first error
        bash <<EOF
        set -e
        --- your script here ---
        EOF
        
        # test status: I don't want this part to stop on the first error,
        # and that's why use the HERE document above to wrap a sub-shell for "set -e"
        if [ $? -eq 0 ]; then
          echo success
        else
          echo fail
        fi
        

        或者,可以将 HERE 文档替换为:

        (
          set -e
          --- your script here ---
        )
        

        【讨论】:

        • 感谢 Robin 为我的问题提供了如此好的解决方案。它现在对我的脚本工作正常。
        猜你喜欢
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-08
        • 2016-07-18
        • 1970-01-01
        • 2017-01-26
        相关资源
        最近更新 更多