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

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

    Here is why the original expression didn't work.

    From man bash:

    Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

    So, brace expansion is something done early as a purely textual macro operation, before parameter expansion.

    Shells are highly optimized hybrids between macro processors and more formal programming languages. In order to optimize the typical use cases, the language is made rather more complex and some limitations are accepted.

    Recommendation

    I would suggest sticking with Posix1 features. This means using for i in ; do, if the list is already known, otherwise, use while or seq, as in:

    #!/bin/sh
    
    limit=4
    
    i=1; while [ $i -le $limit ]; do
      echo $i
      i=$(($i + 1))
    done
    # Or -----------------------
    for i in $(seq 1 $limit); do
      echo $i
    done
    


    1. Bash is a great shell and I use it interactively, but I don't put bash-isms into my scripts. Scripts might need a faster shell, a more secure one, a more embedded-style one. They might need to run on whatever is installed as /bin/sh, and then there are all the usual pro-standards arguments. Remember shellshock, aka bashdoor?

提交回复
热议问题