[prog] getting parameters into scripts
Chris Wilson
chris+linuxchix at aptivate.org
Mon Mar 29 08:53:15 UTC 2010
Hi Miriam,
On Mon, 29 Mar 2010, Miriam English wrote:
> I normally use positional parameters in scripts, collecting them as $1,
> $2, $3, and so on. This is fine, but I recently wrote a script where it
> would have been really nice to be able to give the parameters in a
> different order under certain circumstances.
[...]
> testparams c=turkey a="elephant trunk" b="blob" d='pine cone'
What about using options with getopt, e.g.
testparams --c=turkey --a="elephant trunk"
That would be much, much more standard.
> then all variables are stored, but $a contains just "elephant" and $d
> contains just "pine". Weirdly, $2 is "a=elephant trunk" and $4 is
> "d=pine cone", just as you'd expect.
Probably because of the eval.
> Looking at $@ displays the problem. The quotes have been lost:
> c=turkey a=elephant trunk b=blob d=pine cone
They are used by the shell to work out the arguments to your script,
and then removed. I.e. they have a special meaning to the shell, just like
backticks and $.
> so it looks like we have 6 items, even though $# knows there are only 4.
Only if you try to break them at spaces. You still have $1 == "elephant
trunk". But if you expand $@, it just concatenates them all together,
separated by spaces, and of course there are no quotes then.
How about:
eval `echo $i | sed -e 's/=/="/' -e 's/$/"/'`
which turns:
a=elephant trunk
into:
a="elephant trunk"
and then evaluates that?
> Anybody know how to get parameters with spaces into those variables?
> Or should I just give up on trying to be a mental contortionist? :)
Try getopt.
Cheers, Chris.
--
Aptivate | http://www.aptivate.org | Phone: +44 1223 760887
The Humanitarian Centre, Fenner's, Gresham Road, Cambridge CB1 2ES
Aptivate is a not-for-profit company registered in England and Wales
with company number 04980791.
More information about the Programming
mailing list