When do we need curly braces around shell variables?

后端 未结 7 1221
春和景丽
春和景丽 2020-11-22 01:39

In shell scripts, when do we use {} when expanding variables?

For example, I have seen the following:

var=10        # Declare variable

         


        
7条回答
  •  时光取名叫无心
    2020-11-22 02:07

    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.

提交回复
热议问题