Array

Here's an example of a shell script that demonstrates arrays in shell scripting:

#!/bin/bash

# Array declaration and initialization
fruits=("apple" "banana" "orange" "grape" "watermelon")

# Accessing array elements
echo "First fruit: ${fruits[0]}"
echo "Third fruit: ${fruits[2]}"

# Modifying array elements
fruits[1]="kiwi"

# Adding elements to an array
fruits+=("mango" "pineapple")

# Looping through an array
echo "All fruits:"
for fruit in "${fruits[@]}"; do
    echo "$fruit"
done

# Array length
echo "Total number of fruits: ${#fruits[@]}"

In this script, we have the following array-related operations:

  • Array Declaration and Initialization: We declare and initialize an array called fruits with multiple elements. Elements are enclosed in parentheses and separated by spaces.

  • Accessing Array Elements: We use ${fruits[index]} to access individual elements of the array. The index starts from 0. In the example, we access the first (${fruits[0]}) and third (${fruits[2]}) elements.

  • Modifying Array Elements: We can modify array elements by assigning new values to specific indexes. In this case, we change the second element to "kiwi" by assigning "kiwi" to ${fruits[1]}.

  • Adding Elements to an Array: We can add elements to an array by using the += operator followed by the new elements enclosed in parentheses. In this case, we add "mango" and "pineapple" to the fruits array.

  • Looping Through an Array: We use a for loop to iterate over all elements of the array. The "${fruits[@]}" syntax expands to all elements of the array. In the loop, we display each fruit.

  • Array Length: We use ${#fruits[@]} to get the length of the array, which represents the total number of elements.

When you run the script, it will display the first and third elements of the fruits array, modify the second element, add two new elements, loop through all the elements, and display the total number of fruits.

You can customize and expand this script by adding or removing elements from the array, manipulating array elements, and performing additional operations based on array values. Arrays in shell scripting provide a convenient way to store and manipulate multiple values within a single variable.

Last updated