Iterating through a range of ints in ksh?

纵饮孤独 提交于 2019-12-18 12:49:12

问题


How can I iterate through a simple range of ints using a for loop in ksh?

For example, my script currently does this...

for i in 1 2 3 4 5 6 7
do
   #stuff
done

...but I'd like to extend the range way above 7. Is there a better syntax?


回答1:


Curly brackets?

for i in {1..7}
do
   #stuff
done



回答2:


While loop?

while [[ $i -lt 1000 ]] ; do
    # stuff
   (( i += 1 ))
done



回答3:


ksh93, Bash and zsh all understand C-like for loop syntax:

for ((i=1; i<=9; i++))
do
    echo $i
done

Unfortunately, while ksh and zsh understand the curly brace range syntax with constants and variables, Bash only handles constants (including Bash 4).




回答4:


on OpenBSD, use jot:

for i in `jot 10`; do echo $i ; done;



回答5:


The following will work on AIX / Linux / Solaris ksh.

#!/bin/ksh

d=100

while (( $d < 200 ))
do
   echo "hdisk$d"
  (( d=$d+1 ))
done

Optionally if you wanted to pad to 5 places, i.e. 00100 .. 00199 you could begin with:

#!/bin/ksh
typeset -Z5 d

-Scott




回答6:


seq - but only available on linux.

for i in `seq 1 10`
do 
    echo $i
done

there are other options for seq. But the other solutions are very nice and more important, portable. Thx




回答7:


Just a few examples I use in AIX because there is no range operator or seq, abusing perl instead.

Here's a for loop, using perl like seq:

for X in `perl -e 'print join(" ", 1..10)'` ; do something $X ; done

This is similar, but I prefer while read loops over for. No backticks or issues with spaces.

perl -le 'print "$_ " for 1..10;' | while read X ; do xargs -tn1 ls $X ; done

My fav, do bash-like shell globbing, in this case permutations with perl.

perl -le 'print for glob "e{n,nt,t}{0,1,2,3,4,5}"' | xargs -n1 rmdev -dl


来源:https://stackoverflow.com/questions/1591109/iterating-through-a-range-of-ints-in-ksh

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