Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use $(( )) to evaluate arithmetic expressions in ksh?

Tags:

unix

ksh

1) Should I use $(( )) if I operate on integers?

>typeset -i x=0
>typeset -i y=0
>typeset -i z=0
>y=$(($x+1))
>print $y
1
>z=$x+1
>print $z
1

As you can see there are correct results both in z and y.
Only in case if variable was not declared as integer there is difference:

>typeset j
>typeset k
>j=$(($x+1))
>print $j
1
>k=$x+1
>print $k
0+1

2) What is the difference between $(($x+1)) and $((x+1))?

print $(($x+1))
1
print $((x+1))
1

There is the same situation with let:

x=1
let x=$x+1
print $x
2
let x=x+1
print $x
3

like image 552
Volodymyr Bezuglyy Avatar asked Sep 15 '11 10:09

Volodymyr Bezuglyy


2 Answers

2) With $x expansion in $((..)), you can textually construct the expression:

NUM1=3
NUM2=5
NUM3=7
for OP1 in + - \* /; do
  for OP2 in + - \* /; do
    echo $((NUM1 $OP1 NUM2 $OP2 NUM3));
  done
done

obviously it wouldn't work with $((NUM1 OP1 NUM2)) etc.

The other possibility (without $) can be used to modify the variable:

X=0
Y=1
echo $((Y << (++X))) # prints 2, which is 1 << 1; increments X
echo $X # prints 1

For 1), I'd use $((..)) as it is POSIX, however, I don't think it matters in ksh.

like image 111
jpalecek Avatar answered Sep 28 '22 05:09

jpalecek


1) Should I use $(( )) if I operate on integers?

As with most things in programming, "it depends". If you think your code will be used on old unix systems where there is only the bourne shell, then that syntax will not work.

If you will always be in a totally modern environment, then the $(( ... )) syntax really makes the most sense as it allows for concise and 'C-language' like expressions.

Also, as others point out, for any numeric variables inside the $(( ... )), you can save typing and eliminate the leading '$'. ;-)

2) What is the difference between $(($x+1)) and $((x+1))?

As indicated in the previous paragraph, there is no difference, except that you had to type 1 fewer character.

Finally, I commend you on your approach to figuring things out on your own. Your small tests helped you prove these facts for yourself and is a method I wish more question posters here on S.O would learn to use! ;-).

You are on the right track to understanding how to improve your shell knowledge. If you don't know about the various debug tools available in the shell, see the 3rd paragraph in Using nohup to execute command very confused? , r.e. set -vx and PS4=....

I hope this helps.

like image 27
shellter Avatar answered Sep 28 '22 03:09

shellter