Introduction
Array slicing helps you get a part of a list of items easily. It saves time when you only need some items, not the whole list.
array_name=(item1 item2 item3 ...)
sliced_array=(${array_name[@]:start_index:length})fruits=(apple banana cherry date elderberry)
slice=(${fruits[@]:1:3})
echo "${slice[@]}"numbers=(10 20 30 40 50) slice=(${numbers[@]:0:2}) echo "${slice[@]}"
colors=(red green blue)
slice=(${colors[@]:2:5})
echo "${slice[@]}"empty=()
slice=(${empty[@]:0:2})
echo "${slice[@]}"#!/bin/bash # Create an array of animals animals=(cat dog bird fish horse) echo "Original array: ${animals[@]}" # Slice: get 3 animals starting from index 1 sliced_animals=(${animals[@]:1:3}) echo "Sliced array (3 items from index 1): ${sliced_animals[@]}" # Slice: get first 2 animals first_two=(${animals[@]:0:2}) echo "First two animals: ${first_two[@]}" # Slice: get from index 4 to end last_one=(${animals[@]:4}) echo "Last animal: ${last_one[@]}" # Slice: try slicing beyond array length beyond=(${animals[@]:3:10}) echo "Slice beyond length (from index 3, 10 items): ${beyond[@]}"
${array[@]:start:length}?${array[@]:start:length} extracts elements from the array starting at index start and takes length elements.start index with length elements correctly describes this extraction. Other options describe unrelated operations.arr?${array[@]:start:length}. The @ is needed to refer to all elements.${arr[@]:2:3} matches the correct syntax: ${arr[@]:2:3}. ${arr:2:3} misses @, which is required for arrays. Options B and D use invalid syntax.arr=(a b c d e), what is the output of echo ${arr[@]:1:3}?(a b c d e). The slice starts at index 1 and takes 3 elements.arr=(x y z)
echo ${arr:1:2}${arr:1:2} without @. For arrays, @ is needed to slice multiple elements.@, Bash uses the first element x as a scalar string and slices it from index 1 length 2. Since x has length 1, it outputs an empty string.arr=(1 2 3 4 5). You want to extract the last 3 elements using array slicing. Which command will do this correctly?${arr[@]:-3} extracts from 3rd from end to the end (last 3 elements).${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.Pass the test and this pattern moves unknown