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

后端 未结 20 1949
予麋鹿
予麋鹿 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 06:03

    There are many ways to do this, however the ones I prefer is given below

    Using seq

    Synopsis from man seq

    $ seq [-w] [-f format] [-s string] [-t string] [first [incr]] last
    

    Syntax

    Full command
    seq first incr last

    • first is starting number in the sequence [is optional, by default:1]
    • incr is increment [is optional, by default:1]
    • last is the last number in the sequence

    Example:

    $ seq 1 2 10
    1 3 5 7 9
    

    Only with first and last:

    $ seq 1 5
    1 2 3 4 5
    

    Only with last:

    $ seq 5
    1 2 3 4 5
    

    Using {first..last..incr}

    Here first and last are mandatory and incr is optional

    Using just first and last

    $ echo {1..5}
    1 2 3 4 5
    

    Using incr

    $ echo {1..10..2}
    1 3 5 7 9
    

    You can use this even for characters like below

    $ echo {a..z}
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    

提交回复
热议问题