Posts Tagged ‘Bash’

Python’s range() for Bash

March 9, 2010

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) + " "
else:
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.