Challenge - 5 Problems
Default Value Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this script using default values?
Consider the following Bash script snippet. What will it print?
Bash Scripting
unset NAME
echo "Hello, ${NAME:-Guest}!"Attempts:
2 left
💡 Hint
If a variable is not set, the default value after :- is used.
✗ Incorrect
Since NAME is unset, ${NAME:-Guest} uses the default 'Guest'. So the output is 'Hello, Guest!'.
💻 Command Output
intermediate2:00remaining
Output when variable is empty string with default value
What will this script print?
Bash Scripting
NAME="" echo "Welcome, ${NAME:-User}!"
Attempts:
2 left
💡 Hint
Default value is used only if variable is unset or null (empty).
✗ Incorrect
The variable NAME is set but empty (null). The :- operator uses the default 'User' when the variable is unset or null. So the output is 'Welcome, User!'.
💻 Command Output
advanced2:00remaining
Difference between ${var:-default} and ${var-default}
Given this script, what is the output?
Bash Scripting
NAME="" echo "A: ${NAME:-Guest}" echo "B: ${NAME-Guest}"
Attempts:
2 left
💡 Hint
:- uses default if variable is unset or null; - uses default only if unset.
✗ Incorrect
NAME is set but empty. ${NAME:-Guest} treats empty as null and uses default 'Guest'. ${NAME-Guest} treats empty as set and uses empty string. So output is A: Guest and B: (empty).
🔧 Debug
advanced2:00remaining
Why does this script not print the default value?
This script is intended to print 'Hello, Guest!' if NAME is unset or empty. Why does it print 'Hello, !' instead?
CODE:
NAME=""
echo "Hello, ${NAME-default}!"
Attempts:
2 left
💡 Hint
Check difference between - and :- in parameter expansion.
✗ Incorrect
The operator - uses the default only if the variable is unset. Since NAME is set (empty string), default is not used, so output is empty.
🚀 Application
expert3:00remaining
Write a script snippet that prints a default value only if variable is unset or empty
Which option correctly prints the value of VAR if set and not empty, or 'default_value' otherwise?
Attempts:
2 left
💡 Hint
Use the operator that substitutes default if variable is unset or empty.
✗ Incorrect
The :- operator substitutes the default if VAR is unset or empty. - substitutes default only if unset. := assigns default to VAR if unset or empty. + substitutes default only if VAR is set and not empty.