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
Best Answer
I suppose if you wanted to do this in zsh, you would do the following.
When you entered
arr=($val)
, zsh interpreted this to meanarr=("foo bar")
even though you did not explicitly put a pair of"
around$val
. When I enteredeval "arr=($val)"
, zsh interpreted this to meanarr=(foo bar)
. Usingeval
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 enteredval='foo bar'
.Now replace
eval
withecho
as shown below.Entering the above command produces the following result.
This what zsh will actually be executing.