How To Find BASH Shell Array Length ( number of elements )

by on March 27, 2008 · 16 comments· LAST UPDATED December 13, 2008

in , ,

Q. How do I define array in a bash shell script? How do I find out bash array length (number of elements) while running a script using for shell loop?

A. Bash provides one-dimensional array variables. Any variable may be used as an array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.

How do I define bash array?

Array can be defined using following syntax:
ArrayName=("element 1" "element 2" "element 3")
Define array called distro with 3 elements, enter:

distro=("redhat" "debian" "gentoo")

How do I reference any element in bash array?

Any element of an array may be referenced using following syntax:

${ArrayName[subscript]}

To print redhat i.e first element enter:

echo ${distro[0]}
echo ${distro[2]}  # will print gentoo

How do I find out bash shell array length?

You can easily find out bash shell array length using following syntax:

${#ArrayName[@]}

To print distro array length enter:

echo ${#distro[@]} 

Sample output:

3

If subscript is @ or *, the word expands to all members of name. By prefixing # to variable you will find length of an array (i.e number of elements).

Putting it all together

A sample shell script to print array called NAMESERVERS:

#!/bin/bash
# define array
# name server names FQDN 
NAMESERVERS=("ns1.nixcraft.net." "ns2.nixcraft.net." "ns3.nixcraft.net.")
 
# get length of an array
tLen=${#NAMESERVERS[@]}
 
# use for loop read all nameservers
for (( i=0; i<${tLen}; i++ ));
do
  echo ${NAMESERVERS[$i]}
done

Sample output:

ns1.nixcraft.net.
ns2.nixcraft.net.
ns3.nixcraft.net.
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 16 comments… read them below or add one }

1 S. Nilesh July 27, 2008 at 4:47 pm

Nice one ;)

Reply

2 Diya July 28, 2008 at 8:20 am

Excellent info.

Reply

3 those August 5, 2008 at 8:04 pm

how to clean the array? ;d

Reply

4 Dan June 16, 2010 at 7:39 pm

Here’s a quick flush:
NUM=${#a[@]}; for ((i=0;i<${NUM};i++)); do a[${i}]=''; done

And a for a quick scan, you can do the following either before or after:
COUNT=0; while [ ${COUNT} -lt ${#a[@]} ]; do echo ${a[${COUNT}]}; COUNT=$((COUNT+1)); done

Reply

5 budacsik September 20, 2008 at 12:18 pm

Hi!
I think that this example is bad.
I would do this without a block .

#!/bin/bash

NAMESERVERS=”ns1.nixcraft.net. ns2.nixcraft.net. ns3.nixcraft.net.”
for i in $NAMESERVERS; do
echo “$i”
done

Reply

6 Dan June 16, 2010 at 5:56 pm

That only works if you have no spaces.

Reply

7 Ferk January 3, 2012 at 8:48 pm

The way it’s done in the post only works when using bash. This is a more POSIX-compatible way of making it work. You can also change the element-separator character to something different than the space, using the variabe IFS.

Reply

8 Raymond February 7, 2009 at 10:11 am

Problems,

a[2]=222
echo ${#a[@]}
1

Thus this is the lenght of the array, not the index of the last element.

Try instead:
for i in “${a[@]}”; do echo $i; done

Some further ideas may be found at
http://tldp.org/LDP/abs/html/arrays.html
http://www.linuxjournal.com/content/bash-arrays

Best Regards,
Raymond

Reply

9 Dan June 16, 2010 at 7:29 pm

Well yes, ${#a[@]} pretty much spits out the the number of elements in the array, like the document here said… notice that it’s plainly used as tlen which is the length of the array?

you could do it a million different ways…

NUM=${a[@]}
for ((i=0;i<${NUM};i++)); do echo ${a[${NUM}]}; done

or:

COUNT=0; while [ ${COUNT} -lt ${#a[@]} ]; do echo ${a[${COUNT}]}; COUNT=$((COUNT+1)); done

We could go on and on, since there's more than one way to skin a cat.

Reply

10 Stuart Holme October 27, 2010 at 3:35 pm

Good points on handling a possibly sparse array, Raymond, but the example is pretty useful if you load the array yourself. Also note that you don’t need to use a variable to store the array length:

for (( i = 0 ; i < ${#my_array[@]} ; i++ )) do; echo "${my_array[i]}"; done

Note the implementations of BASH I am using don't require "$i" as the index of the array, they work fine with just "i". This only seems to work with single character length index variable names though, like "i", not with, for example, "index". YMMV.

Regards,
Stuart

Reply

11 Edward August 5, 2011 at 7:17 am

1.Write a Linux shell Script to count the Number of user accounts both normal and special or privileged user user accounts on the system.
2.Write an interactive Linux shell script to test whether a file is (a). Read Permission set. (b). Execution permission set (c). Is a non empty file (d). A regular file (e). Ia a directory.

Reply

12 Ryan October 3, 2011 at 9:48 pm

lol @ all the bikeshedding syntax scholars here. Ok, your voice has been heard, move along idiots.

Reply

13 Dan January 3, 2012 at 10:30 pm

It’s called sharing knowledge. If you don’t like it, move along.

Reply

14 Jeff October 25, 2012 at 9:25 am

Dan I know this is an older thread but I found this and your information was very helpful to me. Unfortunately there are not enough people in the world like you and more like Ryan.

Thanks again!

Reply

15 Raina May 9, 2013 at 9:20 pm

Hi, Sorry i know this is an old thread!

I need a help!

for i in `seq 1 ${#DEV[@]}` ; do
  echo "DEV- ${DEV[$i]} ${DEV_DS[$i]} " >> $REPORT1

${#DEV[@]} –> this represents the length of the array

If I want to go to the second last element of the array , what can I write in place of ${#DEV[@]} ?

Reply

16 Brian June 5, 2013 at 2:59 pm

If ${#DEV[@]} is the last element then just decrement it to get the second last element.

Reply

Leave a Comment

Tagged as: , , , , , , , ,

Previous Faq:

Next Faq: