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

后端 未结 20 1894
予麋鹿
予麋鹿 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:54

    The POSIX way

    If you care about portability, use the example from the POSIX standard:

    i=2
    end=5
    while [ $i -le $end ]; do
        echo $i
        i=$(($i+1))
    done
    

    Output:

    2
    3
    4
    5
    

    Things which are not POSIX:

    • (( )) without dollar, although it is a common extension as mentioned by POSIX itself.
    • [[. [ is enough here. See also: What is the difference between single and double square brackets in Bash?
    • for ((;;))
    • seq (GNU Coreutils)
    • {start..end}, and that cannot work with variables as mentioned by the Bash manual.
    • let i=i+1: POSIX 7 2. Shell Command Language does not contain the word let, and it fails on bash --posix 4.3.42
    • the dollar at i=$i+1 might be required, but I'm not sure. POSIX 7 2.6.4 Arithmetic Expansion says:

      If the shell variable x contains a value that forms a valid integer constant, optionally including a leading plus or minus sign, then the arithmetic expansions "$((x))" and "$(($x))" shall return the same value.

      but reading it literally that does not imply that $((x+1)) expands since x+1 is not a variable.

提交回复
热议问题