0
0
Bash Scriptingscripting~5 mins

Array slicing in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is array slicing in bash scripting?
Array slicing is a way to extract a part of an array by specifying a start index and length, similar to cutting a piece from a list.
Click to reveal answer
beginner
How do you slice an array named arr from index 2 to get 3 elements?
Use ${arr[@]:2:3}. This extracts 3 elements starting from index 2.
Click to reveal answer
intermediate
What happens if the length in array slicing is omitted in bash?
If length is omitted, slicing extracts all elements from the start index to the end of the array.
Click to reveal answer
beginner
Given arr=(a b c d e), what is the output of echo ${arr[@]:1:2}?
The output is b c. It slices 2 elements starting from index 1.
Click to reveal answer
intermediate
Can array slicing in bash use negative indices?
Yes, negative start indices count from the end of the array backwards. For example, ${arr[@]: -2} gets the last two elements.
Click to reveal answer
In bash, what does ${arr[@]:3} do?
AExtracts all elements starting from index 3 to the end
BExtracts the first 3 elements
CExtracts 3 elements starting from index 0
DExtracts 3 elements starting from index 3
How do you get the last 2 elements of an array arr in bash?
A${arr[@]: -2}
B${arr[@]:2:2}
C${arr[@]:-1}
D${arr[@]:0:2}
What is the index of the first element in a bash array?
A1
B-1
C0
DDepends on array size
If arr=(x y z), what does ${arr[@]:1:5} return?
Az
By z
Cx y z
DError
Which syntax correctly slices an array arr from index 0 for 2 elements?
A${arr:0:2}
B${arr[0]:2}
C${arr[2]:0}
D${arr[@]:0:2}
Explain how to extract a slice from a bash array and what happens if the length is omitted.
Think about cutting a piece from a list starting at a position.
You got /4 concepts.
    Describe how negative indices work in bash array slicing and give an example.
    Negative numbers count backwards from the end.
    You got /3 concepts.