How is the echo sum of the sum of the variable and the number?

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

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

How can i do this?

+11
linux scripting shell
source share
9 answers

There is no need for expr , the POSIX shell allows $(( )) for arithmetic evaluation:

 echo $((x+1)) 

See & sect; 2.6.4

+26
source share

Try double parentheses:

 $ x=7; echo $(($x + 1)) 8 
+3
source share

You can also use the bc utility:

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

try echo $ (($ x + 1))

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

 echo `expr $x + 1` 

will be another solution

+1
source share

Just use the expr command:

 $ expr $x + 1 8 
0
source share

We use expr for this:

 echo `expr $x + 1` 
0
source share

Try as follows:

 echo $(( $X + 1 )) 
0
source share
 $ echo $(($x+1)) 8 

From man bash :

Arithmetic expansion

Arithmetic expansion allows you to evaluate the arithmetic expression and the substitution of the result. Format for arithmetic expansion:

  $((expression)) 

The expression is treated as if it were in a double quote, but the double quote inside the parentheses is not specially processed. All tokens in the expression undergo parameter expansion, line expansion, command substitution, and removal of quotes. Arithmetic substitutions can be nested.

The assessment is carried out in accordance with the indicated rules below under the ARIMETIC EVALUATION. If the expression is invalid, bash prints an error message and no substitution occurs.

0
source share

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

0
source share

Source: https://habr.com/ru/post/651313/


All Articles