Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Do arrays work in the posix shell?

SOLVED
Go to Solution
Regular Advisor Regular Advisor

Do arrays work in the posix shell?

Trying to use arrays in the hpux posix shell and either I'm too dumb to interpret the manual page, or the shell's just broken in this respect.

Tell me I'm dumb! :-)

Could someone provide a working example of how to assign three values to one array variable and then reference them?
Hockey PUX?
5 REPLIES
Acclaimed Contributor Acclaimed Contributor

Re: Do arrays work in the posix shell?

Hi Trever:

Try this:

# cat .sharray
#!/usr/bin/sh
set -A ARY this works for you
echo ${ARY[0]}
echo ${ARY[1]}
exit 0

# ./sharray
this
works

...Regards!

...JRF...
Regular Advisor Regular Advisor

Re: Do arrays work in the posix shell?

Thanks, James.

You definitely did exactly what I asked, and now having seen that I realize I was very close in my own attempts, but I had forgotten the numbering started at 0, so when I was assigning using "set" and then referencing ${a[1]}, the shell was telling the truth when it claimed the variable wasn't set. D'OH! :-)
Hockey PUX?
Honored Contributor Honored Contributor

Re: Do arrays work in the posix shell?

The set -A directive is quite nice as it can not only declare the array but assign some of all the values you need at one time. And the elements may be strings:

set -A REASON \
"exceeded password lifetime" \
"exceeded last login time" \
"exceeded absolute account lifetime" \
"exceeded unsuccessful login attempts" \
"password required and a null password" \
"administrator lock" \
"password is a * (asterisk)"

You can display all the defined elements with @ like this:

echo "${REASON[@]}"

or show the elements by number:

for N in 0 1 2 3 4 5 6
do
echo "$N = \"${REASON[$N]}\""
done
Honored Contributor Honored Contributor

Re: Do arrays work in the posix shell?

Hi,

to make Bill's solution a little more general, you can loop through an array without explicitly naming the indices:
Change
>>
for N in 0 1 2 3 4 5 6
do
echo "$N = \"${REASON[$N]}\""
done
<<

To

typeset -i N=-1
while [ N+=1 -lt ${#REASON[*]} ]
do print $N = \"${REASON[N]\"
done

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Highlighted
Regular Advisor Regular Advisor

Re: Do arrays work in the posix shell?

Thanks, guys. I assigned 5 points each for the additional info, since James had already scored the 10.
Hockey PUX?