Linux 如何将 bc 计算通过管道传输到 shell 变量中

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

how to pipe bc-calculation into shell variable

linuxshellvariablesbc

提问by Seb

I have a calculation on a Linux shell, something like this

我在 Linux shell 上有一个计算,类似这样

echo "scale 4;3*2.5" |bc

which gives me an result, now I like to pipe the result of this calculation into an Variable so that I could use it later in another command,

这给了我一个结果,现在我喜欢将这个计算的结果通过管道传输到一个变量中,以便我稍后可以在另一个命令中使用它,

piping into files work, but not the piping into variables

管道到文件工作,但不是管道到变量

echo "scale=4 ; 3*2.5" | bc > test.file

so in pseudo-codei'm looking to do something like this

所以在伪代码中我想做这样的事情

set MYVAR=echo "scale=4 ; 3*2.5" | bc ; mycommand $MYVAR

Any ideas?

有任何想法吗?

回答by Sven

 MYVAR=$(echo "scale 4;3*2.5" | bc)

回答by Erik

MYVAR=`echo "scale=4 ; 3*2.5" | bc`

Note that bash doesn't like non-integer values - you won't be able to do calculations with 7.5 in bash.

请注意,bash 不喜欢非整数值 - 您将无法在 bash 中使用 7.5 进行计算。

回答by bmk

You can do (in csh):

你可以做(​​在 csh 中):

set MYVAR=`echo "scale 4;3*2.5" |bc`

or in bash:

或在 bash 中:

MYVAR=$(echo "scale 4;3*2.5" |bc)