Linux 如何回显变量和数字的总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4750763/
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 do I echo a sum of a variable and a number?
提问by Tom Brito
I have a variable x=7
and I want to echo it plus one, like echo ($x+1)
but I'm getting:
我有一个变量x=7
,我想把它加一,就像echo ($x+1)
但我得到:
bash: syntax error near unexpected token `$x+1'
bash:意外标记“$x+1”附近的语法错误
How can I do that?
我怎样才能做到这一点?
采纳答案by SiegeX
回答by vmpstr
try echo $(($x + 1))
尝试回声 $(($x + 1))
I think that only works on some version of bash that is 3 or more..
我认为这仅适用于 3 或更多版本的 bash。
echo `expr $x + 1`
would be another solution
将是另一种解决方案
回答by chrisaycock
Just use the expr
command:
只需使用以下expr
命令:
$ expr $x + 1
8
回答by orlp
We use expr
for that:
我们expr
为此使用:
echo `expr $x + 1`
回答by Jason Plank
Try this way:
试试这个方法:
echo $(( $X + 1 ))
回答by miku
Try double parentheses:
试试双括号:
$ x=7; echo $(($x + 1))
8
回答by DVK
$ echo $(($x+1))
8
From man bash
:
来自man bash
:
Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$((expression))
The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic substitutions may be nested.
The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs.
算术展开
算术扩展允许对算术表达式求值并替换结果。算术展开的格式为:
$((expression))
该表达式被视为在双引号内,但括号内的双引号不会被特殊处理。表达式中的所有标记都经过参数扩展、字符串扩展、命令替换和引号删除。算术替换可以嵌套。
评估是根据下面在算术评估下列出的规则进行的。如果表达式无效,bash 会打印一条消息指示失败并且不会发生替换。
回答by Mansoor Siddiqui
You can also use the bc
utility:
您还可以使用该bc
实用程序:
$ x=3;
$ echo "$x+5.5" | bc
8.5
回答by tanangular
echo $((x+1)) also same result as echo $(($x+1))
echo $((x+1)) 结果与 echo $(($x+1)) 相同