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

Word splitting/joining inside [[ ]]



I have a string of words:

words="I have a string of words"

What I want to learn is whether the words are already in sorted order.

So my thought is to split the string on spaces, sort the resulting array,
and join the string back together again on spaces, and compare that string
to the original string.

So I wrote this:

[[ $words = ${(on)=words} ]]

Doesn't work.  It's always true.  Confused, I setopt xtrace and discover:

torch% [[ $words != ${(on)=words} ]]
+zsh:6> [[ 'I have a string of words' = I\ have\ a\ string\ of\ words ]]

Oh, I have the (on) at the wrong nesting level.

torch% [[ $words = ${(on)${=words}} ]]
+zsh:7> [[ 'I have a string of words' == I\ have\ a\ string\ of\ words ]]

Er, apparently that's not it.  Works fine outside [[ ]]:

torch% print ${(on)${=words}}
+zsh:8> print a have I of string words
a have I of string words

But then so does the original:

torch% print ${(on)=words} 
+zsh:9> print a have I of string words
a have I of string words

By accident I discovered that adding a supposedly-meaningless extra level
of nested expansion makes it work:

torch% [[ $words = ${${(on)=words}} ]]
+zsh:12> [[ 'I have a string of words' == a\ have\ I\ of\ string\ words ]]

What's going on here?



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