Quantcast
Channel: UNIX and Linux Forums
Viewing all articles
Browse latest Browse all 16232

Question on iterating array elements

$
0
0
Hi,

I am trying to do something similar to the for loop example from KSH For Loop Array: Iterate Through Array Values

Code:

$: cat y.ksh
#!/bin/ksh
# set array called nameservers
set -A nameservers 192.168.1.1 192.168.1.5 202.54.1.5

# print all name servers
for i in ${nameservers[@]}
do
        echo $i
done
$: ./y.ksh
192.168.1.1
192.168.1.5
202.54.1.5

My test script looks like below:

Code:

#!/bin/ksh
#
#

set -A arrSID
set -A arrVERSION

arrVERSION[1]="Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production"
arrVERSION[2]="Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production"

echo
echo
for i in ${arrVERSION[@]}
do
  echo $i
done
echo
echo

It's output when I run it is as below:

Code:

$: ./x.ksh


Oracle
Database
11g
Enterprise
Edition
Release
11.2.0.4.0
-
64bit
Production
Oracle9i
Enterprise
Edition
Release
9.2.0.8.0
-
64bit
Production

I managed to use the while loop below and manage to get the output that I wanted.

Code:

$: ./z.ksh
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
$: cat z.ksh
#!/bin/ksh
#
#

set -A arrSID
set -A arrVERSION

arrVERSION[1]="Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production"
arrVERSION[2]="Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production"

i=1
while [[ $i -le ${#arrVERSION[@]} ]]
do
  echo ${arrVERSION[$i]}
  (( i=i+1 ))
done

exit 0

I just want to know why the for loop, i.e. the x.ksh, does not work like I expect it to be? I am guessing it is due to the spaces in the string. Is there any way around it. I just thought it is easier to use the for loop instead of the while loop.

Anyway, any feedback much appreciated. Thanks.

Viewing all articles
Browse latest Browse all 16232

Trending Articles