BASH Programming

How To Find the Length of an Array in Shell Script

Shell scripting is an essential skill that every Linux or Unix administrator must possess. The ability to manipulate and process data is one of the key tasks of a Linux/Unix administrator. Finding an array’s length is a frequent operation in shell scripting. The total number of elements in an array determines the array’s length. We will look at various shell scripting techniques in this post to determine an array’s length.

How To Find the Length of an Array in Shell Script

Finding the length of an array in the shell can be useful for looping over elements and performing operations on them. Also, it can be used for verifying that an array has a certain number of elements before proceeding with a script, below are some ways to do it:

Method 1: Using Built-in Parameter

The simplest way to find the length of an array is to use the shell built-in parameter ${#array[@]} or ${#array[*]}. The @ and * symbols are used to reference all the elements of the array.

#!/bin/bash

my_array=(Red Blue Pink)

echo "The length of the array is ${#my_array[@]}"

Here is the output of the shell script that uses its built-in parameter to get the length of an array:

Method 2: Using expr Command

The expr command is used to evaluate an expression and print the result to standard output. We can use the wc -w command to count the number of elements in the array and pass the result to the expr command to get the length of the array.

#!/bin/bash

my_array=(Red Blue Pink)

length=$(echo ${my_array[@]} | wc -w)

echo "The length of the array is $(expr $length)"

Here is the output of the shell script that uses the expr to get the length of an array:

Graphical user interface, text Description automatically generated

Method 3: Using for Loop

We can also find the length of an array by using a for loop. In this method, we iterate through each element of the array and count the number of elements.

#!/bin/bash

my_array=(Red Blue Pink)

length=0

for i in "${my_array[@]}"

do

length=$((length+1))

done

echo "The length of the array is $length"

Graphical user interface, text Description automatically generated

Conclusion

In this article, we have explored different ways to find the length of an array in shell scripting. We have used the shell built-in parameter ${#array[@]}, the expr command, and a for loop to find the length of the array. All three methods are equally effective, and it depends on the user’s preference and requirements to choose the appropriate method.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.