bash shell 脚本中的负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20981525/
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
Negative number in bash shell scripting
提问by kwasbob
I need some help with a bash mathematical expression script. I need the expression below to be a negative 2 to the power of 63 but I have tried all sorts of combinations from "", '', (()) and even keeping the positive value but multiplying it by -1 but I can't seem to get the syntax right.
我需要一些有关 bash 数学表达式脚本的帮助。我需要下面的表达式是 2 的 63 次方的负数,但我已经尝试了 "", '', (()) 的各种组合,甚至保持正值但乘以 -1 但我可以'似乎语法正确。
Original expression:
原文表达:
kw=`expr 2^63 | bc`
gives me 9223372036854775808 (which is correct) but I need to get a -9223372036854775808.
给了我 9223372036854775808(这是正确的),但我需要得到 -9223372036854775808。
I want to be able to do a kw=expr -2^63 | bc
to get a negative results but it's not as straight-forward as I'd hoped. Hence my numerous attempts of different permutations to the expression.
我希望能够执行 kw=expr -2^63 | bc
以获得负面结果,但这并不像我希望的那样直接。因此,我多次尝试对表达式进行不同的排列。
Any help will be very appreciated.
任何帮助将不胜感激。
回答by janos
Here you go:
干得好:
$ kw=$(echo -2^63 | bc)
$ echo $kw
-9223372036854775808
UPDATE
更新
@DigitalTraumais right, if you're in bash
, then using a bash here stringis better (one less process, more efficient):
@DigitalTrauma是对的,如果你在bash
,那么在这里使用bash 字符串更好(少一个过程,更高效):
kw=$(bc <<< -2^63)
回答by Digital Trauma
Since this is bash, you don't even need the echo
; you can use a bash here stringinstead:
由于这是bash,您甚至不需要echo
; 您可以在此处使用bash 字符串:
$ kw=$(bc <<< -2^63)
$ echo $kw
-9223372036854775808