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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:19:48  来源:igfitidea点击:

Subtract Two Variables

bashshellunix

提问by Dustin Cook

I have a bash script, which cuts some timestamps down into the form SS.sssand stores this in a variable:

我有一个 bash 脚本,它把一些时间戳削减到表单中SS.sss并将其存储在一个变量中:

s1=$(echo $t1 | cut -c7-)
s2=$(echo $t2 | cut -c7-)

I would like to subtract $s2from $s1(and store as $s3) but I cannot get exprto 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

expronly handles integer arithmetic. You can use bc:

expr只处理整数算术。您可以使用bc

s3=$(echo "$s1 - $s2" | bc)