KSH For Loop Examples

last updated in Categories , , , , , , , , , , , ,

How do I use for loop in Korn Shell (KSH) under UNIX / Linux / *BSD / macOS/OS X operating systems?

We use ksh for loop when we need to execute commands until some specified condition occurs repeatedly. The main advantage of ksh over the traditional Unix shell is in its use as a programming language. The for loop allows us to specify a list of values and commands are executed for each value in the list. Let us see how to use for ksh for loops.

ADVERTISEMENTS


KSH Scripting – for loop syntax

The syntax is as follows:

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

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

OR
$ ksh script.ksh
Where,

  • i is variable name
  • 1 2 3 4 5 is argument list. It can be any list of words, strings, or numbers. We can also use a shell command or shell metacharacter.
  • echo "Welcome $i times" is statement/command to execute five times as per argument list. In this case run echo command 5 times.

ksh for loop examples

You can easily set ranges (1 to 10) as follows:

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

If above failed to work try the seq command as command substitution in a Korn shell:

#!/usr/bin/ksh
for var in $(seq 1 10)
do
     echo "$var"
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

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

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

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

Using command line arguments with ksh loops

In this example, the data entered on the command line becomes the argument list of the for loop:

#!/bin/ksh
for arg in $*
do
	echo "Command line arg: $arg"
done

Run it as follows:
$ ./script This is a test
Linux and Unix KSH for loop examples demo

Conclusion

In this quick tutorial, you learned how to write a script with a for loop construct when using ksh. See ksh man page for more information by typing the following man command:
$ man ksh
This repo contains the ksh93u+ and ksh93v- versions of KSH.

Posted by: Vivek Gite

The author is the creator of nixCraft 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.


ADVERTISEMENTS

21 comment

  1. I don’t understand why you say that does not work :

    #!/bin/ksh
    # Nettoyage du contenu du fichier et suppression des derniers PDFs cree
    >listePdfs.txt
    cd /opt/filenet/temp_batch/800000PDFs
    rm -rf *.pdf
    
    for i in {1..1000}
    do
      echo "$i"
      cp 0.src $i.pdf
      echo "$i      $i.pdf" >> listePdfs.txt
    done
    

    This programme work

  2. Hi Tried this using ksh, [Unix : SunOS 5.10 ]
    and the output of {1..10}is
    ksh Output : Welcome {1..10} times
    , however when I change ksh to bash it
    executes as expected.

  3. The reason is that KSH does not really exist in Linux. If you look, then ksh is a symlink to bash. In Linux if you want to use really ksh, you have to download pdksh = Public Domain KSH.

    In Solaris however it is a different story. There ksh is one shell and bash another one.

  4. Hi,

    Yep, in AIX ksh the operator {1..10} doesn´t work, as well as ksh –version.
    They only work in Linux, because it’s really the bash shell.

  5. For iterating sequence of numbers you can use ‘while’ like posted in this thread:
    ex:

    i=5 ; while [[ $i -lt 23 ]] ; do echo $i ; ((i += 1)) ; done
    
  6. i am learning TCSH shell Loops and i needs a examples of foreach loops so kindly any one give me some examples of foreach loops .

  7. Hi Vivek,

    Your for each example:

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

    misses ; after for i in {1..10}

  8. What if you have 5 or 6 files, specific files .biz in a directory and you want to store them one at the time in a variable $mirage, and want to process $mirage until no more .biz file are found.
    How will you modify the script accordingly

Leave a Comment