Bird
0
0

Identify the error in this bash script snippet that tries to print the number of elements in array data:

medium📝 Debug Q14 of 15
Bash Scripting - Arrays
Identify the error in this bash script snippet that tries to print the number of elements in array data:
data=(1 2 3 4)
echo ${#data}
AIt prints the length of the first element, not the array size
BThe array is not declared properly
CThe echo command is missing quotes
DThe syntax ${#data} is invalid in bash
Step-by-Step Solution
Solution:
  1. Step 1: Check array length syntax

    ${#data} returns the length of the first element (string length), not the number of elements.
  2. Step 2: Correct syntax for array length

    Use ${#data[@]} to get the count of elements in the array.
  3. Final Answer:

    It prints the length of the first element, not the array size -> Option A
  4. Quick Check:

    Use ${#array[@]} for count, not ${#array} [OK]
Quick Trick: Use ${#array[@]} to get count, ${#array} gives first element length [OK]
Common Mistakes:
MISTAKES
  • Assuming ${#array} gives number of elements
  • Not using [@] inside the braces
  • Thinking echo needs quotes for this syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes