KSH For Loop Examples

Q. How do I use for loop in Korn Shell under UNIX / Linux / BSD / OS X operating systems?

A.The main advantage of ksh over the traditional Unix shell is in its use as a programming language. KSH support for loop.

KSH Scripting: for loop syntax

The syntax is as follows:

for {Variable} in {lists}
do
	echo ${Variable}
done

for {Variable} in {lists}
do
echo ${Variable}
done

Here is sample shell script to print welcome message 5 times:

#!/bin/ksh
for i in 1 2 3 4 5
do
  echo "Welcome $i times"
done

#!/bin/ksh
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done

Run script as follows:
$ chmod +x script.ksh
$ ./script.ksh

OR
$ ksh script.ksh
You can easily set ranges (1 to 10) as follows:

#!/bin/ksh
for i in {1..10}
do
  echo "Welcome $i times"
done

#!/bin/ksh
for i in {1..10}
do
echo "Welcome $i times"
done

You can also use variables to define the item list. They will be checked ONLY ONCE, when you start the loop.

#!/bin/ksh
files="/etc/passwd /etc/group /etc/hosts"
for f in $files; do
	if [ ! -f $f ]
	then
 		echo "$f file missing!"
	fi
done

#!/bin/ksh
files="/etc/passwd /etc/group /etc/hosts"
for f in $files; do
if [ ! -f $f ]
then
echo "$f file missing!"
fi
done

Please do NOT quote “$list”, if you want the for command to use multiple items.
Another example using for explicit list:

#!/bin/ksh
for car in bmw ford toyota nissan
   do
   print "Value of car is: $car"
done

#!/bin/ksh
for car in bmw ford toyota nissan
do
print "Value of car is: $car"
done

KSH For Loop Command Substitution

Create a text file called spaceshuttles.txt as follows:

columbia
endeavour
challenger
discovery
atlantis
enterprise
pathfinder

Now create a shell script called demo.ksh

#!/bin/ksh
for shuttle in $(cat  spaceshuttles.txt)
do
        print "Current Space Shuttle : $shuttle"
done

#!/bin/ksh
for shuttle in $(cat spaceshuttles.txt)
do
print "Current Space Shuttle : $shuttle"
done

You can also print file names in /tmp directory:

#!/bin/ksh
for f in $(ls /tmp/*)
do
        print "Full file path  in /tmp dir : $f"
done

#!/bin/ksh
for f in $(ls /tmp/*)
do
print "Full file path in /tmp dir : $f"
done

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.