[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Question about variables and for loop
From: |
Alexander Elgert |
Subject: |
Re: Question about variables and for loop |
Date: |
Sun, 19 Mar 2006 20:08:32 +0100 |
User-agent: |
Mutt/1.4.1i |
Paul Jarc schrieb am 18.03.2006 um 20:44:17 (-0500):
> Bob <bob@dont.spam.me> wrote:
> > XXX='a "b c" d'
> > for x in $XXX ; do
> > echo $x
> > done
>
> XXX='a "b c" d'
> eval "set $XXX"
> for x in "$@" ; do
> echo $x
> done
>
> If the first element in XXX might start with "-", then it takes a
> little more work to ensure it isn't misinterpreted as an option to
> "set":
> eval "set x $XXX"
> shift
>
I would use arrays to complete this task, because it is quite hard to
escape a string for the eval-set construct. There is no need to, look at
this (simple?) solution:
x=("-" 0tt a x) # creating array
for t in "${x[@]}"; do echo "$t"; done
# ^ iterating over all array elements
Because this command does not use eval it is faster and safer;
f.e. you can't add commands in the XXX string, like this:
XXX='a b ; ls -la' # ls -la is executed by eval.
To get rid of you "first element is '-' problem" you can switch off
the option parsing with a single dash or a double dash:
set -- -xxx
set - -xxx
In both cases "$1" would be "-xxx".
Alexander