0
0
Bash Scriptingscripting~5 mins

Array slicing in Bash Scripting

Choose your learning style9 modes available
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.
You want to get the first few files from a list of files.
You need to process only a part of user inputs stored in an array.
You want to print a few recent log entries from an array of logs.
You want to skip the first few items and work with the rest.
You want to split a list into smaller parts for easier handling.
Syntax
Bash Scripting
array_name=(item1 item2 item3 ...)
sliced_array=(${array_name[@]:start_index:length})
start_index starts at 0 for the first item.
length is how many items you want to take from start_index.
Examples
Gets 3 items starting from index 1 (banana, cherry, date).
Bash Scripting
fruits=(apple banana cherry date elderberry)
slice=(${fruits[@]:1:3})
echo "${slice[@]}"
Gets first 2 items (10, 20).
Bash Scripting
numbers=(10 20 30 40 50)
slice=(${numbers[@]:0:2})
echo "${slice[@]}"
Starts at index 2 (blue) and tries to get 5 items but only 1 exists.
Bash Scripting
colors=(red green blue)
slice=(${colors[@]:2:5})
echo "${slice[@]}"
Slicing an empty array returns nothing.
Bash Scripting
empty=()
slice=(${empty[@]:0:2})
echo "${slice[@]}"
Sample Program
This script shows how to slice parts of an array in bash. It prints the original array and different slices to see how slicing works.
Bash Scripting
#!/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[@]}"
OutputSuccess
Important Notes
Array slicing in bash is zero-based, meaning the first item is at index 0.
If the length is omitted, slicing takes all items from start_index to the end.
Trying to slice beyond the array length just returns available items without error.
Time complexity is O(k) where k is the slice length, as it copies those items.
Common mistake: forgetting that array indices start at 0, leading to off-by-one errors.
Use slicing when you want a subset of an array without modifying the original.
Summary
Array slicing extracts a part of an array using start index and length.
Indices start at 0, and length controls how many items to take.
Slicing beyond array length returns only available items without error.