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?
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?
No need for expr
, POSIX shell allows $(( ))
for arithmetic evaluation:
echo $((x+1))
See §2.6.4
Try double parentheses:
$ x=7; echo $(($x + 1))
8
You can also use the bc
utility:
$ x=3;
$ echo "$x+5.5" | bc
8.5
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
Just use the expr
command:
$ expr $x + 1
8
We use expr
for that:
echo `expr $x + 1`
Try this way:
echo $(( $X + 1 ))
$ 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.
echo $((x+1)) also same result as echo $(($x+1))