When do we need curly braces around shell variables?

后端 未结 7 1102
春和景丽
春和景丽 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:17

    Curly braces are always needed for accessing array elements and carrying out brace expansion.

    It's good to be not over-cautious and use {} for shell variable expansion even when there is no scope for ambiguity.

    For example:

    dir=log
    prog=foo
    path=/var/${dir}/${prog}      # excessive use of {}, not needed since / can't be a part of a shell variable name
    logfile=${path}/${prog}.log   # same as above, . can't be a part of a shell variable name
    path_copy=${path}             # {} is totally unnecessary
    archive=${logfile}_arch       # {} is needed since _ can be a part of shell variable name
    

    So, it is better to write the three lines as:

    path=/var/$dir/$prog
    logfile=$path/$prog.log
    path_copy=$path
    

    which is definitely more readable.

    Since a variable name can't start with a digit, shell doesn't need {} around numbered variables (like $1, $2 etc.) unless such expansion is followed by a digit. That's too subtle and it does make to explicitly use {} in such contexts:

    set app      # set $1 to app
    fruit=$1le   # sets fruit to apple, but confusing
    fruit=${1}le # sets fruit to apple, makes the intention clear
    

    See:

    • Allowed characters in Linux environment variable names
    0 讨论(0)
提交回复
热议问题