0
0
Bash Scriptingscripting~10 mins

Double quotes (variable expansion) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Double quotes (variable expansion)
Start script
Assign variable
Use variable inside double quotes
Shell expands variable
Print expanded value
End script
The shell reads the script, assigns variables, then expands variables inside double quotes before printing the result.
Execution Sample
Bash Scripting
name="Alice"
echo "Hello, $name!"
Assigns 'Alice' to variable name and prints 'Hello, Alice!' using double quotes for variable expansion.
Execution Table
StepActionVariable 'name'CommandOutput
1Assign variableAlicename="Alice"
2Expand variable inside double quotesAliceecho "Hello, $name!"Hello, Alice!
3End scriptAlice
💡 Script ends after printing the expanded variable inside double quotes.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
nameundefinedAliceAliceAlice
Key Moments - 2 Insights
Why does the variable $name get replaced with 'Alice' inside double quotes?
Because inside double quotes, the shell expands variables, so $name is replaced by its value 'Alice' as shown in step 2 of the execution_table.
What would happen if single quotes were used instead of double quotes?
Single quotes prevent variable expansion, so the output would literally be 'Hello, $name!' instead of 'Hello, Alice!'. This is different from the double quotes behavior in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
AHello, $name!
BHello, !
CHello, Alice!
Dname
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step is the variable 'name' assigned the value 'Alice'?
AStep 1
BStep 2
CStep 3
DBefore the script starts
💡 Hint
Look at the 'Action' and 'Variable' columns in the execution_table for when 'name' changes.
If we replaced double quotes with single quotes in echo, what would be the output?
AHello, Alice!
BHello, $name!
CHello, !
DError
💡 Hint
Recall that single quotes prevent variable expansion, unlike double quotes shown in step 2.
Concept Snapshot
Double quotes allow variable expansion in bash.
Use "$variable" to get its value inside strings.
Single quotes prevent expansion, printing variables literally.
Example: name="Alice"; echo "Hello, $name!" prints Hello, Alice!
Always use double quotes to safely expand variables in strings.
Full Transcript
This example shows how bash expands variables inside double quotes. First, the variable 'name' is assigned the value 'Alice'. Then, when echo is called with "Hello, $name!", the shell replaces $name with 'Alice' because double quotes allow variable expansion. The output is 'Hello, Alice!'. If single quotes were used instead, the output would be 'Hello, $name!' because single quotes prevent expansion. This behavior is important to understand for scripting and printing variables correctly.