开发者

I'm having trouble performing arithmetic expressions in UNIX

开发者 https://www.devze.com 2023-01-19 06:34 出处:网络
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 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 awkor bc/dc.

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

or

echo "$r+5" | bc
0

精彩评论

暂无评论...
验证码 换一张
取 消