简体   繁体   中英

What is the difference between $VARIABLE and ${VARIABLE}

Can anyone please provide me an explanation as to why some Linux expert suggest that we use ${VARIABLE} in Bash scripts? There doesn't seem to be any difference at all.

Say you want to print $VARIABLE immediately followed by "string"

echo "$VARIABLEstring"    # tries to print the variable called VARIABLEstring
echo "${VARIABLE}string"  # prints $VARIABLE and then "string"

Bash also supports string manipulation using this syntax.

One reason you may want to do this is {} act as delimiters:

a=42
echo "${a}sdf"  # 42sdf
echo "$asdf"  # prints nothing because there's no variable $asdf

This functionality often is used to protect a variable name from surrounding characters.

$ var=foo

If we wish to concatenate a string at the end of $var We cannot do:

$ echo $varbar  

$ 

as this is trying to use a new variable $varbar .
Instead we need to enclose var in {} as:

$ echo ${var}bar
foobar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM