Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Bash Array Size
  • Conclusion

Ways to Find Bash Array Length

PreviousBash Arrays ExplainedNextBash Split String by Delimiter

Last updated 1 year ago

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.

Bash Array Size

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.

Array length using @

We can find the number of members in the array using the @ symbol as follows:

Syntax

echo ${#arr[@]}

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.

Array length using *

We can also find the array length using the @ symbol as follows:

Syntax

echo ${#arr[*]}

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.

Array length using grep

The grep command is an extremely useful tool to filter searches. The keywords can be strings, particular patterns of characters, or regular expressions.

Syntax

grep [flags] pattern [files]

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.

Array length using wc command

The wc command is an equally helpful tool to get count of words, characters or lines.

Syntax

wc [OPTION]... [FILE]...

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.

The difference

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:

books=(book1 book2) 

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"

Conclusion

  • 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.

array
find array length with grep
find array length using *
find array length using @
find array length with wc