【问题标题】:How Do I Trap Error Code from git ls-remote?如何从 git ls-remote 捕获错误代码?
【发布时间】:2014-09-17 19:48:37
【问题描述】:

有时,我的“git ls-remote”语句会通过 HTTP 返回 401 Unauthorized 状态,但并非总是如此。如何在 Bash 中捕获此错误状态,以便在收到 HTTP 401 状态时不继续执行 Bash 脚本?

我正在这样做:

#!/bin/bash
GSERVER_STATUS=$(git ls-remote http://$GREMOTE/$GGROUP/$GREPO.git master | cut -f 1)
# rest of script goes here

大约 50% 的时间,它有效。剩下的 50%,我得到:

error: The requested URL returned error: 401 while accessing http://USER:PASS@SERVER/GROUP/REPO.git/info/refs

fatal: HTTP request failed

(当然,我更改了上面的行以保持我的登录凭据匿名。)

【问题讨论】:

    标签: git bash error-handling error-code


    【解决方案1】:

    你可以通过2>/tmp/TSTRET将它重定向到一个文件,比如/tmp/TSTRET,然后测试该文件是否为空,或者cat该文件并测试结果是否为NULL:

    #!/bin/bash
    GSERVER_STATUS=$(git ls-remote http://$GREMOTE/$GGROUP/$GREPO.git master 2>/tmp/TESTRET | cut -f 1)
    
    if [[ -n `cat /tmp/TESTRET` ]] 
    then exit;
    fi
    
    # rest of script goes here
    

    如果字符串cat /tmp/TESTRET 不为空,则-n 返回true,表示产生了错误消息。 [ ]test 的替代语法。

    注意:我尝试评估 GSERVER_STATUS 的值,但运气不佳。

    另外 -- 我在这里使用了反引号,但 $(cat /tmp/TESTRET) 在这种情况下也可以使用。

    如果您想查看产生的错误,可以在if 块中插入cat

    if [[ -n $(cat /tmp/TESTRET) ]]
    then
        cat /tmp/TESTRET;
        exit;
    fi
    

    最后,如果这个脚本是从其他脚本中调用的,对exit 的调用可能不是你想要的,所以你可以在里面嵌套你的附加代码以避免完全退出脚本:

    if [[ -n $(cat /tmp/TESTRET) ]]
    then
        cat /tmp/TESTRET;
    else
        # rest of script goes here
        # ...
    fi
    

    if [[ -z $(cat /tmp/TESTRET) ]]
    then
        # rest of script goes here
        # ...
    else
        cat /tmp/TESTRET;
    fi
    

    【讨论】:

    • 顺便说一句,一个旁注是在早期版本的 git 中似乎有一个小故障,它带有“git ls-remote”,它无意中返回了这个状态。一旦我切换到最新版本的 git,问题消失了。但是,根据您的建议调整我的 Bash 脚本是有意义的,因为您永远不知道我什么时候会遇到任何类型的错误,并且在发生这种情况时不需要在脚本中继续进行。
    猜你喜欢
    • 2021-04-20
    • 2018-06-30
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2014-12-11
    • 2011-09-27
    相关资源
    最近更新 更多