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

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

    These are all nice but seq is supposedly deprecated and most only work with numeric ranges.

    If you enclose your for loop in double quotes, the start and end variables will be dereferenced when you echo the string, and you can ship the string right back to BASH for execution. $i needs to be escaped with \'s so it is NOT evaluated before being sent to the subshell.

    RANGE_START=a
    RANGE_END=z
    echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash
    

    This output can also be assigned to a variable:

    VAR=`echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash`
    

    The only "overhead" this should generate should be the second instance of bash so it should be suitable for intensive operations.

提交回复
热议问题