0
0
Bash Scriptingscripting~20 mins

Default values (${var:-default}) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Default Value Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2: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}!"
AHello, ${NAME:-Guest}!
BHello, !
CHello, Guest!
DHello, NAME!
Attempts:
2 left
💡 Hint
If a variable is not set, the default value after :- is used.
💻 Command Output
intermediate
2:00remaining
Output when variable is empty string with default value
What will this script print?
Bash Scripting
NAME=""
echo "Welcome, ${NAME:-User}!"
AWelcome, ${NAME:-User}!
BWelcome, User!
CWelcome, !
DWelcome, ""!
Attempts:
2 left
💡 Hint
Default value is used only if variable is unset or null (empty).
💻 Command Output
advanced
2: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}"
A
A: Guest
B: 
B
A: 
B: Guest
C
A: Guest
B: Guest
D
A: 
B: 
Attempts:
2 left
💡 Hint
:- uses default if variable is unset or null; - uses default only if unset.
🔧 Debug
advanced
2: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}!"
ABecause the default value must be in quotes to work.
BBecause the syntax ${NAME-default} is invalid and causes empty output.
CBecause the variable NAME is not exported to the environment.
DBecause ${NAME-default} uses default only if NAME is unset, not if empty.
Attempts:
2 left
💡 Hint
Check difference between - and :- in parameter expansion.
🚀 Application
expert
3: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?
Aecho "${VAR:-default_value}"
Becho "${VAR:+default_value}"
Cecho "${VAR:=default_value}"
Decho "${VAR-default_value}"
Attempts:
2 left
💡 Hint
Use the operator that substitutes default if variable is unset or empty.