Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh is not splitting by IFS after parameter expansion

This is my code to loop over colon separated values and do something with each value.

f()
{
    IFS=:
    for arg in $1
    do
        echo arg: $arg
    done
}

f foo:bar:baz

This works fine in most POSIX compliant shells.

$ dash foo.sh
arg: foo
arg: bar
arg: baz
$ bash foo.sh
arg: foo
arg: bar
arg: baz
$ ksh foo.sh
arg: foo
arg: bar
arg: baz
$ posh foo.sh
arg: foo
arg: bar
arg: baz
$ yash foo.sh
arg: foo
arg: bar
arg: baz

But it does not work as expected in zsh.

$ zsh foo.sh
arg: foo:bar:baz

Is zsh in violation of POSIX here?

like image 947
Lone Learner Avatar asked Sep 20 '17 05:09

Lone Learner


1 Answers

Yes. Zsh has chosen its own way.

Here is the zsh faq entry: “3.1: Why does $var where var="foo bar" not do what I expect?”

In this particular case, you could workaround by adding the -y option to the zsh invocation:

$ zsh -y foo.sh
arg: foo
arg: bar
arg: baz

You could take a look at the zsh's faq especially the chapter 2 and 3. The more you've experienced other shells, the more you can find zsh's pitfalls.

like image 155
hchbaw Avatar answered Sep 21 '22 05:09

hchbaw