Shell script “for” loop syntax

前端 未结 11 924
攒了一身酷
攒了一身酷 2020-12-07 07:11

I have gotten the following to work:

for i in {2..10}
do
    echo \"output: $i\"
done

It produces a bunch of lines of output: 2

相关标签:
11条回答
  • 2020-12-07 08:01

    This is a way:
    Bash:

    max=10
    for i in $(bash -c "echo {2..${max}}"); do echo $i; done
    

    The above Bash way will work for ksh and zsh too, when bash -c is replaced with ksh -c or zsh -c respectively.

    Note: for i in {2..${max}}; do echo $i; done works in zsh and ksh.

    0 讨论(0)
  • 2020-12-07 08:01

    We can iterate loop like as C programming.

    #!/bin/bash
    for ((i=1; i<=20; i=i+1))
    do 
          echo $i
    done
    
    0 讨论(0)
  • 2020-12-07 08:04

    Well, as I didn't have the seq command installed on my system (Mac OS X v10.6.1 (Snow Leopard)), I ended up using a while loop instead:

    max=5
    i=1
    
    while [ $max -gt $i ]
    do
        (stuff)
    done
    

    *Shrugs* Whatever works.

    0 讨论(0)
  • 2020-12-07 08:05

    Brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.

    Instead, use the seq 2 $max method as user mob stated.

    So, for your example it would be:

    max=10
    for i in `seq 2 $max`
    do
        echo "$i"
    done
    
    0 讨论(0)
  • 2020-12-07 08:06

    Try the arithmetic-expression version of for:

    max=10
    for (( i=2; i <= $max; ++i ))
    do
        echo "$i"
    done
    

    This is available in most versions of bash, and should be Bourne shell (sh) compatible also.

    0 讨论(0)
提交回复
热议问题