如何在 bash 脚本中运行 curl 并将结果保存在变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42245271/
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
How to run curl in bash script and keep the result in a variable
提问by Elad Tabak
This should have been easy but for some reason it's not:
这应该很容易,但由于某种原因,它不是:
Trying to run a simple curl
command, get it's output, and do stuff with it.
尝试运行一个简单的curl
命令,获取它的输出,然后用它做一些事情。
cmd='curl -v -H "A: B" http://stackoverflow.com'
result=`$cmd | grep "A:"`
...
The problem - the header "A: B" is not sent.
问题 - 未发送标头“A:B”。
The execution of the curl command seems to ignore the header argument, and run curl twice - second time with "B" as host (which obviously fail).
curl 命令的执行似乎忽略了标头参数,并运行 curl 两次 - 第二次以“B”作为主机(显然失败)。
Any idea?
任何的想法?
回答by Blakey
Your problem here is that all you are doing on the first command is just setting cmd to equal a string.
你的问题是你在第一个命令上所做的只是将 cmd 设置为等于一个字符串。
Try using $(...)
to execute the actual command like so:
尝试使用$(...)
执行实际命令,如下所示:
cmd=$(curl -v -H "A: B" http://stackoverflow.com)
The result of this will be the actual output from with curl request.
这样做的结果将是来自 curl 请求的实际输出。
This has been answered many-times see here for example Set variable to result of terminal command (Bash)
这已被多次回答参见此处,例如将变量设置为终端命令的结果(Bash)
回答by Michael
Keep in mind that cURL debug output is redirected to STDERR - this is so you can pipe the output to another program without the information clobbering the input of the pipe.
请记住,cURL 调试输出被重定向到 STDERR - 这样您就可以将输出通过管道传输到另一个程序,而不会破坏管道输入的信息。
Redirect STDERR to STDOUT with the --stderr -
flag like so:
使用--stderr -
标志将 STDERR 重定向到 STDOUT,如下所示:
cmd="curl -s -v http://stackoverflow.com -H 'Test:1234' --stderr -"
result=`$cmd | grep "Test:"`
echo $result
./stackoverflow.sh
> 'Test:1234'