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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:33:37  来源:igfitidea点击:

How do I echo a sum of a variable and a number?

linuxshellscripting

提问by Tom Brito

I have a variable x=7and 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

No need for expr, POSIX shell allows $(( ))for arithmetic evaluation:

不需要expr,POSIX shell 允许$(( ))进行算术评估:

echo $((x+1))

See §2.6.4

§2.6.4

回答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 exprcommand:

只需使用以下expr命令:

$ expr $x + 1
8

回答by orlp

We use exprfor 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 bcutility:

您还可以使用该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)) 相同