Bird
0
0

Which bash snippet correctly checks if the variable input is empty by using string length?

hard🚀 Application Q8 of 15
Bash Scripting - String Operations
Which bash snippet correctly checks if the variable input is empty by using string length?
Aif [ $input -eq 0 ]; then echo "Empty"; fi
Bif [ ${#input} -eq 0 ]; then echo "Empty"; fi
Cif [ -z ${input} ]; then echo "Empty"; fi
Dif [ ${input} == "" ]; then echo "Empty"; fi
Step-by-Step Solution
Solution:
  1. Step 1: Understand string length check

    Using ${#input} gives the length of the string.
  2. Step 2: Check for zero length

    Comparing ${#input} to 0 correctly tests if the string is empty.
  3. Step 3: Analyze other options

    if [ $input -eq 0 ]; then echo "Empty"; fi tries numeric comparison on string content, invalid. if [ -z ${input} ]; then echo "Empty"; fi lacks quotes and may cause errors if input is unset. if [ ${input} == "" ]; then echo "Empty"; fi uses string comparison but is less reliable without quotes.
  4. Final Answer:

    if [ ${#input} -eq 0 ]; then echo "Empty"; fi -> Option B
  5. Quick Check:

    Test with input="" outputs "Empty" [OK]
Quick Trick: Check if ${#var} equals 0 to test empty string [OK]
Common Mistakes:
MISTAKES
  • Using numeric comparison on string variable directly
  • Not quoting variables causing syntax errors
  • Using -z without quotes leading to errors if variable unset

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes