0

I'm looking for a way to pass an arbitrary sequence of numbers to a bash script. I know about seq. However, the key word here is arbitrary. For example:

$ ./do_foo 2,4,5

Should perform something like this:

#!/bin/bash
for i in {2,4,5}; do
    foo $i
done

And, of course:

$ ./do_foo 2..5

Should also be possible and perform something like this:

#!/bin/bash
for i in {2..5}; do
    foo $i
done
  • 1
    Why don't you pipe the sequence (generated by seq or whatever other program) in to the script (seq 2 5 | your_script` ? – Anthon May 7 '15 at 18:15
  • @Anthon That's more or less what I do today (run the loop outside the script), but wanted to see if something a bit more elegant and less verbose was possible. – sudarkoff May 7 '15 at 18:35
1

Just pass them as parameters:

#! /bin/sh
for i in "$@"; do
    foo "$i"
done

Then:

./do_foo 2 4 5
  • This covers only part of the problem. You can't do 2..5 this way. – sudarkoff May 7 '15 at 18:27
  • Sure you can: ./do_foo {2..5}. – lcd047 May 7 '15 at 18:30
  • Oh, I haven't tried it that way! Doh! – sudarkoff May 7 '15 at 18:31
  • @kos My actual script is a lot more complicated, of course, so I have a few shifts while loading other parameters and then treat the remainder $@ as the sequence. – sudarkoff May 7 '15 at 18:37
  • @kos Yes, I kinda agree with you. But you can do do_foo {2,4,5} as well, which I prefer because it makes usage more consistent. – sudarkoff May 7 '15 at 18:48

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.