0

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
  echo "item: ${array[2]}" # prints: <nothing>
1
  • You are making an array of one string here. What results do you expect other than zsh and bash not agreeing what the zeroth item of an array might be?
    – bmike
    Aug 8, 2022 at 12:28

3 Answers 3

3

The value of STR is one element in your array due to quoting. You could populate your array like-

array=(one two three)

Arrays in zsh start at 1 not 0 as in ksh and bash.

3

In ZSH you can use a parameter expansion. Here, the s: : expansion is used to split the string on which might be hard to see; we could call it ASCII decimal value 32 or just space.

% string="foo bar"
% array=(${(s: :)string})
% print $array[1]
foo

The bash code elsewhere on this page is not really safe under all conditions. The POSIX shell by default does an auto-split (which here is desired) and auto-glob (which may be very undesirable; if any glob characters at any point get into the string and then match files in the current working directory):

bash-5.1$ string="who* foo"
bash-5.1$ array=($string)
bash-5.1$ echo ${array[@]}
whoops.app whoops.png whoops.txt foo
bash-5.1$ printf '%s\n' ${array[@]}
whoops.app
whoops.png
whoops.txt
foo
bash-5.1$ ls whoops.*
whoops.app      whoops.png      whoops.txt

Surprise!!

(ZSH is not POSIX compliant so does not do the unquoted variable auto-split auto-glob thing (by default), thank goodness.)

2
  • Nice call out of the need for noglob in many command line scripting situations. +1
    – bmike
    Aug 8, 2022 at 13:42
  • 1
    I dabbled with noglob for a while then was like why don't I just use ZSH or some other language...
    – thrig
    Aug 8, 2022 at 14:22
1

I found this to be working:

bash

 array=($STR) # removed expansion ""

zsh

eval "array=($STR)"

You must log in to answer this question.

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