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

Can someone explain to me why some Linux expert suggests using $ {VARIABLE} in Bash scripts? There seems to be no difference.

+6
source share
3 answers

Suppose you want to print $VARIABLE and then "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.

+9
source

One of the reasons you can do this is to {} act as delimiters:

 a=42 echo "${a}sdf" # 42sdf echo "$asdf" # prints nothing because there no variable $asdf 
+3
source

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

 $ var=foo 

If we want to concatenate the string at the end of $var we cannot do:

 $ echo $varbar $ 

as this is trying to use the new $varbar variable.
Instead, we need to wrap var in {} as:

 $ echo ${var}bar foobar 
+1
source

Source: https://habr.com/ru/post/902289/


All Articles