Bird
0
0

Which script snippet correctly does this?

hard🚀 Application Q15 of 15
Bash Scripting - Arrays
You have a bash array items that may be empty or have elements. You want to print "Empty" if it has zero elements, or "Count: N" where N is the number of elements. Which script snippet correctly does this?
Aif [ ${#items} -eq 0 ]; then echo "Empty"; else echo "Count: ${#items[@]}"; fi
Bif [ ${#items[@]} -eq 0 ]; then echo "Empty"; else echo "Count: ${#items[@]}"; fi
Cif [ ${#items[@]} -eq 0 ]; then echo "Empty"; else echo "Count: ${#items}"; fi
Dif [ ${#items} -eq 0 ]; then echo "Empty"; else echo "Count: ${#items}"; fi
Step-by-Step Solution
Solution:
  1. Step 1: Check condition for empty array

    Use ${#items[@]} to get the number of elements. If zero, array is empty.
  2. Step 2: Print count correctly

    Use ${#items[@]} to print the count of elements, not ${#items} which is length of first element.
  3. Final Answer:

    if [ ${#items[@]} -eq 0 ]; then echo "Empty"; else echo "Count: ${#items[@]}"; fi -> Option B
  4. Quick Check:

    Use ${#array[@]} for count in both condition and output [OK]
Quick Trick: Always use ${#array[@]} to check and print array length [OK]
Common Mistakes:
MISTAKES
  • Using ${#array} instead of ${#array[@]} for count
  • Mixing length of first element with element count
  • Forgetting to use [ ] in if condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes