Bird
0
0

You want to create a script that prints a greeting with a variable name that might be empty. Which is the best way to write it to avoid errors?

hard🚀 Application Q8 of 15
Bash Scripting - Quoting and Expansion
You want to create a script that prints a greeting with a variable name that might be empty. Which is the best way to write it to avoid errors?
echo "Hello, $name!"
AUse no quotes: echo Hello, $name!
BUse single quotes: echo 'Hello, $name!'
CUse double quotes and default value: echo "Hello, ${name:-Guest}!"
DEscape the variable: echo "Hello, \$name!"
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable expansion with defaults

    Using ${name:-Guest} provides a default if name is empty.
  2. Step 2: Analyze other options

    Single quotes prevent expansion; no quotes risk word splitting; escaping prints literal.
  3. Final Answer:

    Use double quotes and default value: echo "Hello, ${name:-Guest}!" -> Option C
  4. Quick Check:

    Default value with double quotes avoids errors = C [OK]
Quick Trick: Use ${var:-default} inside double quotes for safe defaults [OK]
Common Mistakes:
MISTAKES
  • Using single quotes which prevent expansion
  • Not handling empty variables
  • Escaping dollar sign instead of expanding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes