Shell script “for” loop syntax

前端 未结 11 803
攒了一身酷
攒了一身酷 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 07:39

    These all do {1..8} and should all be POSIX. They also will not break if you put a conditional continue in the loop. The canonical way:

    f=
    while [ $((f+=1)) -le 8 ]
    do
      echo $f
    done
    

    Another way:

    g=
    while
      g=${g}1
      [ ${#g} -le 8 ]
    do
      echo ${#g}
    done
    

    and another:

    set --
    while
      set $* .
      [ ${#} -le 8 ]
    do
      echo ${#}
    done
    
    0 讨论(0)
  • 2020-12-07 07:46

    If the seq command available on your system:

    for i in `seq 2 $max`
    do
      echo "output: $i"
    done
    

    If not, then use poor man's seq with perl:

    seq=`perl -e "\$,=' ';print 2..$max"`
    for i in $seq
    do
      echo "output: $i"
    done
    

    Watch those quote marks.

    0 讨论(0)
  • 2020-12-07 07:47

    Use:

    max=10
    for i in `eval echo {2..$max}`
    do
        echo $i
    done
    

    You need the explicit 'eval' call to reevaluate the {} after variable substitution.

    0 讨论(0)
  • 2020-12-07 07:51

    There's more than one way to do it.

    max=10
    for i in `eval "echo {2..$max}"`
    do
        echo "$i"
    done
    
    0 讨论(0)
  • 2020-12-07 07:52

    Step the loop manually:

    i=0
    max=10
    while [ $i -lt $max ]
    do
        echo "output: $i"
        true $(( i++ ))
    done
    

    If you don’t have to be totally POSIX, you can use the arithmetic for loop:

    max=10
    for (( i=0; i < max; i++ )); do echo "output: $i"; done
    

    Or use jot(1) on BSD systems:

    for i in $( jot 0 10 ); do echo "output: $i"; done
    
    0 讨论(0)
  • 2020-12-07 07:53

    Here it worked on Mac OS X.

    It includes the example of a BSD date, how to increment and decrement the date also:

    for ((i=28; i>=6 ; i--));
    do
        dat=`date -v-${i}d -j "+%Y%m%d"` 
        echo $dat
    done
    
    0 讨论(0)
提交回复
热议问题