Bird
0
0

How can you modify this script to avoid errors with set -u when reading multiple variables?

hard🚀 Application Q9 of 15
Bash Scripting - Error Handling
How can you modify this script to avoid errors with set -u when reading multiple variables?
#!/bin/bash
set -u

read -p "Enter name: " name
read -p "Enter age: " age

echo "Name: $name, Age: $age"
AInitialize variables with empty strings before read
BRemove quotes around variables in echo
CDisable set -u before echo and enable after
DUse parameter expansion with defaults when echoing
Step-by-Step Solution
Solution:
  1. Step 1: Identify risk of unset variables

    If user presses enter without input, variables may be empty but set; however, if variables are unset, set -u causes error.

  2. Step 2: Use parameter expansion to provide defaults

    Using ${name:-unknown} and ${age:-unknown} avoids errors if variables are unset.

  3. Final Answer:

    Use parameter expansion with defaults when echoing -> Option D
  4. Quick Check:

    Parameter expansion prevents unset errors in user input [OK]
Quick Trick: Use ${var:-default} for user input variables with set -u [OK]
Common Mistakes:
MISTAKES
  • Initializing variables before read is unnecessary
  • Disabling set -u instead of fixing code
  • Removing quotes causing word splitting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes