Bash Array Length


Bash Array Length

In Bash scripting, finding the length of an array is useful for various tasks that require determining the number of elements in an array.


Syntax

${#array[@]}

The basic syntax involves using ${#array[@]} to get the length of the array.


Example Bash Array Length

Let's look at some examples of how to find the length of an array in Bash:

1. Find Length of a Simple Array

This script initializes an array with elements and prints the length of the array.

#!/bin/bash

array=("element1" "element2" "element3")
length=${#array[@]}
echo "The length of the array is: $length"

In this script, the array variable array is initialized with the elements 'element1', 'element2', and 'element3'. The length of the array is determined using ${#array[@]} and stored in the variable length. The script then prints the length of the array.

Find length of a simple array in Bash

2. Find Length of an Empty Array

This script initializes an empty array and prints the length of the array.

#!/bin/bash

array=()
length=${#array[@]}
echo "The length of the empty array is: $length"

In this script, the array variable array is initialized as an empty array using (). The length of the array is determined using ${#array[@]} and stored in the variable length. The script then prints the length of the array, which is 0.

Find length of an empty array in Bash

3. Find Length of an Array from User Input

This script initializes an array with elements from user input and prints the length of the array.

#!/bin/bash

array=()
while true; do
    read -p "Enter an element (or 'done' to finish): " element
    if [ "$element" == "done" ]; then
        break
    fi
    array+=("$element")
done
length=${#array[@]}
echo "The length of the array is: $length"

In this script, the array variable array is initialized as an empty array using (). The user is prompted to enter elements, which are added to the array using the += operator. When the user types 'done', the loop exits. The length of the array is determined using ${#array[@]} and stored in the variable length. The script then prints the length of the array, which includes the elements entered by the user.

Find length of an array from user input in Bash

Conclusion

Finding the length of an array in Bash is a fundamental task for determining the number of elements in an array in shell scripting. Understanding how to find the length of arrays can help you manage and manipulate arrays effectively in your scripts.