Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we need curly braces around shell variables?

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?

like image 680
New User Avatar asked Jan 05 '12 19:01

New User


People also ask

When should curly brackets be used?

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).

What are {} used for in Bash?

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.

Why are curly braces needed for multi digit positional parameters?

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.


1 Answers

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:

  • expanding array elements, as in ${array[42]}
  • using parameter expansion operations, as in ${filename%.*} (remove extension)
  • expanding positional parameters beyond 9: "$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.

like image 151
5 revs, 4 users 50% Avatar answered Oct 15 '22 23:10

5 revs, 4 users 50%