jsg25
jsg25

Reputation: 33

for loop range not working ksh

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.

Upvotes: 3

Views: 17793

Answers (4)

Trevor North
Trevor North

Reputation: 2296

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

Upvotes: 0

gruntled
gruntled

Reputation: 2694

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"
}

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881323

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.

Upvotes: 4

Decado
Decado

Reputation: 356

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

Upvotes: 0

Related Questions