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
Try double parentheses:
$ x=7; echo $(($x + 1))
8
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
echo $((x+1)) also same result as 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.
No need for expr
, POSIX shell allows $(( ))
for arithmetic evaluation:
echo $((x+1))
See §2.6.4