Linux Shell Script - Difference between $(()) and (())

Asked

Viewed 97 times

8

I’m studying shell script and learned to use $(()) and (()) to make calculations. I understood the difference: while $(()) serves to make a calculation and return the result of it, (()) serves to create/change a variable, but without printing the result in the current shell. Examples:

echo $((10+10)) # imprimir 20
x=$((10+10))    # criar variável com valor 20
x=20; ((x++)); echo $x # imprimirá 21

That is, it seems to me that the operators $(()) and (()) are very similar, with the difference that the first returns the result of the calculation for the current shell, while the (()) just creates/alters a variable, but without returning anything to the current shell. But if they are so similar, why does $()) accept that I refer within it the names of variables with or without $, while (()) accepts only without siphon? Example:

x=1
echo $((x)) # funciona
echo $(($x)) # funciona
((x++)) # funciona
(($x++)) # dá erro, pois coloquei o $ no nome da variável

It may seem an unnecessary question, but I would like to understand this difference in behavior of the two operators, the first accept I call a variable of the two ways (with and without $) and the second not accept. Or are these two operators not as similar as I think they are?

1 answer

4


Paul, This is not an answer but a long comment

In a simplistic way:

$x       ---> val(x)
(( exp )) --> eval(exp)

That is your example in slow motion:

echo $((x))
:: echo val(eval(x)) ==> echo val(1) ==> echo 1 ==> 1

echo $(($x)) # funciona
:: echo $((1)) ==> echo val(eval(1)) ==> echo val(1) ==> 1

((x++)) # funciona
:: eval(x++) ==> ...alterou x para 2

(($x++)) # dá erro,
:: eval(val(x)++) ==> eval(1++) ==> erro(não posso incrementar "1")
  • Your comment made me understand the difference.

  • Thank you. Still the notation is unclear...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.