Working with Arrays in Shell Scripting

An array in shell scripting is a variable that can hold multiple values. It allows you to store and access a collection of elements under a single variable name. Shell scripting supports one-dimensional arrays, where elements are accessed by their index.

Declaring an Array:

To declare an array in shell scripting, you can use the following syntax:

Bash
array_name=(element1 element2 element3 ... elementN)

Example:

Bash
fruits=(apple banana cherry)

Accessing Elements:

You can access elements of an array using their indices. The indices start from 0 for the first element, 1 for the second element, and so on.

Bash
# Accessing the first element
echo ${fruits[0]}

# Accessing the second element
echo ${fruits[1]}

# Accessing all elements
echo ${fruits[@]}

Array Length:

To get the length of an array, you can use the ${#array_name[@]} syntax.

Bash
# Get the length of the array
length=${#fruits[@]}
echo "Length of the array: $length"

Modifying Elements:

You can modify individual elements of an array by assigning a new value to the desired index.

Bash
fruits[1]="grape" # Change the second element to "grape"

Iterating Over an Array:

You can use loops to iterate over the elements of an array.

Bash
fruits=(apple banana cherry)

# Iterate over the elements using a for loop
for fruit in "${fruits[@]}"
do
    echo "Fruit: $fruit"
done

Adding Elements:

You can add elements to an array using the += operator.

Bash
fruits+=(orange)

Removing Elements:

You can remove elements by using the unset command.

Bash
unset fruits[1]  # Removes the second element

Associative Arrays (Bash 4.0 and later):

Bash 4.0 and later versions support associative arrays, which allow you to use arbitrary strings as indices instead of just numbers.

Bash
declare -A colors
colors["red"]="#FF0000"
colors["green"]="#00FF00"
colors["blue"]="#0000FF"

echo "Red: ${colors["red"]}"
echo "Green: ${colors["green"]}"
echo "Blue: ${colors["blue"]}"

Caveats:

  • Shell scripting’s array support is somewhat limited compared to other programming languages. It doesn’t support multi-dimensional arrays or complex operations like sorting or searching.
  • Arrays in shell scripting are indexed by integers, and they are not sparse. If you assign a value to an element with an index that’s not in use, the array will automatically expand to include it.
  • Array indices are evaluated as arithmetic expressions. Be careful when using variables as indices, as they should be integers.
  • The length of an array is not fixed. It can grow or shrink dynamically as you add or remove elements.

Remember that different shells (like Bash, Zsh, etc.) may have slight variations in their array syntax or features. The examples provided here are for Bash.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...