Python’s range() for Bash

I doubt I’m the only one who often ends up typing: for i in 1 2 3 4 … a lot. I got sick and tired of it. Sometimes for the longer ones I’d start python, and use it to generate the sequence for me. It was absurd, so I fixed it.

Just set up the following Python script in /usr/local/bin/range and you’ll be good to go:

#!/usr/bin/env python

import sys

out = " "
if len(sys.argv) < 2 or len(sys.argv) > 4:
print "Usage: range [begin] end [[inc]]"
elif len(sys.argv) == 2:
for i in range(int(sys.argv[1])):
out += repr(i) + " "
elif len(sys.argv) == 3:
for i in range(int(sys.argv[1]), int(sys.argv[2])):
out += repr(i) + " "
for i in range(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])):
out += repr(i) + " "
print out

(Ugh. WordPress is destroying indents….)

Now you can just do for i in `range 100`; … Yipee!

And yes, this is trivial. I don’t know why it took me so long to decide to do this.

Tags: ,

3 Responses to “Python’s range() for Bash”

  1. - Says:

    and seq command? just run “seq 1 10” and you will see 1 2 … 10

  2. Raph Says:

    and bash builtins: {x..y}
    for i in {1..5}; do echo $i; done

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: