bashshellsyntaxcurly-bracesvariable-expansion

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?


Solution

  • 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:

    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.