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

2020-02-26 07:35发布

I have a variable x=7 and I want to echo it plus one, like echo ($x+1) but I'm getting:

bash: syntax error near unexpected token `$x+1'

How can I do that?

9条回答
干净又极端
2楼-- · 2020-02-26 07:58
$ echo $(($x+1))
8

From 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.

查看更多
可以哭但决不认输i
3楼-- · 2020-02-26 08:00

Just use the expr command:

$ expr $x + 1
8
查看更多
倾城 Initia
4楼-- · 2020-02-26 08:05

Try this way:

echo $(( $X + 1 ))
查看更多
SAY GOODBYE
5楼-- · 2020-02-26 08:07

Try double parentheses:

$ x=7; echo $(($x + 1))
8
查看更多
不美不萌又怎样
6楼-- · 2020-02-26 08:12

try echo $(($x + 1))

I think that only works on some version of bash that is 3 or more..

echo `expr $x + 1`

would be another solution

查看更多
干净又极端
7楼-- · 2020-02-26 08:13

We use expr for that:

echo `expr $x + 1`
查看更多
登录 后发表回答