Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: bug: nested for loop body is executed once!



On Thu, Aug 12, 2021 at 11:13:09PM -0400, Daniil Iaitskov wrote:
> Hi,
> 
> I just spot a following bug on Big Sur zsh 5.8 (x86_64-apple-darwin20.0)
> 
> $ K="1 2 3"
> > $ for i in $(for j in $K; do echo "ddd/$j" ; done) ; do echo  "$i" ; done
> > ddd/1
> > 2
> > 3

That's because zsh doesn't do word splitting on parameter expansions by
default. Running under set -x is illuminating.

+zsh:3> j=1 2 3
+zsh:3> echo 'ddd/1 2 3'
+zsh:3> i=ddd/1
+zsh:3> echo ddd/1
ddd/1
+zsh:3> i=2
+zsh:3> echo 2
2
+zsh:3> i=3
+zsh:3> echo 3
3

j is assigned '1 2 3' and the result of the command substitution is
'ddd/1 2 3'. However word splitting does happen on unquoted command
substitutions, so i is assigned to thrice.

> I would expect following output
> 
> > ddd/1
> > ddd/2
> > ddd/3

You want an array: K=(1 2 3)

At which point you could skip the command substitution and instead
for i in ddd/$^K; do ...




Messages sorted by: Reverse Date, Date, Thread, Author