[prog] getting parameters into scripts
Miriam English
mim at miriam-english.org
Mon Mar 29 02:07:01 UTC 2010
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. I filed that away in my
head until this morning I hit on the idea of doing something like this:
for i in $@; do
eval "$i"
done
If I give all parameters in the form a=blah or x=nerf then this little
loop stores the value into a variable called $a or $x in the script.
This works wonderfully regardless of how many parameters it is fed,
automatically adapting to how many are given.
My problem is that it trips up if I feed it a parameter with a space in
it. For example if my script is called testparams and I invoke it this way:
testparams c=turkey a="elephant trunk" b="blob" d='pine cone'
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.
Add this after the above little loop and you'll see what I mean:
echo "named:"
echo $a
echo $b
echo $c
echo $d
echo "positional:"
echo $1
echo $2
echo $3
echo $4
Looking at $@ displays the problem. The quotes have been lost:
c=turkey a=elephant trunk b=blob d=pine cone
so it looks like we have 6 items, even though $# knows there are only 4.
So I tried a different tack:
for i in $(seq $#); do
and noticed that putting
echo $`echo $i`
inside the loop printed out "$1", "$2", and so on, so I tried (hold onto
your hat) evaluating that with:
eval `eval "echo $\`echo $i\`"`
but was back to the same old problem again. [sigh]
Anybody know how to get parameters with spaces into those variables?
Or should I just give up on trying to be a mental contortionist? :)
--
If you don't have any failures then you're not trying hard enough.
- Dr. Charles Elachi, director of NASA's Jet Propulsion Laboratory
-----
Website: http://miriam-english.org
Blog: http://miriam_e.livejournal.com
More information about the Programming
mailing list