KSH For Loop Array: Iterate Through Array Values

In Korn Shell (KSH), you can use a for loop to iterate through an array of values. Here’s an example:

#!/usr/bin/ksh

# Define an array
fruits=(apple banana orange)

# Iterate through the array
for fruit in ${fruits[@]}
do
echo "I like to eat $fruit"
done

In this example, we define an array named fruits that contains three values: apple, banana, and orange. We then use a for loop to iterate through the array, assigning each value to the variable fruit in turn. Within the loop, we use the echo command to print a message that includes the current value of fruit.

When you run this script, it will output the following:

I like to eat apple
I like to eat banana
I like to eat orange

In the for loop, ${fruits[@]} is used to reference all the elements in the fruits array. The @ symbol is used to expand the array to a list of its values. The loop then iterates over each element in the array and sets the fruit variable to the current value.

By using this method, you can easily iterate through an array of values in Korn Shell (KSH).

Leave a Comment