When do we need curly braces around shell variables?

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

    The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.

    Classic Example 1) - shell variable without trailing whitespace

    TIME=10
    
    # WRONG: no such variable called 'TIMEsecs'
    echo "Time taken = $TIMEsecs"
    
    # What we want is $TIME followed by "secs" with no whitespace between the two.
    echo "Time taken = ${TIME}secs"
    

    Example 2) Java classpath with versioned jars

    # WRONG - no such variable LATESTVERSION_src
    CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar
    
    # RIGHT
    CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar
    

    (Fred's answer already states this but his example is a bit too abstract)

提交回复
热议问题