When you are dealing with arrays in bash, you may find yourself in a situation where you need to find the array length.
Thankfully, bash provides the length expression for this purpose:
${#array_name[@]}
You may also run a for loop and calculate the length but that’s quite primitive.
Let’s see it in detail with examples.
Finding array length in bash
Contents
Throughout the tutorial, I will be using a simple array named my_array
which contains the following values:
my_array=("apple" "banana" "cherry" "date" "elderberry")
And I will store this array inside a bash script named Array.sh
so you’d have a better idea while I’d jump to the how-to part.
1. Using length expression (recommended)
This is the easiest and most effective way to find the length.
And there’s a reason for that. All you need is two lines of code to print the value!
The length expression stores the length of the array so all you have to do is store the value inside a variable and print it!
Pretty simple. Right?
For example, here’s my bash script, which will print the length of my array:
#!/bin/bash # Declare an array
my_array=("apple" "banana" "cherry" "date" "elderberry") # Get the length of the array
array_length=${#my_array[@]} # Print the array length
echo "Array length: $array_length"
Now, let’s breakdown the script:
my_array
: It is an array that holds certain values and I have to find out its length.array_length
: It stores the value of length expression which means this variable has a value of 5.echo
: Simply prints the value ofarray_length
.
And if you execute my script, you should expect the following output:
2. Using for loop (not recommended)
This is an advanced form of the above method where it uses the same length expression but with the for loop in bash to print the value.
Here’s the bash script which I will be using:
#!/bin/bash # Declare an array
my_array=("apple" "banana" "cherry" "date" "elderberry") # Initialize a counter variable
Array_length=0 # Loop through the array elements and increment the counter
for element in "${my_array[@]}"; do ((Array_length++))
done # Print the array length
echo "Array length: $Array_length"
Now, let’s breakdown the script:
Array_length
: It is an integer that has a predefined value of 0 and will increase based on loop iterations.for ... done
: This is the for loop which will be iterated as many times as the size of anmy_array
array.echo
: Prints the value ofArray_length
.
And if you were to execute the above script, be sure to make it executable using the chmod command.
Here’s what to expect if you execute the above script:
And there you have it!
Learn Bash scripting for Free
If you’re interested in learning the bash, it is always a good idea to start from scratch.
And to make things easy, we created a dedicated series that would cover all the basics for the bash:
I hope you will find this guide helpful.