In shell scripts, when do we use {}
when expanding variables?
For example, I have seen the following:
var=10 # Declare variable echo "${var}" # One use of the variable echo "$var" # Another use of the variable
Is there a significant difference, or is it just style? Is one preferred over the other?
Curly brackets are rarely used in prose and have no widely accepted use in formal writing, but may be used to mark words or sentences that should be taken as a group, to avoid confusion when other types of brackets are already in use, or for a special purpose specific to the publication (such as in a dictionary).
Parameter expansion. Here the braces {} are not being used as apart of a sequence builder, but as a way of generating parameter expansion. Parameter expansion involves what it says on the box: it takes the variable or expression within the braces and expands it to whatever it represents.
The reason the braces are needed to access elements beyond element 9 in most POSIX-like shells is because the POSIX standard says so. A positional parameter is a parameter denoted by the decimal value represented by one or more digits, other than the single digit 0.
In this particular example, it makes no difference. However, the {}
in ${}
are useful if you want to expand the variable foo
in the string
"${foo}bar"
since "$foobar"
would instead expand the variable identified by foobar
.
Curly braces are also unconditionally required when:
${array[42]}
${filename%.*}
(remove extension)"$8 $9 ${10} ${11}"
Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg
, where it's not visually obvious that the underscore becomes part of the variable name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With