What's the difference between ${varname} and $varname in a shell scripts

后端 未结 3 803
忘掉有多难
忘掉有多难 2020-12-02 02:00

I have a simple question but I wonder what is the difference between ${varname} and $varname ?

I use both but I don\'t see any difference w

3条回答
  •  被撕碎了的回忆
    2020-12-02 02:28

    Using {} in variable names helps get rid of ambiguity while performing variable expansion.

    Consider two variables var and varname. Lets see you wanted to append the string name to the variable var. You can't say $varname because that would result in the expansion of the variable varname. However, saying ${var}name would help you achieve the desired result.

    $ var="This is var variable."
    $ varname="This is varname variable."
    $ echo $varname
    This is varname variable.
    $ echo ${var}name
    This is var variable.name
    

    Braces are also required when accessing any element of an array.

    $ a=( foo bar baz )       # Declare an array
    $ echo $a[0]              # Accessing first element -- INCORRECT
    foo[0]
    $ echo ${a[0]}            # Accessing first element -- CORRECT
    foo
    

    Quoting from info bash:

       Any  element  of  an  array may be referenced using ${name[subscript]}.
       The braces are required to avoid conflicts with pathname expansion.
    

提交回复
热议问题