0
0
Bash Scriptingscripting~10 mins

Default values (${var:-default}) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Default values (${var:-default})
Start
Check if var is set and not empty
Use var value
Output
End
The script checks if a variable is set and not empty; if yes, it uses its value, otherwise it uses the default value.
Execution Sample
Bash Scripting
name=""
echo "Hello, ${name:-Guest}!"

name="Alice"
echo "Hello, ${name:-Guest}!"
This code prints a greeting using the variable 'name' if set and not empty; otherwise, it uses 'Guest' as default.
Execution Table
StepVariable 'name'Condition '${name:-Guest}'Output
1'' (empty string)Empty or unset, use default 'Guest'Hello, Guest!
2'Alice'Set and not empty, use 'Alice'Hello, Alice!
💡 Execution ends after printing greetings with either the default or the variable value.
Variable Tracker
VariableStartAfter Step 1After Step 2
nameunset'' (empty string)'Alice'
Key Moments - 2 Insights
Why does the first echo print 'Guest' even though 'name' is set to an empty string?
Because '${name:-Guest}' treats empty strings as unset or empty, so it uses the default 'Guest' as shown in execution_table step 1.
What happens if 'name' is set to a non-empty value?
The expression uses the actual value of 'name', as in execution_table step 2 where 'Alice' is printed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when 'name' is an empty string?
AHello, Guest!
BHello, !
CHello, name!
DHello, ${name}!
💡 Hint
Check execution_table row 1 under Output column.
At which step does the condition '${name:-Guest}' use the variable's actual value?
AStep 1
BStep 2
CBoth steps
DNeither step
💡 Hint
See execution_table Condition column for Step 2.
If 'name' was unset instead of empty, what would the output be?
AHello, name!
BHello, !
CHello, Guest!
DError
💡 Hint
Default value is used when variable is unset or empty, as shown in Step 1.
Concept Snapshot
Syntax: ${var:-default}
If 'var' is unset or empty, use 'default'.
Otherwise, use 'var' value.
Common in scripts to provide fallback values.
Example: echo "${name:-Guest}" prints 'Guest' if name is empty or unset.
Full Transcript
This visual execution shows how the bash syntax ${var:-default} works. First, it checks if the variable 'name' is set and not empty. If 'name' is empty or unset, it uses the default value 'Guest'. Otherwise, it uses the actual value of 'name'. The example runs two steps: first with 'name' as an empty string, printing 'Hello, Guest!'; second with 'name' set to 'Alice', printing 'Hello, Alice!'. This helps beginners see how default values provide safe fallbacks in scripts.