Bird
0
0

You want to safely reference an optional variable path in a bash script with set -u enabled. Which method prevents errors if path is unset?

hard🚀 Application Q8 of 15
Bash Scripting - Error Handling
You want to safely reference an optional variable path in a bash script with set -u enabled. Which method prevents errors if path is unset?
#!/bin/bash
set -u

echo "Path is: ???"
Aunset path; echo "Path is: $path"
Becho "Path is: $path"
Cecho "Path is: ${path:-/default/path}"
Dset +u; echo "Path is: $path"
Step-by-Step Solution
Solution:
  1. Step 1: Identify the problem

    Referencing $path directly causes an error if unset with set -u.
  2. Step 2: Use default value expansion

    Use ${path:-/default/path} to provide a fallback value.
  3. Final Answer:

    echo "Path is: ${path:-/default/path}" -> Option C
  4. Quick Check:

    Use ${var:-default} to avoid unset variable errors [OK]
Quick Trick: Use ${var:-default} to handle optional variables safely [OK]
Common Mistakes:
MISTAKES
  • Referencing variables directly without defaults
  • Unsetting variables intentionally before use
  • Disabling set -u instead of handling variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes