1

I want to run a bash numeric 'for' loop but I want to skip some numbers in between.

Example:

for num in {1..4, 7..11, 23..34}; do (echo num $num); done

or

for num in {17..24, 41..48}; do (echo num $num); done
  1. Is this possible?
  2. How?
1
4
for num in {17..24} {41..48}; do (echo num $num); done

, and see the documentation for Brace Expansion in bash.

8
  • Aha! Syntax! makes sense. Thank you. – skeetastax Jun 3 '19 at 11:13
  • For anyone looking for the same answer, I found that: for num in {17..24}{41..48}; do (echo num $num); done is treated as a two-dimensional array, whereas: for num in {17..24} {41..48}; do (echo num $num); done is treated as two 'slices' from a one dimensional array. – skeetastax Jun 3 '19 at 12:57
  • @skeetastax Removing the space between the brace expansions would not involve a two-dimensional array in any way, but it would produce a list of numbers that are the combinations (concatenation) of each number in the first expansion with every number in the second expansion. This is how brace expansions work. – Kusalananda Jun 3 '19 at 13:01
  • You are right - I used the wrong term. It is a nested loop concatenating each iterative value. – skeetastax Jun 3 '19 at 13:12
  • 1
    @skeetastax: It's not a "nested loop" because it's actually not a loop at all. Try echo {17..24}{41..48} and you'll get the same thing with no for loop. It's "just" a brace expansion. – Kevin Jun 3 '19 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.