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

2020-02-26 07:45发布

问题:

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?

回答1:

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

echo $((x+1))

See §2.6.4



回答2:

Try double parentheses:

$ x=7; echo $(($x + 1))
8


回答3:

You can also use the bc utility:

$ x=3;
$ echo "$x+5.5" | bc
8.5


回答4:

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



回答5:

Just use the expr command:

$ expr $x + 1
8


回答6:

We use expr for that:

echo `expr $x + 1`


回答7:

Try this way:

echo $(( $X + 1 ))


回答8:

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



回答9:

echo $((x+1)) also same result as echo $(($x+1))