Do you know why the following is not converting string into array?
STR="one two three"
array=("$STR")
echo "${array[@]}" # prints: one two three
echo "len: ${#array[@]}" # prints: len: 1
CodePudding user response:
You have to tell zsh that you want word splitting to occur:
array=( ${(z)STR} )
NOTE This applies to zsh. At the time I was writing the answer, the question was tagged zsh, but meanwhile the tag was changed to bash. In bash, the assignment would be
array=( $STR )
CodePudding user response:
cat "73276948.sh"
#!/bin/bash
STR="one two three"
array=($STR)
echo "${array[@]}" # prints: one two three
echo "len: ${#array[@]}" # prints: len: 1
echo "1ST: ${array[0]}" # prints: one two three
echo "2ND: ${array[1]}" # prints: one two three
echo "3RD: ${array[2]}" # prints: one two three
echo "Using loop:"
for (( indx = 0; indx < ${#array[@]}; indx ))
do
echo "$indx" "${array[indx]}"
done
Output:
$ ./73276948.sh
one two three
len: 3
1ST: one
2ND: two
3RD: three
Using loop:
0 one
1 two
2 three
Related difference:
array=("$STR")
array=($STR)
CodePudding user response:
I found this to be working:
bash
array=($STR) # removed expansion ""
zsh
eval "array=($STR)"