Bird
0
0

Which of the following is the correct syntax to check if a variable var is not empty in bash?

easy📝 Syntax Q12 of 15
Bash Scripting - Conditionals
Which of the following is the correct syntax to check if a variable var is not empty in bash?
A[ -z "$var" ]
B[ "$var" = "" ]
C[ -n "$var" ]
D[ $var != "" ]
Step-by-Step Solution
Solution:
  1. Step 1: Understand -n operator

    -n returns true if the string length is greater than zero (not empty).
  2. Step 2: Check syntax correctness

    Using quotes around $var prevents errors if variable is empty or contains spaces.
  3. Final Answer:

    [ -n "$var" ] -> Option C
  4. Quick Check:

    Not empty check = -n [OK]
Quick Trick: Use [ -n "$var" ] to test if var is not empty [OK]
Common Mistakes:
MISTAKES
  • Using -z instead of -n for not empty
  • Forgetting quotes around variable
  • Using = "" to check emptiness incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes