3

I tried this,

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

in Ksh of an AIX box. I am getting the output as,

Welcome {1..10} times

What's wrong here? Isn't it supposed to print from 1 to 10?. Edit: According to perkolator's post, from Iterating through a range of ints in ksh?

It works only on linux. Is there any other work around/replacements for unix box ksh?

for i in 1 2 3 4 5 6 7 8 9 10

is ugly.

Thanks.

Community
  • 1
  • 1
jsg25
  • 33
  • 1
  • 1
  • 4

4 Answers4

4

I think from memory that the standard ksh on AIX is an older variant. It may not support the ranged for loop. Try to run it with ksh93 instead of ksh. This should be in the same place as ksh, probably /usr/bin.

Otherwise, just use something old-school like:

i=1
while [[ $i -le 10 ]] ; do
    echo "Welcome $i times"
    i=$(expr $i + 1)
done

Actually, looking through publib seems to confirm this (the ksh93 snippet) so I'd try to go down that route.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Unfortunately, Ksh93 doesn't seem to work for me here. But it is indeed there on /usr/bin. – jsg25 Jun 09 '10 at 11:43
  • 1
    Since older versions of shells don't have the range feature, `seq` is often used: `for i in $(seq 10)` or `for i in \`seq 10\`` (or on BSD systems, you can use `jot`). @paxdiablo: if a shell has `[[]]` it most likely has `$(())` and you don't need to use `expr`. – Dennis Williamson Jun 09 '10 at 22:40
  • Upvoted for the while-loop which solved my issue (albeit less elegantly than I would like). The ksh93 idea doesn't work on my AIX machine. – Katerberg Jan 20 '11 at 20:03
0

The reason being that pre-93 ksh doesn't actually support range.

When you run it on Linux you'll tend to find that ksh is actually a link to bash or ksh93.

Try looping like :-

for ((i=0;i<10;i++))
do
 echo "Welcome $i time"
done
Decado
  • 356
  • 2
  • 15
  • ksh93, Bash and zsh all understand C-like for loop syntax. Refer: http://stackoverflow.com/questions/1591109/how-can-i-iterate-through-a-range-of-ints-in-ksh – askmish Aug 10 '12 at 10:26
0

It seems that the version of ksh you have does not have the range operator. I've seen this on several systems.

you can get around this with a while loop:

while [[ $i -lt 10 ]] ; do
    echo "Welcome $i times"
   (( i += 1 ))
done

On my systems i typically use perl so the script would look like

#!/usr/bin/perl
for $i (1 .. 10) {
    echo "Welcome $i times"
}
gruntled
  • 2,684
  • 19
  • 16
0

You can check and see if jot works see man page here or if not, write your own little C program to do the same and call that.

The syntax for jot is something like

for i in `jot 1 10`
do 
    //do stuff here
done
Trevor North
  • 2,286
  • 1
  • 16
  • 19