Bird
0
0

You have a Bash array arr=(1 2 3 4 5). You want to extract the last 3 elements using array slicing. Which command will do this correctly?

hard🚀 Application Q15 of 15
Bash Scripting - Arrays
You have a Bash array arr=(1 2 3 4 5). You want to extract the last 3 elements using array slicing. Which command will do this correctly?
A<code>echo ${arr[@]:-3}</code>
B<code>echo ${arr[@]: -3:3}</code>
C<code>echo ${arr[@]:3:3}</code>
D<code>echo ${arr[@]:3}</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand negative index slicing in Bash

    Using a negative start index slices from the end. ${arr[@]:-3} extracts from 3rd from end to the end (last 3 elements).
  2. Step 2: Check each option

    ${arr[@]: -3:3} has space after : causing bad substitution. ${arr[@]:3:3} slices from index 3 length 3 but only 2 elements remain (4 5). ${arr[@]:3} slices from 3 to end (4 5). Only ${arr[@]:-3} gets exactly the last 3: 3 4 5.
  3. Final Answer:

    echo ${arr[@]:-3} -> Option A
  4. Quick Check:

    Negative start index slices from end [OK]
Quick Trick: Use negative start index without length to get last elements [OK]
Common Mistakes:
MISTAKES
  • Adding space after ':' before negative offset
  • Using slice length larger than remaining elements
  • Not knowing negative indices slice from array end

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes