0
0
Bash Scriptingscripting~20 mins

set -u for undefined variable errors in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Set -u Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output when using set -u with an undefined variable?
Consider this bash script snippet with set -u enabled. What will be the output or error?
Bash Scripting
set -u

echo "Value: $UNDEFINED_VAR"
Abash: UNDEFINED_VAR: unbound variable
BValue:
CValue: $UNDEFINED_VAR
DNo output, script runs silently
Attempts:
2 left
💡 Hint
Think about what set -u does when a variable is not set.
💻 Command Output
intermediate
2:00remaining
How to safely use an undefined variable with set -u?
Given set -u is enabled, which command safely prints the value of MY_VAR without error if it is undefined?
Bash Scripting
set -u

# Which echo command below works safely?
Aecho "$MY_VAR"
Becho "${MY_VAR+default}"
Cecho "${MY_VAR?default}"
Decho "${MY_VAR:-default}"
Attempts:
2 left
💡 Hint
Look for the syntax that provides a default value if the variable is unset.
🔧 Debug
advanced
2:00remaining
Why does this script fail with set -u enabled?
Examine the script below. Why does it fail when set -u is set?
Bash Scripting
set -u

function greet() {
  echo "Hello, $1!"
}

greet $NAME
ABecause $NAME is undefined and used without quotes
BBecause $NAME is undefined and <code>set -u</code> causes an error on undefined variables
CBecause $1 is undefined inside the function
DBecause functions cannot access variables outside their scope
Attempts:
2 left
💡 Hint
Check which variable is undefined and how set -u treats it.
🚀 Application
advanced
2:00remaining
Modify this script to avoid errors with set -u
Given the script below, which modification prevents errors when set -u is enabled and CONFIG_PATH might be unset?
Bash Scripting
set -u

if [ -f "$CONFIG_PATH" ]; then
  echo "Config found"
else
  echo "Config missing"
fi
Aif [ -f "${CONFIG_PATH?}" ]; then
Bif [ -f "$CONFIG_PATH" ] 2>/dev/null; then
Cif [ -f "${CONFIG_PATH:-}" ]; then
Dif [ -f "$CONFIG_PATH" ] || true; then
Attempts:
2 left
💡 Hint
Use parameter expansion to provide a safe default for unset variables.
🧠 Conceptual
expert
2:00remaining
What is the main purpose of set -u in bash scripting?
Choose the best description of what set -u does in a bash script.
AIt treats unset variables as an error and exits the script when they are used.
BIt enables debugging mode to print each command before execution.
CIt disables all variable expansions to improve performance.
DIt automatically initializes all variables to empty strings.
Attempts:
2 left
💡 Hint
Think about how set -u helps catch mistakes with variables.