Challenge - 5 Problems
Array Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this Bash array slicing?
Given the array
arr=(a b c d e f g), what is the output of echo ${arr[@]:2:3}?Bash Scripting
arr=(a b c d e f g)
echo ${arr[@]:2:3}Attempts:
2 left
💡 Hint
Remember that array slicing starts at index 0 and the syntax is ${array[@]:start:length}.
✗ Incorrect
The slice starts at index 2 (third element) and takes 3 elements: c, d, e.
💻 Command Output
intermediate2:00remaining
What does this negative index slice output?
With
arr=(1 2 3 4 5 6 7 8 9), what is the output of echo ${arr[@]: -4:2}?Bash Scripting
arr=(1 2 3 4 5 6 7 8 9) echo ${arr[@]: -4:2}
Attempts:
2 left
💡 Hint
Negative start index counts from the end of the array.
✗ Incorrect
Start index -4 means start at the 4th last element, which is 6, then take 2 elements: 6 and 7.
📝 Syntax
advanced2:00remaining
Which option correctly slices the last 3 elements of an array?
Given
arr=(x y z a b c d), which command outputs the last 3 elements?Bash Scripting
arr=(x y z a b c d)
Attempts:
2 left
💡 Hint
Use negative start index and specify length to get exact elements.
✗ Incorrect
Option A starts 3 from the end and takes 3 elements, correctly outputting 'b c d'. Option A omits length and outputs 3 elements but may be ambiguous. Option A starts at index 3, which is 'a', not last 3. Option A starts 4 from end and takes 3 elements, which is 'a b c'.
🔧 Debug
advanced2:00remaining
Why does this slicing command fail?
Given
arr=(10 20 30 40 50), why does echo ${arr[@]:-3:2} produce unexpected output?Bash Scripting
arr=(10 20 30 40 50) echo ${arr[@]:-3:2}
Attempts:
2 left
💡 Hint
Check how Bash interprets the colon and minus sign in parameter expansion.
✗ Incorrect
Without a space, ${arr[@]:-3:2} is interpreted as 'if arr[@] is unset or null, use -3:2', not slicing. To slice with negative index, a space is needed after the colon: ${arr[@]: -3:2}.
🚀 Application
expert3:00remaining
How many elements are in the slice?
Given
arr=(alpha beta gamma delta epsilon zeta eta), what is the number of elements output by echo ${arr[@]:4:10}?Bash Scripting
arr=(alpha beta gamma delta epsilon zeta eta)
echo ${arr[@]:4:10}Attempts:
2 left
💡 Hint
The slice length can be longer than the remaining elements, but output only includes available elements.
✗ Incorrect
Starting at index 4 (epsilon), there are only 3 elements left: epsilon, zeta, eta. The length 10 is more than available, so only 3 elements are output.