Bourne Shell For i in (seq)

后端 未结 6 852
陌清茗
陌清茗 2020-12-29 10:37

I want to write a loop in Bourne shell which iterates a specific set of numbers. Normally I would use seq:

for i in `seq 1 10 15 20`
   #do stuf         


        
相关标签:
6条回答
  • 2020-12-29 11:08

    try

    for i in 1 10 15 20
    do
       echo "do something with $i"
    done
    

    else if you have recent Solaris, there is bash 3 at least. for example this give range from 1 to 10 and 15 to 20

    for i in {1..10} {15..20}
    do
      echo "$i"
    done
    

    OR use tool like nawk

    for i in `nawk 'BEGIN{ for(i=1;i<=10;i++) print i}'`
    do
      echo $i
    done
    

    OR even the while loop

    while [ "$s" -lt 10 ]; do s=`echo $s+1|bc`; echo $s; done
    
    0 讨论(0)
  • 2020-12-29 11:08

    Another variation using bc:

    for i in $(echo "for (i=0;i<=3;i++) i"|bc); do echo "$i"; done
    

    For the Bourne shell, you'll probably have to use backticks, but avoid them if you can:

    for i in `echo "for (i=0;i<=3;i++) i"|bc`; do echo "$i"; done
    
    0 讨论(0)
  • 2020-12-29 11:11

    I find that this works, albeit ugly as sin:

    for i in `echo X \n Y \n Z ` ...
    
    0 讨论(0)
  • 2020-12-29 11:11
    for i in `seq 1 5 20`; do echo $i; done
    

    Result:

    5
    10
    15
    20
    

    $ man seq

    SEQ(1)                           User Commands                          SEQ(1)
    
    NAME
           seq - print a sequence of numbers
    
    SYNOPSIS
           seq [OPTION]... LAST
           seq [OPTION]... FIRST LAST
           seq [OPTION]... FIRST INCREMENT LAST
    
    0 讨论(0)
  • 2020-12-29 11:26

    You can emulate seq with dc:

    For instance:

    seq 0 5 120
    

    is rewritten as:

    dc -e '0 5 120  1+stsisb[pli+dlt>a]salblax'
    
    0 讨论(0)
  • 2020-12-29 11:29
    #!/bin/sh
    for i in $(seq 1 10); do
            echo $i
    done
    
    0 讨论(0)
提交回复
热议问题