for loop range not working ksh

我是研究僧i 提交于 2019-12-07 16:47:49

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/3005265/for-loop-range-not-working-ksh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!