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

后端 未结 3 802
忘掉有多难
忘掉有多难 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:17

    The distinction becomes important when something follows the variable:

    text="House"
    plural="${text}s"
    

    Without the braces, the shell would see texts as variable name which wouldn't work.

    The braces are also necessary when you use the extended syntax to specify defaults (${name-default}), display errors when undefined (${name?error}), or pattern substitution (see this article for other patterns; it's for BASH but most work for KSH as well)

    > echo $name-default
    -default
    > echo ${name-default}
    default
    

    Related:

    • Parameter Substitution in Korn-/POSIX-Shell

提交回复
热议问题