I am trying a simple for loop which is throwing an error.
Below is my code:
#/bin/sh
set -A array "are" "you" "there";
for ( i = 0 ; i < ${#array[@]} ; i++ )
do
echo ${array[$i]}
done
I am getting this error
tci001wasd02 $ sh -vx array_for.sh
#/bin/sh
set -A array "are" "you" "there";
+ set -A array are you there
for ( array_for.sh[5]: 0403-057 Syntax error at line 5 : `(' is not expected.
I did the while loop so that it would not be dependent on the array size but I see from your while loop that you were not concerned about that. So, for loop looks like this:
#/bin/sh
array=( are you there )
#for i in 0 1 2
for i in ${!array[@]}
do
echo ${array[$i]}
done
@cfajohnson,
Thanks for pointing out the errors, i have changed the sh to ksh93.
But even now i am not able to run the for command.
tci001wasd02 $ cat array_for.sh
#/bin/ksh93
set -A array "are" "you" "there";
for (( i = 0 ; i < ${#array[@]} ; i++ ))
do
echo ${array[$i]}
done
tci001wasd02 $ sh -vx array_for.sh
#/bin/ksh93
set -A array "are" "you" "there";
+ set -A array are you there
for ((array_for.sh[5]: 0403-057 Syntax error at line 5 : `(' is not expected.
the command u mentioned above
for i in "${!array[@]}"
will give me all the elements in the array. But i want only certain elements from the array, which i wanted to do it using a for loop...
I would use the more portable (though arrays are not standard) form of assigning an array:
array=( are you there ) ## doesn't work in ksh88, AFAIK
Then use the standard syntax.
(That works for me in ksh93; perhaps you are using a different version of ksh93. All the more reason to use the standard syntax; it will work in all versions and other shells.)
Both forms give you all the elements in the array. You have to select the ones you want inside the loop.
Always use the standard syntax when possible without losing efficiency. Non-standard features may (and often do) change from one verion of a shell to the next.