1

I using macos 10.14.2 (18C54) with zsh (latest version I couldn't find any versioning with zsh). If I create an array from a string it works. But If i use a variable containing the string split does not work. Is this expected behavior or something wrong with my environment? What is the correct way to do this if I am doing it wrong?

~ arr=(foo bar)
~ echo $arr[1]
foo
~ val='foo bar'
~ arr=($val)
~ echo $arr[1]
foo bar
1

I suppose if you wanted to do this in zsh, you would do the following.

~ arr=(foo bar)
~ echo $arr[1]
foo
~ val='foo bar'
~ eval "arr=($val)"
~ echo $arr[1]
foo

When you entered arr=($val), zsh interpreted this to mean arr=("foo bar") even though you did not explicitly put a pair of " around $val. When I entered eval "arr=($val)", zsh interpreted this to mean arr=(foo bar). Using eval can be confusing. When in doubt, you can use the following experiment.

Say you want to know what eval sees and therefore what really will be executed. Start with the statement shown below. Here, I assume you have already entered val='foo bar'.

eval "arr=($val)"

Now replace eval with echo as shown below.

echo "arr=($val)"

Entering the above command produces the following result.

arr=(foo bar)

This what zsh will actually be executing.

  • thank you it worked. also thank you for the tip. I will use it. – Hadi Tok Feb 13 at 13:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .