views:

66

answers:

5

I have the following script:

  #!/bin/sh
  r=3
  r=$((r+5))
  echo r

However, I get this error:

Syntax error at line 3: $ unexpected.

I don't understand what I'm doing wrong. I'm following this online guide to the letter http://www.unixtutorial.org/2008/06/arithmetic-operations-in-unix-scripts/

A: 

It works for me (printing 8), if you change echo r to echo $r. What version of sh do you have installed? What unix distribution?

Ether
If it works for you, it's because your sh is bash, and bash is not strict about forbidding bash-specific extensions while running as sh
Daenyth
@Daenyth: yup you're right, `/bin/sh --version` prints `GNU bash, ...` for me.
Ether
A: 

You might want to try the following:

#!/bin/sh  
r=3  
r=$((r + 5))  
echo $r
Shynthriir
+3  A: 

This sounds fine if you're using bash, but $((r+5)) might not be supported if you're using another shell. What does /bin/sh point to? Have you considered replacing it with /bin/bash if it's available?

Bruno
That was exactly the issue. Thanks!
Waffles
+2  A: 

The shebang line is your problem. bash is not sh. Change it to #!/bin/bash and it will work. You'll also want echo $r instead of echo r.

Daenyth
A: 

For doing maths (including decimals/floats), you can use awkor bc/dc.

awk -vr="$r" 'BEGIN{r=r+5;print r}'

or

echo "$r+5" | bc
ghostdog74