Computing.Net > Forums > Unix > Array size in shell script?

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Array size in shell script?

Reply to Message Icon

Name: walty
Date: November 12, 2003 at 19:22:39 Pacific
OS: LINUX
CPU/Ram: P4
Comment:

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.




Sponsored Link
Ads by Google

Response Number 1
Name: WilliamRobertson
Date: November 13, 2003 at 01:36:09 Pacific
Reply:

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.


0

Response Number 2
Name: walty
Date: November 13, 2003 at 02:39:23 Pacific
Reply:

Thank you very much!!!! :)

${#myarray[*]}

works (in my sh)!!!!


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

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


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: Array size in shell script?

loops in shell scripts!!! www.computing.net/answers/unix/loops-in-shell-scripts/5140.html

Using hex-code in shell script www.computing.net/answers/unix/using-hexcode-in-shell-script/4227.html

SQL in shell script www.computing.net/answers/unix/sql-in-shell-script/5538.html