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 

9 Comments:

  1. I truly enjoy examining on this website , it has wonderful articles.

  2. Very interesting info !Perfect just what I was looking for!

  3. You really make it seem so easy with your presentation but I find this topic to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  4. An attention-grabbing dialogue is value comment. I think that it is best to write extra on this subject, it might not be a taboo subject however generally individuals are not enough to speak on such topics. To the next. Cheers

Leave a Reply

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