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

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

>typeset -ix=0 >typeset -iy=0 >typeset -iz=0 >y=$(($x+1)) >print $y 1 >z=$x+1 >print $z 1 

As you can see, there are correct results in both z and y.
Only if the variable was not declared as an integer, there is a 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

+4
source share
3 answers

2) When expanding $x into $((..)) you can text build 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 this won't work with $((NUM1 OP1 NUM2)) etc.

Another possibility (without $ ) can be used to change a variable:

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

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

+1
source

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

As in most cases in programming, "it depends." If you think your code will be used on older unix systems where there is only a bourne shell, then this syntax will not work.

If you are always in a completely modern environment, the $(( ... )) syntax really makes the most sense, since it allows you to use compressed expressions and expressions like C.

Also, as others point out, for any numeric variables inside $(( ... )) you can save the input 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 less characters.

Finally, I thank you for your approach to understanding yourself. Your little tests helped you prove these facts for yourself and this is the method that I want more questions about posters here on SO learned to use! ;-).

You are on the right track to understand how to improve your shell knowledge. If you are not aware of the various debugging tools available in the shell, see the third paragraph in Using nohup to execute a very confusing command? , re set -vx and PS4=...

Hope this helps.

+1
source

2) $ x is expanded before calculating $ (()):

 x=1+ echo $(($x 1)) =>2 echo $((x 1)) =>syntax error when trying to make an operand from "1+" 
0
source

All Articles