Ways to Find Bash Array Length
Last updated
Last updated
Knowing the length of the array plays an important role in automating the flow or running the script as a cron job. We can loop through the array elements seamlessly. The data can be stored as well as fetched from these elements in an organized manner.
In this tutorial, we learn different ways to find the bash array length.
In Bash, there is no limit on the size of an . The array members need not be indexed or assigned contiguously as well. Knowing the size of the array, we can iterate over all the elements using the available loops.
We can find the number of members in the array using the @ symbol as follows:
Syntax
Example:
#!/bin/basharr=("Pushkin"
"Tolstoy"
"Chekhov"
"Gorky"
"Turgenev")echo
${#arr[@]}
The presence of @ expands all the elements of the array. Prefixing the # symbol to that array variable finds the number of members present. [@] also preserves spaces within the tokens. When parsing the array, Bash splits it into a series of words which are separated by spaces.
We can also find the array length using the @ symbol as follows:
Syntax
Example:
#!/bin/basharr=("Pushkin"
"Tolstoy"
"Chekhov"
"Gorky"
"Turgenev")echo
${#arr[*]}
The * symbol is a quantifier which means "match zero or more". When placed inside the array variable it pulls all the array members. Just like we did last time, prefixing the # symbol to that array variable will give us the array length.
The grep command is an extremely useful tool to filter searches. The keywords can be strings, particular patterns of characters, or regular expressions.
Syntax
Example:
#!/bin/basharr=("Pushkin"
"Tolstoy"
"Chekhov"
"Gorky"
"Turgenev")result=$(echo
${arr[@]} | grep
-o " "
| grep
-c " ")if
[ $result -gt 0 ]then expr
$result + 1else if
[ ! -z "${arr[0]}"
] then expr
$result + 1 else echo
$result fifi
We learned above that while parsing the array with the @ symbol, Bash splits it into a series of words that are separated by spaces. Hence, we are using a blank space as the pattern for grep. The grep command used with -o option only pulls the matching pattern, which is a space. The -c option only prints the count of the lines that match the pattern. Everything put together, we are sending the output of the echo command as an input to the grep command using the pipe "|" operator. The result after the second pipe is a number indicating the number of spaces. Adding 1 to it will give us the total number of words in the array, provided the array has more than 1 element. Even if it has one element, the number of spaces will be 0. Hence, we check if the first element exists or not. If it does, we add 1, otherwise return the result which will be 0.
The wc command is an equally helpful tool to get count of words, characters or lines.
Syntax
Example:
#!/bin/basharr=("Pushkin"
"Tolstoy"
"Chekhov"
"Gorky"
"Turgenev")echo
${arr[@]} | wc
-w
We have employed the same approach which we did with grep to find the array size. The result of the echo command is being piped as an input to the wc command. This command when used with the -w option counts the number of words available in the provided input.
Let’s look at another example and use all 4 methods we have understood so far:
#!/bin/basharr=("Alexander Pushkin"
"Leo Tolstoy"
"Anton Chekhov"
"Maxim Gorky"
"Ivan Turgenev")echo
Length of array:echo
"----Using @----"echo
${#arr[@]}echo
"----Using *----"echo
${#arr[*]}echo
"----Using grep----"expr
$(echo
${arr[@]} | grep
-o " "
| grep
-c " ") + 1echo
"----Using wc----"echo
${arr[@]} | wc
-w
From this example we learn that we cannot completely rely on grep and wc command. Since they count the number of words based on spaces to get the array size, they will eventually get a wrong result if the data in array elements themselves contain spaces.
The difference between [@] and [*]-expanded arrays in double-quotes is that "${myarr[@]}" leads to each element of the array being treated as a separate shell-word, while "${myarr[*]}" results in a single shell-word with all of the elements of the array separated by spaces.
To simplify this even further, say we have an array as follows:
ls "${books[*]}" is equivalent to ls "book1 book2", which will make bash look for a single file named book1 book2.
ls "${books[@]}" is equivalent to ls "book1" "book2"
The length of Bash arrays helps to iterate over the elements.
Prefixing the # symbol to that array variable returns the array size.
There are different approaches to get the array length and we also learned how they differ.