Bash Integer Array



Bash Integer Array

In Bash scripting, creating and working with an integer array is useful for various tasks that require managing numerical data in arrays.


Syntax

array=(value1 value2 value3)

The basic syntax involves using parentheses to initialize an array with integer elements separated by spaces.


Example Bash Integer Array

Let's look at some examples of how to create and work with an integer array in Bash:

1. Create an Integer Array

This script initializes an array with integer elements and prints the array.

#!/bin/bash

array=(1 2 3 4 5)
echo "Integer array: ${array[@]}"

In this script, the array variable array is initialized with the integers 1, 2, 3, 4, and 5. The script then prints the array.

Create an integer array in Bash

2. Access Elements in an Integer Array

This script initializes an integer array and prints each element by accessing them using their indices.

#!/bin/bash

array=(10 20 30 40 50)
echo "First element: ${array[0]}"
echo "Second element: ${array[1]}"
echo "Third element: ${array[2]}"
echo "Fourth element: ${array[3]}"
echo "Fifth element: ${array[4]}"

In this script, the array variable array is initialized with the integers 10, 20, 30, 40, and 50. The script then prints each element by accessing them using their indices.

Access elements in an integer array in Bash

3. Perform Arithmetic Operations on an Integer Array

This script initializes an integer array, performs arithmetic operations on each element, and prints the results.

#!/bin/bash

array=(1 2 3 4 5)
for element in "${array[@]}"; do
    squared=$((element * element))
    echo "The square of $element is: $squared"
done

In this script, the array variable array is initialized with the integers 1, 2, 3, 4, and 5. The for loop iterates over each element in the array, performs the arithmetic operation of squaring the element, and prints the result.

Perform arithmetic operations on an integer array in Bash

4. Sum Elements of an Integer Array

This script initializes an integer array, calculates the sum of its elements, and prints the total sum.

#!/bin/bash

array=(5 10 15 20 25)
sum=0
for element in "${array[@]}"; do
    sum=$((sum + element))
done
echo "The total sum of the array elements is: $sum"

In this script, the array variable array is initialized with the integers 5, 10, 15, 20, and 25. The for loop iterates over each element in the array, adds the element to the sum variable, and the script then prints the total sum.

Sum elements of an integer array in Bash

Conclusion

Creating and working with an integer array in Bash is a fundamental task for managing numerical data in arrays in shell scripting. Understanding how to create, access, and perform operations on integer arrays can help you manage and manipulate numerical data effectively in your scripts.