Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

zsh/bash string to array not working using parentheses

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading