爱国者
爱国者

Reputation: 4348

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.

Upvotes: 12

Views: 7214

Answers (3)

cnicutar
cnicutar

Reputation: 182744

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.

Upvotes: 13

codaddict
codaddict

Reputation: 455400

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

Upvotes: 3

David Hu
David Hu

Reputation: 3136

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

Upvotes: 5

Related Questions