toto:~$ for word in un "deux trois"; do echo $word; done
un
deux trois
toto:~$ sentence='un "deux trois"'
toto:~$ for word in $sentence; do echo $word; done
un
"deux
trois"
toto:~$ sentence="un 'deux trois'"
toto:~$ for word in $sentence; do echo $word; done
un
'deux
trois'
Why is the word with a space split in two parts even though it is surrounded by quotes in the variable $sentence?
Is there any way to get the same behavior with a variable and with an explicit string?
... and if you quote $sentence, there's no point in using a loop, since without field splitting there will always be just one word after the parameter expansion
Quote characters stored in a variable are not special in any way. The variable's expansion occurs after the shell has identified quoted strings.
Yes radoulov, you're right.
Your idea is indeed interesting but I don't think I can easily change my script commands from variable to array.
Your sed example doesn't work with a variable either but I just learned a powerfull command (set).
Thanks for your help anyway.
I don't know if you're still following this thread but I found a way to efficiently use both your ideas.
Because the sentence was read as a string (not an array), I had no other way than using alister's idea:
But I also had a lot of statements to put in my for loop. So it would have become a little messy:
$ eval "for word in $sentence; do action1 \$word; action2 \$word; action3 \$word; action4 \$word...; done"
At that point, radoulov's idea was interesting because it left the for loop open to any statement:
So I combined the two ideas and came up with this:
# That's how I read the sentence anyway:
sentence='un "deux trois" quatre'
# Then I turn it into an array:
eval "sentence=($sentence)"
# Et voila!
for word in "${sentence[@]}"; do
action1 "$word"
action2 "$word"
action3 "$word"
action4 "$word"
...
done