Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Dear all,
I wonder how to find the size of an array in shell script. For example, I declared an array as following:
#! /bin/sh
a = (1 adf 8 2 se)How could I get the size of the array a?
I had searched the google for one night, and found nothing...... :(
Thanks for your help.
Have a nice day
walty.

The various shells support arrays differently, except sh and csh which don't seem to support them at all. (The example you posted didn't work for me.)
In ksh and zsh:
set -A myarray First Second Third
echo "myarray has ${#myarray[*]} elements."
echo "myarray contains: ${myarray[*]}"In bash there is no "set -A", you just assign values directly to elements (the shell defines or redefines an array variable implicitly). This also works in ksh and zsh.
You can use any arithmetic expression for the array index, including for example the length expression itself:
myarray[${#myarray[*]}]=Furthermore
Note that shell arrays start at zero by default. Also behaviour varies between shells e.g. if you assign
newarray[94]=Testvalue
echo ${#newarray[*]}
ksh and bash report 1 element, zsh reports 94.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |