bash 在 Shell 脚本中将值存储到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30528518/
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
Store value to variable in Shell script
提问by Sivailango
"$emails" has the array of values, i want to parse the values from it, To do it, i am using the jq. if i do below command
“$emails”具有值数组,我想从中解析值,为此,我正在使用jq。如果我执行以下命令
echo "$emails" | ./jq '.total_rows'
i could get the value i.e 4, i want to store the returned results into some variable,
我可以得到值,即 4,我想将返回的结果存储到某个变量中,
total_rows="$emails" | ./jq '.total_rows'
but total_rows has no value.
但 total_rows 没有价值。
echo $total_rows
How do store the returned result into variable?
如何将返回的结果存储到变量中?
回答by Nidhoegger
You have to use the right quotation, like this:
你必须使用正确的引用,像这样:
total_rows=`echo "$emails" | ./jq '.total_rows'`
The `` will execute the command and give total_rows
the value of it, so whatever would be the output of
`` 将执行命令并给出total_rows
它的值,所以无论输出是什么
echo "$emails" | ./jq '.total_rows'
will so be stored in total_rows
.
将因此存储在total_rows
.
As mentioned in the comments by Tom Fenech, it is better to use $()
for command substitution. It provides a better readability. So what you can do is:
正如 Tom Fenech 在评论中提到的,最好使用$()
命令替换。它提供了更好的可读性。所以你可以做的是:
total_rows=$(echo "$emails" | ./jq '.total_rows')