Bird
Raised Fist0
Bash Scriptingscripting~5 mins

Array slicing in Bash Scripting

Choose your learning style10 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.

Practice

(1/5)
1. In Bash scripting, what does array slicing do when you use ${array[@]:start:length}?
easy
A. Sorts the array elements alphabetically
B. Deletes elements from the array starting at start index
C. Extracts a part of the array starting at start index with length elements
D. Reverses the array elements from start to length

Solution

  1. Step 1: Understand array slicing syntax

    In Bash, ${array[@]:start:length} extracts elements from the array starting at index start and takes length elements.
  2. Step 2: Compare options with this behavior

    Only Extracts a part of the array starting at start index with length elements correctly describes this extraction. Other options describe unrelated operations.
  3. Final Answer:

    Extracts a part of the array starting at start index with length elements -> Option C
  4. Quick Check:

    Array slicing = Extract part [OK]
Hint: Remember slicing picks elements, not deletes or sorts [OK]
Common Mistakes:
  • Confusing slicing with deleting elements
  • Thinking slicing sorts or reverses the array
  • Mixing up start index and length meaning
2. Which of the following is the correct syntax to slice 3 elements from index 2 in a Bash array named arr?
easy
A. ${arr[2:3]}
B. ${arr[@]:2:3}
C. ${arr:2:3}
D. ${arr[2..4]}

Solution

  1. Step 1: Recall correct array slicing syntax

    In Bash, to slice an array, use ${array[@]:start:length}. The @ is needed to refer to all elements.
  2. Step 2: Check each option

    ${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.
  3. Final Answer:

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

    Use ${array[@]:start:length} for slicing [OK]
Hint: Use @ inside braces for array slicing syntax [OK]
Common Mistakes:
  • Omitting @ when slicing arrays
  • Using square brackets with colon syntax
  • Trying to slice with invalid range notation
3. Given the Bash array arr=(a b c d e), what is the output of echo ${arr[@]:1:3}?
medium
A. a b c
B. c d e
C. b c d e
D. b c d

Solution

  1. Step 1: Identify the array and slice parameters

    The array is (a b c d e). The slice starts at index 1 and takes 3 elements.
  2. Step 2: Extract elements from index 1 to 3

    Index 0 = a, 1 = b, 2 = c, 3 = d, 4 = e. Taking 3 elements from index 1 gives: b, c, d.
  3. Final Answer:

    b c d -> Option D
  4. Quick Check:

    Slice from 1 length 3 = b c d [OK]
Hint: Count from zero, pick length elements starting at start [OK]
Common Mistakes:
  • Starting count at 1 instead of 0
  • Taking wrong number of elements
  • Confusing output with full array
4. What is wrong with this Bash code snippet for slicing an array?
arr=(x y z)
echo ${arr:1:2}
medium
A. It will output an empty string
B. It will output only one element instead of two
C. It will cause a syntax error because slicing is not allowed
D. It will output 'y z' correctly

Solution

  1. Step 1: Check slicing syntax correctness

    The code uses ${arr:1:2} without @. For arrays, @ is needed to slice multiple elements.
  2. Step 2: Understand the effect of missing @

    Without @, 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.
  3. Final Answer:

    It will output an empty string -> Option A
  4. Quick Check:

    Missing @ slices first elem as string -> empty [OK]
Hint: Always use @ for array slicing, else string slicing happens [OK]
Common Mistakes:
  • Omitting @ and expecting array slice
  • Assuming no error but wrong output
  • Confusing string and array slicing syntax
5. 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
A. echo ${arr[@]:-3}
B. echo ${arr[@]: -3:3}
C. echo ${arr[@]:3:3}
D. echo ${arr[@]:3}

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]
Hint: Use negative start index without length to get last elements [OK]
Common Mistakes:
  • Adding space after ':' before negative offset
  • Using slice length larger than remaining elements
  • Not knowing negative indices slice from array end
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard