How do I iterate over a range of numbers defined by variables in Bash?

后端 未结 20 1990
予麋鹿
予麋鹿 2020-11-21 05:19

How do I iterate over a range of numbers in Bash when the range is given by a variable?

I know I can do this (called \"sequence expression\" in the Bash documentatio

20条回答
  •  面向向阳花
    2020-11-21 05:49

    This works in Bash and Korn, also can go from higher to lower numbers. Probably not fastest or prettiest but works well enough. Handles negatives too.

    function num_range {
       # Return a range of whole numbers from beginning value to ending value.
       # >>> num_range start end
       # start: Whole number to start with.
       # end: Whole number to end with.
       typeset s e v
       s=${1}
       e=${2}
       if (( ${e} >= ${s} )); then
          v=${s}
          while (( ${v} <= ${e} )); do
             echo ${v}
             ((v=v+1))
          done
       elif (( ${e} < ${s} )); then
          v=${s}
          while (( ${v} >= ${e} )); do
             echo ${v}
             ((v=v-1))
          done
       fi
    }
    
    function test_num_range {
       num_range 1 3 | egrep "1|2|3" | assert_lc 3
       num_range 1 3 | head -1 | assert_eq 1
       num_range -1 1 | head -1 | assert_eq "-1"
       num_range 3 1 | egrep "1|2|3" | assert_lc 3
       num_range 3 1 | head -1 | assert_eq 3
       num_range 1 -1 | tail -1 | assert_eq "-1"
    }
    

提交回复
热议问题