Shell Scripting Arrays: Definition, Manipulation, and Usage

Shell arrays provide a mechanism to store multiple values under a single variable name, differentiated by numerical indices. These indices, or subscripts, typically start from 0. Arrays are a specialized form of shell variables, inheriting functionalities such as substring manipulation.

Defining Arrays

Arrays can be defined in several ways:

  1. Static Initialization:

    • my_array=(apple banana cherry)
    • config_urls=( http://example.com http://sample.net )
    • indexed_array=([0]=first [1]=second [2]=third [3]=fourth)
  2. Dynamic Initialization (Command Substitution):

    • file_list=($(ls -1 *.txt))
    • command_output=(ls -l`)

Accessing Array Elements

  • All Elements: ${my_array[@]} or ${my_array[*]}
  • Array Length: ${#my_array[@]} or ${#my_array[*]}
  • Specific Element: ${my_array[index]} (e.g., ${my_array[0]} for the first element)

Modifying Array Elements

Assigning a value to a existing index overwrites the current value. Assigning to a new index expands the array.

my_array[0]=new_value
my_array[5]=another_value

Deleting Array Elements

Use the unset command:

  • Delete a specific element: unset my_array[index]
  • Delete the entire array: unset my_array

Array Slicing and Substitution

Arrays support substring-like operations.

  • Slicing: Extract a range of elements. ${my_array[@]:start_index:count}

    data=(10 20 30 40 50)
    echo "${data[@]:1:3}" # Output: 20 30 40
    

    This extracts 3 elements starting from index 1.

  • Substitution: Replace occurrences of a pattern within array elements. ${array_name[@]/pattern/replacement}

    nums=(1 2 1 3 1)
    echo "${nums[@]/1/X}" # Output: X 2 X 3 X
    

    This replaces all occurrences of '1' with 'X'. The original array remains unchanged.

Example: Filtering Words by Length

This script iterates through an array of words and prints those with a length of 6 characters or less.

#!/bin/bash

words=("apple" "banana" "kiwi" "strawberry" "grape")

echo "Words with length <= 6 (using ".[*]"):"
for word in "${words[*]}"; do
  if [ "${#word}" -le 6 ]; then
    echo "$word"
  fi
done

echo "-----------------"

echo "Words with length <= 6 (using indexed loop):"
for (( i=0; i<${#words[*]}; i++ )); do
  if [ "${#words[i]}" -le 6 ]; then
    echo "${words[i]}"
  fi
done

Running this script would produce:

Words with length <= 6 (using ".[*]"):
apple
banana
kiwi
grape
-----------------
Words with length <= 6 (using indexed loop):
apple
banana
kiwi
grape

Tags: Shell bash Scripting Arrays Variables

Posted on Thu, 27 Aug 2026 16:28:44 +0000 by chadtimothy23