More on Variable Syntax

Before we show the many things you can do with shell variables, we have to point out a simplification we have been making: the syntax of $varname for taking the value of a variable is actually the simple form of the more general syntax, ${varname}.

Why two syntaxes? For one thing, the more general syntax is necessary if your code refers to more than nine positional parameters: you must use ${10} for the tenth instead of $10. Aside from that, consider the following case where you would like to place an underscore after your user ID:

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

echo $UID_

The shell will try to use UID_ as the name of the variable. Unless, by chance, $UID_ already exists, this won't print anything (the value being null or the empty string, ""). To obtain the desired result, you need to enclose the shell variable in curly brackets:

echo ${UID}_

It is safe to omit the curly brackets ({}) if the variable name is followed by a character that isn't a letter, digit, or underscore.

 


[3] Unless the option nounset is turned on, in which case the shell will return an error message.