Sometimes we have to administrate this operating systems such as FreeBSD / AIX / HP UX or even Mac OS server where by default due to historical reasons or for security bash shell is not avialable. That's not a common scenario but it happens so if as sysadmin we need to create for loops on ksh it is useful to know how to do that, as for loop cycles are one of the most important command line tools the sysadmin swiss army knife kind of.
So how to create a for loop (cycle) in ksh (Korn Shell)?
The most basic example for a KSH loop shell is below:
#!/bin/ksh
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
Add the content to any file lets say ksh_loop.ksh then make it executable as you do in bash shells
$ chmod +x ksh_loop.ksh
$ ksh ksh_loop.ksh
The overall syntax of the for loop ksh command is as follows:
for {Variable} in {lists}
do
echo ${Variable}
done
Hence to list lets say 20 iterations in a loop in ksh you can use something like:
#!/bin/ksh
for i in {1..20}
do
echo "Just a simple echo Command $i times";
# add whatever system commands you like here
done
Example for some useful example with KSH loop is to list a directory content so you can execute whatever command you need on each of the files or directories inside
#!/bin/ksh
for f in $(ls /tmp/*)
do
print "Iterating whatever command you like on /tmp dir : $f"
done
Other useful for loop iteration would be to print a file content line by line just like it is done in bash shell, you can do that with a small loop like belows:
#!/bin/ksh
for iteration_variable in $(cat file_with-your-loved-content-to-iterate.txt)
do
print "Current iteration like is : $iteration_variable"
done
More helpful Articles
Tags: freebsd, loop, make, system, unix, Useful