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.
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.
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:
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.
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"
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.