You can use the following methods to determine the length of an array in Bash:
- Using Length Expression:
echo "${#your_array[@]}"
- Using “for 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
Later, in the article, I will discuss how to adopt each approach in detail to get the array length in Bash.
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.
Length of an Array 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?
Size of an Array in Bash
On the other hand, 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.
Displaying 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 two effective techniques (using length expressions and loops) to get and print the length of an indexed array via Bash scripting.
Get Indexed Array Length Using General Length Expressions
There are two general expressions in Bash that you can utilize and seamlessly get the array length. Below, I will show the usage of both expressions to retrieve the array length and it only takes exploiting the echo command with some strategies. Let’s look at the syntax:
Syntax 01 >
echo ${#array_name[@]}
Syntax 02 >
echo ${#array_name[*]}
- 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.
Okay, now, follow the below steps where I have developed a Bash script for you to see the pragmatic aspects of the aforesaid concepts.
- First, open the Ubuntu terminal.
- Secondly, run the below command to open a file on the nano editor.
nano getLength_1.sh
EXPLANATION- nano: Opens file in the nano text editor.
- getLength_1.sh: Bash script name.
- After that, copy the code below inside the Bash script:
#!/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”
EXPLANATIONIn the first line of the getLength_1.sh bash script, #!/bin/bash, #! is called shebang. It indicates the system uses the bash interpreter for executing the script. Then, 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).
- After that, press CTRL+O and ENTER to save the file; CTRL+X to exit.
- Use the following command to make the script executable.
chmod u+x getLength_1.sh
EXPLANATION- chmod: Changes permission of files and directories.
- +x: Argument to add the executable permission.
- getLength_1.sh: Bash script you want to make executable.
- Finally, run the script using the following mentioned command.
./getLength_1.sh
In the above, I have used the bash script to successfully print the length of the metallica array to the screen by using both expressions.
Obtain Indexed Array Length Using Commands.
Using length expression is the most frequent practice in Bash array length retrieval. In addition, you can make use of the various standard commands in Linux to serve the same purpose. So, in this section, I will introduce you to the obtaining of the array length in Bash using the wc and the grep commands.
1. Using the “wc” Command to Obtain Indexed Array Length in Bash
You can use the wc command in a strategic way to get the length of an array in Bash. Below, I have developed a script to show you the practical aspect.
Script (arr_length_wc.sh) >
#!/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.
Run the script using the below command:
./arr_length_wc.sh
So, in the above snap, you notice that I have printed the array length correctly which is also visible through the printing of the elements.
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.
Script (arr_length_wc2.sh) >
#!/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.
Run the script using the below command:
./arr_length_wc2.sh
In the aforementioned image, you discern the code gives an output of 10 instead of 5 which is the original array length.
2. Using the “grep” Command to Obtain Indexed Array Length in Bash
Similarly, there’s another command called grep that you can utilize smartly 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, you can follow the below approach that I will show you via script development namely array_length_grep.sh.
Script (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.
-
Run the script using the below command:
./array_length_grep.sh
The aforestated screenshot shows that I have successfully printed the array length using the grep command with the assistance of the ${arr[@]} expression.
Find out Indexed Array Length Using Loops
Looping through an array of elements to access them is a very usual technique. However, a smart use of the loops can be a very powerful tool in pursuing the length of an array. Therefore, in this section, I will mention the employing of three common loops in Bash (for loop, while loop, and until loop) to get the length of an indexed array.
1. Using “For Loop” to Get Indexed Array Length in Bash
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. Therefore, in the next scope, I will show how you can make the most of the for loop and retrieve the length of an indexed array.
That being said, I will now develop a script named length_loop1.sh below and calculate the array length using for loops.
Script (length_loop1.sh) >
#!/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.
Run the script using the below command:
./length_loop1.sh
In the snapshot above, you discern that I have printed the array length using for loop which is evident in the display of the array elements.
Syntax >
for ((i = 0; i < ${#my_array[@]}; i++)); do
((length++))
done
2. Employing “While Loop” to Get Indexed Array Length in Bash
Exploiting the potential of the until loop is a very pragmatic as well as versatile approach toward the determination of the indexed array length in Bash. So, in the coming section, I will talk about this technique via script development.
Script (length_loop2.sh) >
#!/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.
Run the script using the below command:
./length_loop2.sh
Here, in the aforestated snap, you spot that I have used the while loop to know the length of the array my_array.
3. Applying “Until Loop” to Get the Indexed Array Length in Bash
Bash scripting provides the users with another loop called the until loop. This really is a powerful tool if you can utilize it to its full potential. In this section, I will exploit it to obtain the length of an indexed array.
Following this, take a look at the script that I have attached for you for the sake of clarity.
Script (length_loop3.sh) >
#!/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.
Run the script using the below command:
./length_loop3.sh
In this image, I have displayed the printing of the length of the array hannibal using until loop.
Displaying 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. On top of that, you can employ the methods above (length expression and looping methods) for array length calculation, and discussion on them is also the target of this upcoming feature.
Determine Associative Array Length Using General Length Expressions
Like the previous scope, you can simply use the length expressions to find the length of an associative array in Bash. In associative arrays, the items are stored in key-value pairs. Hence, the ${#array[@]} and ${#array[*]} expressions count the number of the key-value pairs which is exactly the length of the specified array.
At this point, I will show you the usage of the above expressions that return the array length as the final result. Follow the script below carefully.
Script (get_assoc_length_1.sh) >
#!/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.
Run the script using the below command:
./get_assoc_length_1.sh
In the above snapshot, I have printed the length (which is 4) of the vocals array without any issues employing both the length expressions.
Acquire Associative Array Length Using loops
Like in the case of indexed arrays, the looping technique is also helpful to fetch you the length of an associative array in Bash. So, in this section, I will dive deeper to make you understand the iterating concepts to obtain the array length in Bash associative arrays using both the for loop and while loop.
1. Utilizing “For Loop” to Retrieve Associative Array Length in Bash
The agenda of this section is to introduce you to the practical aspects of the iterating concept (using for loop) in Bash to know the associative array length. That being said, I will attach a Bash script named assoc_length_loop1.sh to show you the array length retrieving procedure.
Script (assoc_length_loop1.sh) >
#!/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 length 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.
Run the script using the below command:
./assoc_length_loop1.sh
In this above program, I have used for loop to iterate through the array elements and finally print its length.
2. Using “While Loop” to Obtain Associative Array Length in Bash
Though not among the popular strategies for acquiring the array length in Bash, you can still make use of the while loop. So, now, I will use the while loop to print the length of an associative array in Bash. Just navigate to the following script.
Script (assoc_length_loop2.sh) >
#!/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.
Run the script using the below command:
./assoc_length_loop2.sh
So, the above image shows that I have fetched the length of the associative array RSA using the while loop.
Conclusion
To sum up, I have tried to provide you with an in-depth analysis of determining array length in Bash employing a number of 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 check an array length in a shell script?
You can use the echo command in the format echo ${#array_name[@]} to get the length of an array in shell scripting.
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.
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.
Does Bash have arrays?
Yes, Bash provides you with one-dimensional indexed and associative arrays. Moreover, you can define these bash arrays in a variable of array type for data storage and manipulation.