When you use $variable, you're telling the shell, "Give me the value stored in the variable named variable." For instance:
name="Yesh"
echo "$name"
name="Yesh"
echo "$name"
This will print: Yesh
When you use ${variable}2, you're saying, "Give me the value stored in variable and then add 2 right after it." For example:
name="Yesh"
echo "${name}2"
name="Yesh"
echo "${name}2"
This will print: Yesh2
The curly braces, {}, are used to make sure the shell knows exactly where the variable name ends. This is important when you're combining a variable with other text. Without the braces, the shell might get confused and look for a variable name that includes the extra characters.
Example:
Imagine Imagine you have a variable called file and you want to add a file extension to it:
file="document"
echo "$file.txt" # This will be a problem because the shell will look for a variable named 'file.txt'
echo "${file}.txt" # This will work correctly and print 'document.txt'
file="document"
echo "$file.txt" # This will be a problem because the shell will look for a variable named 'file.txt'
echo "${file}.txt" # This will work correctly and print 'document.txt'
Using the braces helps the shell understand where the variable name stops and the extra text starts.
So, in short:
$variable: Just gives you the value of variable.
${variable}2: Gives you the value of variable with 2 added to the end.
Using ${} helps avoid confusion and errors when you're mixing variables with other text.
$variable: Just gives you the value ofvariable.${variable}2: Gives you the value ofvariablewith2added to the end.- Using
${}helps avoid confusion and errors when you're mixing variables with other text.