Home > Blockchain >  ((h=h 1)) is syntax error in shell script but not at the terminal
((h=h 1)) is syntax error in shell script but not at the terminal

Time:09-28

enter image description hereI expect the value to be incremented but get the same value of h i.e. 9. When I tried this directly in terminal it's working fine but after writing in shell file value remains same. Please tell me how to increment using this method only. i=$((i 1)) is also working.

h=9
echo $h

((h=h 1))
echo $h

((h=h 8))
echo $h

CodePudding user response:

This is a difference between sh and bash.

The POSIX sh standard only requires h=$(( h 1 )) to work. It does not require (( h = h 1 )) to work.

Bash, however, supports (( h = h 1 )). If you write a script using this syntax, you need to run it in bash -- not in sh -- to operate correctly.

That means you should run bash yourscript instead of sh yourscript, and start the script with a shebang such as #!/usr/bin/env bash to tell it to use bash as its interpreter when run as an executable.

CodePudding user response:

Simply copy pasted your code and got the below mentioned error

-bash-4.2$ cat test1.sh 
#!/bin/bash

h=9

echo $h

((h=h 1))

((h=h 8)) echo $h
-bash-4.2$ ./test1.sh 
9
./test1.sh: line 9: syntax error near unexpected token `echo'
./test1.sh: line 9: `((h=h 8)) echo $h'
-bash-4.2$ 

That is because, your syntax is not the correct way to add two values. Have a read here for more details.

Added the required echo check and used correct syntax, and it gave the below result

-bash-4.2$ cat test1.sh 
#!/bin/bash

h=9

echo $h

h=$(($h   1))

echo $h

h=$(($h   8))

echo $h
-bash-4.2$ ./test1.sh 
9
10
18
-bash-4.2$

You can use expr too.

h=`expr $h   1`
  • Related