[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: bash expansion crap...



On Tue, Oct 02, 2007 at 12:48:04PM -0700, Mike Bird wrote:
> On Tuesday 02 October 2007 11:49, Andrew Sackville-West wrote:
> > Hey folks, help me out with this...please
> >
> > andrew@basement:~$ for i in {1..3}; do echo $i; done
> > 1
> > 2
> > 3
> > andrew@basement:~$ TEST=3; for i in {1..$TEST}; do echo $i; done
> > {1..3}
> >
> >
> > in the first example, its obvious. In the second, $TEST gets replaced
> > with 3, but then the {} doesn't get expanded. I'm sure I have to do
> > some kind of wacky $({[ type thing, but I'm not able to grok it. any
> > ideas?
> >
> > the purpose is to be able to easily update some loops in a script for
> > different numbers of object to iterate over. obvious, I guess.
> 
> From man bash:
> 
>        Brace expansion is performed before any other expansions, and any char???
>        acters  special to other expansions are preserved in the result.  It is
>        strictly textual.  Bash does not apply any syntactic interpretation  to
>        the context of the expansion or the text between the braces.
> 
> This is not pretty but it works:
> 
>        TEST=3; for i in $(eval echo {1..$TEST}); do echo $i; done

Andrew,

This I why I use phthon for such scripts.  Its much prettier.

[UNTESTED, but enough to point you in the right direction]
I added a sample sanity check.


#! /usr/bin/python

import os

try:
	TEST_env = os.environ['TEST']
except KeyError:
	print "TEST environment variable not set"
	os.exit()

try:
	TEST = int(TEST_env)
except ValueError:
	print "TEST environment variable not an integer"
	os.exit()

# do whatever other sanity checks you want.

### without sanity checkes, this would be:
# TEST = int(os.environ['TEST'])

for i in range(1, (TEST + 1)):
	print i

#######

### Without sanity checks and a one-liner:

for i in range(1, (int(os.environ['TEST']) +1)): print i

####

Doug.



Reply to: