Bash Loop Through Sequence with a Gap or Skipping Numbers

Let’s say you want iterate over a series of sequential numbers with Bash. If so, then you could do the following:

 $ for i in {1..10}; do echo $i; done
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10 

Now, let’s say you want to loop over a sequence of numbers, but you want to skip over by 10 each time:

 $ for i in `seq 0 10 100`; do echo $i; done
 0
 10
 20
 30
 40
 50
 60
 70
 80
 90
 100 

Supposedly, this syntax should work, but it is not on a Mac at least: for i in {0..100..10}; do echo $i; done (see source). It does work on an Amazon Linux instance though:

 $ for i in {0..100..10}; do echo $i; done
 0
 10
 20
 30
 40
 50
 60
 70
 80
 90
 100
 $ cat /etc/os-release
 NAME="Amazon Linux AMI"
 VERSION="2018.03"
 ID="amzn"
 ID_LIKE="rhel fedora"
 VERSION_ID="2018.03"
 PRETTY_NAME="Amazon Linux AMI 2018.03"
 ANSI_COLOR="0;33"
 CPE_NAME="cpe:/o:amazon:linux:2018.03:ga"
 HOME_URL="http://aws.amazon.com/amazon-linux-ami/" 

Now, let’s say you want to skip over gaps that are not as well distributed or evenly spaced. This is probably not the most elegant solution; however, it works:

 $ for i in `seq 3 5` `seq 7 10`; do echo $i; done
 3
 4
 5
 7
 8
 9
 10 

Leave a Reply

Your email address will not be published. Required fields are marked *