user14558198
user14558198

Reputation: 47

zsh to iterate like in bash

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

Answers (3)

user1934428
user1934428

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

glenn jackman
glenn jackman

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

KamilCuk
KamilCuk

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

Related Questions