bash 如何在bash中捕获curl的输出到变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25320928/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:37:14  来源:igfitidea点击:

How to capture the output of curl to variable in bash

bashshellcurl

提问by frazman

So, lets say I have the following command:

所以,假设我有以下命令:

curl -I http://google.com | head -n 1| cut -d $' ' -f2

This will capture the http status code?? Now I want to assign this to variable.. in bash script

这将捕获 http 状态代码?现在我想将它分配给变量.. 在 bash 脚本中

like output = "curl -I http://localhost:8088/tracks?key=9 | head -n 1| cut -d $' ' -f2" 

or something like that..

或类似的东西..

How do I assign the response of above command to a variable called output in bash? Thanks

如何将上述命令的响应分配给 bash 中名为 output 的变量?谢谢

回答by

You have two options. Surrounding the invocation in back ticks or $(), like so:

你有两个选择。用反勾号或围绕调用$(),像这样:

output=`curl -I http://google.com | head -n 1| cut -d $' ' -f2`
echo $output;
output=$(curl -I http://google.com | head -n 1| cut -d $' ' -f2)