Inside which type of parenthesis (), (()), {}, [[ ]], $( ), $(( ))
should we use the dollar sign before the variable to expand it?
Asked
Active
Viewed 58 times
0

Caterina
- 775
- 9
- 26
-
Looks like an exam question – Arkadiusz Drabczyk Oct 04 '21 at 16:24
-
What have you tried? What research did you do? Isn't it easy to spawn a shell and test all combinations? – KamilCuk Oct 04 '21 at 16:27
-
Yes, of course I can try it myself. But I wanted to know if there was a logical reason behind it, or a rule. – Caterina Oct 04 '21 at 16:28
-
1I guess what I'm trying to say is if there's sort of a pattern of when to use them or not. – Caterina Oct 04 '21 at 16:29
-
The source of all rules is the POSIX shell command language specification. https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html – Charles Duffy Oct 04 '21 at 16:32
-
For those who marked this as duplicate... this question is not asking what do those parenthesis do, it's asking about how to deal with a variable inside those parenthesis... – Caterina Oct 04 '21 at 16:47
2 Answers
2
The arithmetic expansion is the one that doesn't need dollar sings, which means both ((...))
and $((...))
. But you don't need the dollar sign in other arithmetic contexts, either, e.g. in array indices.
arr=(a b c)
x=1
echo "${arr[x]}" # b
See "Arithmetic Evaluation" in man bash
.

choroba
- 231,213
- 25
- 204
- 289
1
It depends...
Try it yourself in a bash.
A big Country is in array number 4
$ array=(0 1 2 3 COUNTRY 5 6 7 8 9)
$ echo ${array[4]}
COUNTRY
And now lets expand it...
$ array=(0 1 2 3 $COUNTRY 5 6 7 8 9)
$ echo ${array[4]}
DE
...to a very little country.
But what should it be?
My personnel like...
$ array=(0 1 2 3 ${COUNTRY} 5 6 7 8 9)
$ echo ${array[4]}
DE
...better because it makes it clearer that ${COUNTRY}
is a Variable than a single Dollarsign ($
).

koyaanisqatsi
- 2,585
- 2
- 8
- 15