A. Index 3 is out of range, so output is empty string
B. Syntax error due to missing quotes
C. Array elements must be accessed with parentheses
D. It will print 'cherry' instead of empty
Solution
Step 1: Check array size and index used
Array has 3 elements at indexes 0,1,2. Index 3 is out of range.
Step 2: Understand Bash behavior for out-of-range index
Accessing an out-of-range index returns an empty string, no error occurs.
Final Answer:
Index 3 is out of range, so output is empty string -> Option A
Quick Check:
Out-of-range index returns empty string [OK]
Hint: Out-of-range indexes return empty, not errors [OK]
Common Mistakes:
Expecting syntax error for out-of-range index
Using parentheses instead of brackets
Assuming last element is at index 3
Expecting output 'cherry' for index 3
5. You have a Bash array items=(pen notebook eraser). You want to print the last element without hardcoding the index. Which command achieves this?
hard
A. echo ${items[-1]}
B. echo ${items[${#items[@]}-1]}
C. echo ${items[${#items[@]}]}
D. echo ${items[3]}
Solution
Step 1: Understand array length and indexing
${#items[@]} gives the number of elements (3). Last index is length minus 1 (2).
Step 2: Use arithmetic inside array index
Use ${items[${#items[@]}-1]} to get last element dynamically.
Step 3: Check other options
echo ${items[-1]} uses negative index which Bash does not support. echo ${items[${#items[@]}]} uses length as index (out of range). echo ${items[3]} hardcodes index 3 which is out of range.
Final Answer:
echo ${items[${#items[@]}-1]} -> Option B
Quick Check:
Last element = items[length-1] [OK]
Hint: Use ${array[${#array[@]}-1]} for last element [OK]
Common Mistakes:
Using negative indexes (not supported in Bash)
Using length as index (off by one)
Hardcoding index without checking length
Forgetting to use ${} around length
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.