Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh to iterate like in bash

Tags:

bash

zsh

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?

like image 646
user14558198 Avatar asked Oct 30 '25 09:10

user14558198


1 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

like image 64
KamilCuk Avatar answered Nov 01 '25 14:11

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!