KSH For Loop Examples

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.

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
21 comments… add one
  • Kai Mar 13, 2009 @ 10:32

    for i in {1..10}

    does not work in KSH.

    You must have tried this with BASH or compagnion.

  • Wilfrid May 14, 2009 @ 9:23

    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

  • H Mark Jul 7, 2009 @ 17:14

    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.

  • 🐧 nixCraft Jul 7, 2009 @ 17:16

    I’ve tested this on KSH-93. Can you find out your ksh version?

    ksh --version
  • Peter Charpentier Jul 21, 2009 @ 7:27

    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.

  • ruchi Aug 31, 2009 @ 10:50

    Hey,
    It doesn’t work on tcsh shell. whats the way to iterate for loop for 1 to 100.
    Thanks
    Ruchi

  • tom Aug 31, 2009 @ 11:42

    same problem, try
    for ((i=0;i<100;i++))
    do
    echo $i
    done

  • 🐧 nixCraft Aug 31, 2009 @ 11:55

    Try

    #!/bin/csh
    foreach i ( 1 2 3 )
    	echo "welcome $i times"
    end
  • Billy Baroo Oct 14, 2009 @ 19:37

    #!/usr/bin/ksh
    n=1
    while [[ $n -le 100 ]]; do
    echo $n
    ((n+=1))
    done

  • Carlos Ijalba Jan 20, 2010 @ 17:59

    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.

  • RaMa Mar 29, 2010 @ 11:19

    can any one say -In which shell ,script can be written in Aix?.

  • Cyro Aug 7, 2010 @ 23:55

    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
    
    • Coco123 May 30, 2013 @ 8:29

      Thanks a lot for this answer, work perfectly on AIX !

  • navneet Jun 16, 2011 @ 14:55

    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 .

  • Dima Mar 5, 2012 @ 16:29

    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}

  • Amin Apr 12, 2012 @ 4:23

    Hi,
    This is so cool:

    end=20
    step=3
    i=0
    while [ $((i+=$step)) -le $end ]; do
    	echo $i
    done

    output:
    3
    6
    9
    12
    15
    18

  • Max May 28, 2016 @ 7:25

    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

  • sadane Jun 8, 2016 @ 13:42

    #!/bin/ksh
    for i in {1..10} …………
    doesnt work with ksh. but still working with bash, Thanks.

    • Jimmy Mejia Oct 28, 2016 @ 22:21

      With KSH

      for i in $(seq 1 10); do echo $i ; done

  • Koumaomao Aug 3, 2016 @ 1:26

    for i in ‘ls’ I could not get single one file or directory when using $i, instead of
    1.txt
    2.txt

  • Marcel Aug 4, 2020 @ 5:24

    It works with #!/bin/ksh93

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.