while-loopzshexpansion

How to iterate through string one word at a time in zsh


How do I modify the following code so that when run in zsh it expands $things and iterates through them one at a time?

things="one two"

for one_thing in $things; do
    echo $one_thing
done

I want the output to be:

one 
two

But as written above, it outputs:

one two

(I'm looking for the behavior that you get when running the above code in bash)


Solution

  • In order to see the behavior compatible with Bourne shell, you'd need to set the option SH_WORD_SPLIT:

    setopt shwordsplit      # this can be unset by saying: unsetopt shwordsplit
    things="one two"
    
    for one_thing in $things; do
        echo $one_thing
    done
    

    would produce:

    one
    two
    

    However, it's recommended to use an array for producing word splitting, e.g.,

    things=(one two)
    
    for one_thing in $things; do
        echo $one_thing
    done
    

    You may also want to refer to:

    3.1: Why does $var where var="foo bar" not do what I expect?