bash 从脚本调用时,curl 返回 HTTP 代码 503
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24803320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
curl return HTTP code 503 when called from a script
提问by PierreF
I'm try to call some REST API and get the resulting HTTP code using curl
. If in a terminal I type :
我尝试调用一些 REST API 并使用curl
. 如果在终端中输入:
curl -s -o /dev/null -I -w '%{http_code}' -X POST 'http://localhost/gitlab/api/v3/projects?private_token=my_private_token&name=blabla' -H 'Content-Length: 0'
It works and return me the HTTP code 201
("created"). Now I try to use this command in a bash script replacing a part of the url with variable:
它工作并返回 HTTP 代码201
(“创建”)。现在我尝试在 bash 脚本中使用此命令,用变量替换 url 的一部分:
echo "Enter base URL :"
read gitlab_url # Here I type 'http://localhost/gitlab', to generate the same URL as in first code snippet
code_status=$(curl -s -o /dev/null -I -w '%{http_code}' -X POST '$gitlab_url/api/v3/projects?private_token=my_private_token&name=blabla' -H 'Content-Length: 0')
echo "$code_status"
And then it returns me the HTTP code 503
("Service Unavailable"). To see if there is any differences between the "hard coded" URL and the generated one, I do :
然后它返回给我 HTTP 代码503
(“服务不可用”)。要查看“硬编码” URL 和生成的 URL 之间是否存在任何差异,我执行以下操作:
echo "curl -s -o /dev/null -I -w '%{http_code}' -X POST '$gitlab_url/api/v3/projects?private_token=my_private_token&name=blabla' -H 'Content-Length: 0'"
# Output :
curl -s -o /dev/null -I -w '%{http_code}' -X POST 'http://localhost/gitlab/api/v3/projects?private_token=my_private_token&name=blabla' 'Content-Length: 0'
And if I execute this in a terminal directly, it works and return me 201
. So: why do this command fails if I use it in a script ? Is there anything I missed ?
如果我直接在终端中执行它,它会工作并返回 me 201
。所以:如果我在脚本中使用这个命令为什么会失败?有什么我错过的吗?
回答by PierreF
It was a proxy problem. If I use curl -v ....
I can see the following output:
这是一个代理问题。如果我使用,curl -v ....
我可以看到以下输出:
When curl
is typed directly in terminal I have :
什么时候curl
直接在终端中输入我有:
* About to connect() to localhost port 80 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
And when I used it into a bash script I get :
当我将它用于 bash 脚本时,我得到:
* About to connect() to proxy proxy.my.company port xxx (#0)
* Trying xx.xx.xx.xx... connected
* Connected to proxy.my.company (xx.xx.xx.xx) port xxx (#0)
So to fix it I added this in the top of my script :
所以为了修复它,我在脚本的顶部添加了这个:
export no_proxy=localhost,127.0.0.1
export http_proxy=""
I am very surprised to have to do this, because I already have an environment var no_proxy
who already reference localhost
and 127.0.0.1
我很惊讶必须这样做,因为我已经有一个环境变量no_proxy
已经引用localhost
和127.0.0.1
回答by paq
Try to run it as bash -x script.sh
.
尝试将其作为bash -x script.sh
.