bash 减去两个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21260698/
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
Subtract Two Variables
提问by Dustin Cook
I have a bash script, which cuts some timestamps down into the form SS.sss
and stores this in a variable:
我有一个 bash 脚本,它把一些时间戳削减到表单中SS.sss
并将其存储在一个变量中:
s1=$(echo $t1 | cut -c7-)
s2=$(echo $t2 | cut -c7-)
I would like to subtract $s2
from $s1
(and store as $s3
) but I cannot get expr
to work - is there another option?
我想$s2
从$s1
(并存储为$s3
)中减去,但我无法expr
上班 - 还有其他选择吗?
回答by Noctua
You can do most bash calculations like this:
您可以像这样进行大多数 bash 计算:
s3="$((s2 - s1))"
Those are limited to basic operations on integers, if I recall correctly, so things like
如果我没记错的话,这些仅限于对整数的基本操作,所以像
s3="$(echo "$s2 - $s1" | bc)"
might be better.
可能会更好。
回答by chepner
expr
only handles integer arithmetic. You can use bc
:
expr
只处理整数算术。您可以使用bc
:
s3=$(echo "$s1 - $s2" | bc)