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

25

那么,假设我有以下命令:

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

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

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

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


4
请使用反引号将命令括起来。 - Bohemian
@Bohemian:哎呀.. :) 谢谢 - frazman
1个回答

51

你有两个选择(参见这个 StackOverflow 回答这里):

  • 首选:将调用括在$()
  • 用反引号将调用括起来

注意:反引号已经过时了,推荐使用前一种方法。

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`
echo "$output";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接