3

I was reading this question and answer: zsh - variable assignment isn't working. The post explains how to fix it, but not why. Why does the local variable assignment fail in that case ?

There are also some other examples of similar behaviour like this:

myfun()
{
local x=$(echo "a b"); echo ${x} 
}

myfun2()
{
local x 
x=$(echo "a b")
echo ${x}
}

myfun3()
{
local x=$(echo "a b")
echo ${x}
}

This results in the following output:

a
a b
a

If I put quotes around the 'x="$(echo "a b")" in all cases I get the correct variable assignment.

If I run the same thing in bash, I get 'a b' for all functions.

Can someone explain why bash and zsh are acting differently here ?

1

If you run your script with -x (both bash and zsh) you will see that the $(...) code gets interpreted/parsed differently. This is because, as stated in the FAQ, word splitting in zsh is backwards/bash/sh incompatible.

You can use SH_WORD_SPLIT to address this difference.

Ok, so it is not a word split problem as we have a command substitution, quoting the docs again:

...If the substitution is not enclosed in double quotes, the output is broken into words using the IFS parameter...

So your alternative is to local IFS="" :/

  • that doesn't seem to work: zsh -x test.sh +test.sh:1> setopt shwordsplit +test.sh:21> myfun +myfun:2> echo 'a b' +myfun:2> local 'x=a' b +myfun:2> echo a – theooze Jun 29 '15 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.