gpt4 book ai didi

git - 如何从git ls-remote捕获错误代码?

转载 作者:行者123 更新时间:2023-12-03 08:30:47 25 4
gpt4 key购买 nike

有时,我的“git ls-remote”语句通过HTTP返回401未经授权状态,但并非总是如此。如何在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

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

最佳答案

您可以通过/tmp/TSTRET将其重定向到文件,例如2>/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

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

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

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

如果要查看产生的错误,可以将 cat插入 if块:
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捕获错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com