zsh to iterate like in bash

Viewed 355

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?

3 Answers

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

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.

Related