Bird
0
0

Why does echo ${arr[-1]} not print the last element in Bash arrays?

hard🧠 Conceptual Q10 of 15
Bash Scripting - Arrays
Why does echo ${arr[-1]} not print the last element in Bash arrays?
ABash does not support negative indexes in arrays
BThe syntax is correct but array is empty
CNegative indexes print first element instead
DIt prints last element only in Bash 5+
Step-by-Step Solution
Solution:
  1. Step 1: Understand Bash array indexing rules

    Bash arrays use zero-based positive indexes only; negative indexes are invalid.
  2. Step 2: Explain behavior of negative index

    Using ${arr[-1]} does not access last element; it is treated as a string key or empty.
  3. Final Answer:

    Bash does not support negative indexes in arrays -> Option A
  4. Quick Check:

    Negative indexes unsupported in Bash arrays [OK]
Quick Trick: Bash arrays only support zero or positive indexes [OK]
Common Mistakes:
MISTAKES
  • Assuming negative indexes work like Python
  • Expecting last element with ${arr[-1]}
  • Confusing Bash versions or features

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes