Reputation: 47
I recently switched from bash to zsh and not sure how to achieve this:
bash:
$ list='aaa
> bbb
> ccc
> ddd'
$ for i in $list; do echo $i-xxx; done
aaa-xxx
bbb-xxx
ccc-xxx
ddd-xxx
in zsh I get:
% list='aaa
quote> bbb
quote> ccc
quote> ddd'
% for i in $list; do echo $i-xxx; done
aaa
bbb
ccc
ddd-xxx
how to force zsh to do this in the same way as bash?
Upvotes: 4
Views: 3826
Reputation: 22217
You have to split your string list
on white space:
for i in ${(z)list}
do
echo $i
done
Of course, the question is why you defined list
as a scalar in the first place. Even in bash, it would perhaps make more sense to use it as array. In Zsh, an array would be (perhaps - depends on what else you want to do with it) even more convenient than a single string.
Upvotes: 0
Reputation: 246817
You can use a parameter expansion flag to split the string at newlines:
for line in ${(f)list}; do ...
See http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
Upvotes: 2
Reputation: 141040
Most certainly consider using an array instead:
arraylist=(aaa bbb ccc ddd)
for i in "${arraylist[@]}"; do echo "$i-xxx"; done
You seem to want to iterate over lines in a variable, so you want to do:
while IFS= read -r i; do echo "$i-xxx"; done <<<"$list"
If you want to suffix each line with -xxx
string, use sed
instead:
sed 's/$/-xxx/' <<<"$line"
There's also xargs
:
xargs -d'\n' -i echo {}-xxx <<<"$line"
If you want to iterate over words in a string and the words may be inside double quotes, I would go with xargs
:
xargs -i echo {}-xxx <<<"$line"
If you want to iterate over words in a string without interpreting quotes, the way in other answer with for i in $(echo $list)
is compatible with both zsh and bash
Upvotes: 5