You can use the following methods to determine the length of an array in Bash:
- Using Length Expression ${#array[@]}:
echo "${#your_array[@]}"
- Using Loop:
array_length=0 # Initialize a variable to store the array length #iterate and fetch the array length for element in "${array[@]}"; do ((array_length++)) done
The length of an array in Bash is the total number of elements present in the array. Understanding array length is crucial considering the operations such as array iteration including working with each element. This article discusses several methods on how to get the array length in Bash. It mentions basic techniques using the standard length expressions to advanced techniques using commands and Bash loops to measure the array length in Bash. Additionally, it discusses the essential concept of array size including array length with their distinctive attributes.
What is Array Length and Array Size in Bash?
You must have heard the terms array length and array size used from time to time by the coders and developers. Although they seem to have the same meaning, the terms have a rudimentary distinction that I will mention below using their standard definition:
1. Array Length in Bash: In the context of arrays, the attribute length determines the number of elements the array contains. It is the most pertinent metric that lets you know how many items the array currently has and is often used in looping tasks for specified data-managing goal accomplishment. Now, look at the array mentioned below:
hello_reader=("harryPotter" "greatGatsby" "vinciCode")
The length of the array hello_reader is 3. Isn’t it obvious?
2. Array Size in Bash: The array size represents the memory/storage space allocated to that array. It makes more sense in programming languages such as C and C++, where the manual allocation/deallocation of memory is a must.
6 Methods to Get the Length of a Bash Indexed Array
You can get the length of an indexed array in Bash by employing several user-friendly methods. In this section, I will guide you through 6 effective methods to print the length of an indexed array via Bash scripting.
1. Using the Expression Syntax ${#array[@]} and ${#array[*]}
The two length expressions ${#array[@]} or ${#array[*]} in Bash with the echo command as the prefix seamlessly get the array length. Let’s look at the full syntax:
Syntax 01:
echo ${#array[@]}
Syntax 02:
echo ${#array[*]}
- echo: Bash command used to set the array variable attribute.
- ${ }: Used to retrieve the value of a variable.
- array_name: The name of the array you want to assign.
- [@] or [*]: Points out the referencing of all elements of the array.
Here’s an example to print an array length in Bash using the syntax echo ${#array[@]} and echo ${#array[*]}:
#!/bin/bash
#Array creation
metallica =(unforgiven1 unforgiven2 unforgiven3 )
#Array length calculation and assign to a new two variables named length and len
length=${#metallica[@]}
len=${#metallica[*]}
#printing array length to the terminal using both expressions
echo “the array length using \${#metallica[@]}: $length”
echo # for adding extra spaces between the outputs
echo “the array length using \${#metallica[*]}: $len”
In the script, metallica=(unforgiven1 unforgiven2 unforgiven3) expression creates the array metallica with 3 elements.
After that, the expressions ${#metallica[@]}
and ${#metallica[*]}
, in consecutive lines, get the array length twice and store the values in the length
and len
variables afterward. On an end note, the echo command twice prints the length to the prompt followed by the variable names prefixed with $ sign to access the numeric value (3, in this case).
2. Using the “wc” Command with the expression ${array[@]}
You can strategically use the wc command with the length expression ${array[@]} to get the length of an array in Bash. Below, I have developed a script to show you the practical aspect:
#!/bin/bash
# Array creation
drummers=(vinnie portnoy lars sazu dio)
#printing items
echo "the items: ${drummers[@]}"
#getting length using wc command and assigning variable
arr_len=`echo ${drummers[@]} | wc -w`
#printing the length
echo "The array length is $arr_len"
In the above Bash script, drummers=(vinnie portnoy lars sazu dio) creates an array named drummers with 5 values. Then, the echo command prints the elements incorporating the expression ${drummers[@]}
. After that, the expression `echo ${drummers[@]} | wc -w` determines the array length. Here, the ${drummers[@]} expression takes all the elements of the array as a single string and pipes to the wc
-w command. The -w option counts the number of words (the array elements in this case) and stores the value to the arr_len
variable. Finally, the echo command prints the length.
In the following script, I will create an array and fetch the length twice using two methods to show you that the wc command cannot figure out the array length of elements having multi-word strings:
#!/bin/bash
# Array creation with elements that have multiple words
drummers2=("vinnie paul" "mike portnoy" "lars ulrich" "kazi sazu" "dio haque")
#printing the array elements
echo "the items: ${drummers2[@]}"
echo #to create an extra space in between
#getting length using the wc command and assigning a variable
len=`echo ${drummers2[@]} | wc -w`
#printing the actual length
echo "the actual array length: ${#drummers2[@]}"
echo #to create extra space in between
#printing the wrong length using wc
echo "The array length is using wc: $len"
In the aforementioned Bash script, the fourth line creates an array named drummers2 with 5 items (multi-word strings). Following this, the echo command prints the elements of that array to the prompt. After that, the expression `echo ${drummers2[@]} | wc -w` calculates the array length and stores the final value to the len variable. In addition, the ${#drummers2[@]}
expression obtains the length of the array. Finally, the echo command operates twice and prints both results.
3. Using the “grep” Command with the expression ${array[@]}
Similarly, there’s another command called grep that you can utilize with ${array[@]} to determine the length of a bash array. It is not recommended to use the grep command to get the array length in Bash. However, if you want to adopt this method for some reason, follow the below script namely array_length_grep.sh:
#!/bin/bash
#array creation with 5 elements
arr=("Pushkin" "Tolstoy" "Chekhov" "Gorky" "Turgenev")
#determining and storing the array length into result variable
result=$(echo ${arr[@]} | grep -o " " | grep -c " ")
#necessary checking on the result value before final printing
if [ $result -gt 0 ]
then
expr $result + 1
else
if [ ! -z "${arr[0]}" ]
then
expr $result + 1
else
echo $result
fi
fi
Here, arr=(“Pushkin” “Tolstoy” “Chekhov” “Gorky” “Turgenev”) directly creates an indexed array named arr with 5 elements. Then, the grep command fetches the array length and stores it in the variable result. The detailed view of the expression is below:
- ${arr[@]}: Expands to all elements in the array as a single string.
- grep with -o option: Searches for space characters and outputs them individually.
- second grep with -c option: Counts the occurrences of spaces.
- result: A variable holding the number of spaces, which is one less than the number of elements in the array.
Now, follow the below steps to complete your understanding of the looping part.
- First, the script checks if the result (the count of spaces) is greater than 0.
- Secondly, if the result value is greater than 0, the value is incremented by 1 by the expr $result + 1
- Then, if the result is not greater than 0, the code checks if the first element of the array (arr[0]) is not empty using [ ! -z “${arr[0]}” ]. If it’s not empty, it uses expr to increment the result by 1.
- Again, if the first element of the array is empty and the result is not greater than 0, it just prints the original value of the result.
4. Using “For Loop”
Leveraging Bash for loops to access elements of an indexed array is a fundamental strategy in data handling. In addition, you can smartly utilize this technique to acquire the length of that array.
Here’s an example to find the array length in Bash using for
loop:
#!/bin/bash
#create an indexed array with elements
my_array=(1 2 3 4 5)
# Initialize a counter
length=0
# Use a for loop to iterate through the elements
for element in "${my_array[@]}"; do
((length++))
done
#printing array elements
echo "elements: ${my_array[@]}"
#printing array length
echo "length: $length"
In this script, my_array=(1 2 3 4 5) command creates an array named my_array with 5 values. Following this, the length
variable keeps track of the number of elements. Then, Bash for loop iterates through the entire array using the ${my_array[@]}
expression and increments the value of length
by 1 for each iteration advancement until all the elements are covered. Finally, the echo command operates twice: 1. To print the elements to show you the number of entries, and 2. To print the length and verify that the code runs without issues and fetches the length correctly.
for ((i = 0; i < ${#my_array[@]}; i++)); do
((length++))
done
5. Using “While Loop”
Exploiting the potential of the while loop is a very pragmatic as well as versatile approach toward the determination of the indexed array length in Bash. Let’s see this technique in action via a Bash script:
#!/bin/bash
# Create an indexed array
my_array=("element1" "element2" "element3" "element4")
# Initialize counter for keeping track of the length
length=0
# while loop to iterate through the elements
while [ -n "${my_array[$length]}" ]; do
((length++))
done
#print the array length
echo "This is an indexed array with length: $length"
In this Bash script, my_array=(“element1” “element2” “element3” “element4”) expression creates an array with 4 items named my_array
. After that, the while loop continues as long as it finds elements and increments the length by 1. Here, the length
variable tracks the array length. Finally, the echo command prints the array’s length by fetching the value from the $length
expression.
6. Using “Until Loop”
Bash scripting provides the users with another loop called the until loop. This is a powerful tool if you can utilize it to its full potential and obtain the length of an indexed array.
Take a look at the script below for clarity on getting Bash array length using until loop:
#!/bin/bash
# Declare an indexed array with 4 values
hannibal=(lecter will abigail jack)
# Initialize a counter
length=0
# Use an until loop to iterate through the array
until [ -z "${hannibal[$length]}" ]; do
((length++))
done
#print the array length
echo "The length of the indexed array is $length"
In the above script length_loop3.sh, the command hannibal=(lecter will abigail jack) creates an indexed array hannibal
with 4 elements. In addition, the variable length
keeps the iteration track using the until loop starting from 0. Now, the until loop continues as long as the given condition is false. In this case, the [ -z "${hannibal[$length]}" ]
condition checks if the index represented by the length
variable in hannibal
array has an empty string and length++
increases the value of length by 1 for iteration advancement. On an end note, the echo command prints the array length to the prompt.
3 Ways to Get the Length of a Bash Associative Array
In a similar manner, getting to know the length of a Bash Associative array is essential in working with data. You can employ 2 methods ( using length expression and loops) for array length calculation which is also the target of this upcoming feature.
1. Using Length Expressions ${#array[@]} and ${#array[*]}
Like the previous scope, you can simply use the length expressions ${#array[@]} and ${#array[*]} to find the length of an associative array in Bash. In associative arrays, the items are stored in key-value pairs and the ${#array[@]} and ${#array[*]} expressions count the number of the key-value pairs which is exactly the length of the specified array.
Follow the script below carefully to understand how to print Bash associative array length:
#!/bin/bash
#crearting an associative array
declare -A vocals
#populate the array with values
vocals[artcell]=lincoin
vocals[black]=jon
vocals[crypticFate]=shakib
vocals[nemesis]=zohad
#getting the length and storing into variable
length=${#vocals[@]}
len=${#vocals[*]}
#printing array length to the terminal using both expressions
echo "the array length using \${#vocals[@]}: $length"
# an extra echo command for adding extra spaces between the outputs
echo
echo “the array length using \${#vocals[*]}: $len”
First, declare -A vocals
command creates an empty associative array namely vocals
with the insertion of 4 values using keys. After that, the length expressions ${#vocals[@]}
and ${#vocals[*]}
fetch the length. On a final note, the two variables length and len store the array length and the echo command prints the length twice to the terminal.
2. Using “for Loop”
Apart from indexed arrays, the Bash for loop can get the associative array length. That being said, see the below script named assoc_length_loop1.sh to understand the array length retrieving procedure:
#!/bin/bash
#array declare
declare -A places
#value initialization
places[roll1]=Mostafa
places[roll2]=Das
places[roll3]=Masrur
# Initialize a counter
length=0
# Use a for loop to iterate through the
for key in "${!places[@]}"; do
((length++))
done
#printing the length
echo "length of this associative array is $length"
First, the declare -A
command declares an associative array named places, and 3 values are initialized afterward. In addition, the variable namely <strong>length </strong>
keeps track of each iteration item for length calculation. After that, the for loop increments the value of length by 1 and it stops when all the array elements are covered. Finally, the echo command prints the value of the variable length to display the length of the places array.
3. Using While Loop
Though not among the popular strategies for acquiring the array length in Bash, you can still make use of the while loop to print the length of an associative array in Bash. Just navigate to the following script:
#!/bin/bash
# Declare an associative array with value initialization
declare -A RSA
RSA["key1"]=kallis
RSA["key2"]=AbD
RSA["key3"]=miller
# Initialize a counter
length=0
# Use a while loop to iterate through the keys
while IFS= read -r key; do
((length++))
done < <(printf "%s\n" "${!RSA[@]}")
#printing the length
echo "The length of the associative array is $length"
In developing the above Bash script, first, the declare -A RSA
command declares an associative array called RSA along with initializing with 3 values using the expression RSA["key"]=value
. Then, the variable length keeps track of the number of elements of the array. After that, the while loop stores the value of the array length to the counter variable length. The step-by-step breakdown of the while loop is:
- while: The while loop continues till the iterating condition is satisfied.
- IFS: It sets the Internal Field Separator (IFS) to empty string for preserving leading and trailing spaces.
- read -r key: This command reads the key from the associative array and stores it in the key
- length++: Increases the value of the length variable by 1 with each iteration to preserve the array length.
- (printf “%s\n” “${!RSA[@]}”): Takes the keys and prints on a separate line each.
- < <: Process substitution taking the output of (printf “%s\n” “${!RSA[@]}”) expression and supplies it as input to the while loop.
Lastly, the echo command prints the value of the final length.
Conclusion
To sum up, I have tried to provide you with an in-depth analysis of determining array length in Bash employing several hands-on examples. So, after reading this article, you will be able to write efficient code and elevate your script development capability.
People Also Ask
How to find the length of a Bash array?
To find the length of an array in Bash, just use the code ${#array[@]} with the echo command. For example: the full syntax echo ${#array[@]}
will return the length of the array to the terminal screen.
Can I store the length of a Bash array into a variable for later use?
Certainly. You can find the length of a Bash array using the expression syntax ${#array[@]} and assign the value to another variable like this: Length=${#array[@]}
. In this way, the Length variable will store the array length which you can avail for later use.
Is there any limitation in the size of Bash arrays?
No, Bash arrays are dynamic natured and this lets you work with arrays of unlimited size as there is no maximum limit on the Bash array size.
Is it possible to check if a Bash array is empty?
Yes, it is. Use the code ${#array[@]}
to get the length of array, and if it returns 0, then it means that the specified array is empty.
Does Bash have 0-indexed arrays?
Yes, Bash has indexed arrays which are indeed 0-based. This means the first item assignment starts from zero and increases by 1 after every insertion of elements. However, you can assign items at any random index if you want.
What is an array in Bash?
A Bash array is a data structure used to store information in an indexed way. The indexed array in Bash has numbered indices while the associative arrays have string indices called keys.
Can I print the length of a Bash array with null values?
Absolutely. You can use the standard syntax echo ${#array[@]}
to get and print the length of the Bash array even if it contains null values. For instance, consider the array fruit_null=("" "apple" "" "banana" "")
. If you print its length using echo "${#fruit_null[@]}"
, it will return 5 as the final output by counting the null elements as valid array elements.
Related Articles
- Declare Array in Bash [Create, Initialize]
- How to Read into Bash Array [3 Methods]
- Index Array in Bash [Explained]
- Bash Associative Arrays [Explained]
- Bash Array of Arrays [Explained]
- Elements of Bash Array
- How to Print an Array in Bash? [5 Methods]
- Array Operations in Bash
<< Go Back to Bash Array | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners