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-开发者_如何学Coperations-in-unix-scripts/
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?
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
.
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?
You might want to try the following:
#!/bin/sh
r=3
r=$((r + 5))
echo $r
For doing maths (including decimals/floats), you can use awk
or bc/dc
.
awk -vr="$r" 'BEGIN{r=r+5;print r}'
or
echo "$r+5" | bc
精彩评论