如何将 echo 的结果分配给 bash 脚本中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34532677/
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 assign the result of echo to a variable in bash script
提问by Remco
I'm a Linux newbie and have copied a bash script that extracts values from a XML. I can echo the result of a calculation perfectly, but assigning this to a variable doesn't seem to work.
我是 Linux 新手,复制了一个从 XML 中提取值的 bash 脚本。我可以完美地回应计算结果,但将其分配给变量似乎不起作用。
#!/bin/bash
IFS=$'\r\n' result=(`curl -s "http://xxx.xxx.xxx.xxx/smartmeter/modules" | \
xmlstarlet sel -I -t -m "/modules/module" \
-v "cumulative_logs/cumulative_log/period/measurement" -n \
-v "point_logs/point_log/period/measurement" -n | \
sed '/^$/d' `)
# uncomment for debug
echo "${result[0]}"*1000 |bc
gas=$(echo"${result[0]}"*1000 |bc)
echo "${result[0]}"*1000 |bc
Gives me the result I need, but I do not know how to assign it to a variable.
给了我我需要的结果,但我不知道如何将它分配给一个变量。
I tried with tick marks:
我试过刻度线:
gas=\`echo"${result[0]}"*1000 |bc\`
And with $(
与 $(
Can somebody point me in the right direction?
有人可以指出我正确的方向吗?
回答by Ijaz Ahmad Khan
If you want to use bc
anyway then
you can just use back ticks , why you are using the backslashes? this code works , I just tested.
如果您bc
无论如何都想使用,那么您可以只使用 back ticks ,为什么要使用反斜杠?这段代码有效,我刚刚测试过。
gas=`echo ${result[0]}*1000 | bc`
Use one space after echo
and no space around * operator
echo
在 * 运算符之后使用一个空格并且周围没有空格
回答by fedorqui 'SO stop harming'
There is no need to use bc
nor echo
. Simply use the arithmetic expansion $(( expression ))
for such operations:
没有必要使用bc
nor echo
。只需将算术扩展$(( expression ))
用于此类操作:
gas=$(( ${result[0]} * 1000))
This allows the evaluation of an arithmetic expression and the substitution of the result.
这允许计算算术表达式并替换结果。