0

I'm trying to convert a string variable into an array to iterate over the elements in Bash

This is my variable:

items="component01 component02 component03"
echo $items
>> component01 component02 component03

I tried with items=($items) but when I check with echo ${#items[@]} I get just one single element so I can't iterate over the elements with a for loop.

Also, I cannot make use of read -a as I can't use it in macOS.

SemirAdam
  • 9
  • 3
  • What's your version of bash? `items=($items) ; echo "${#items[@]}"` gives me 3 on 4.1.2. – tjm3772 Jun 22 '23 at 16:14
  • 1
    If there were a good way to do this, `bash` wouldn't need arrays. `items=($items)` works fine, as long as none of the "items" is supposed to contain whitespace (or elements that could be subject to pathname expansion). `read -a arr <<< "$items"` is a possibility, but suffers from the same whitespace issue that led to the introduction of arrays in the first place. – chepner Jun 22 '23 at 16:15
  • 1
    `read -a` is supported in the (ancient) default version of Bash on macOS. It's a good option for solving your problem. You may be thinking of `readarray`. It was introduced in a later version of Bash, but it's not relevant to your problem. – pjh Jun 22 '23 at 16:28
  • Have you changed `IFS`? If not, `read -a items <<<"$items"` should work (yes, even in bash v3.2.57 that ships in macOS). If you have changed `IFS`... that'll cause a variety of problems, and you should change it back. – Gordon Davisson Jun 22 '23 at 22:35

3 Answers3

0

I'm not sure how to get it into an array per se but you can iterate through it as is provided $IFS=

#!/bin/bash

string="component01 component02 component03"
for s in $string
do
  echo $s
done

yields:

$ ./iterate.sh
component01
component02
component03

This works out of the box provided your IFS is set to the default space characters (tab, space, newline I think).

Just in case:

$ bash --version
GNU bash, version 5.2.15(3)-release (x86_64-pc-cygwin)
Dan
  • 45
  • 4
0

if your items split with whitespace, and none of your items of array does not have whitespace in itself, you can use this way to change it to array

arr=(`echo $items`)
Milad Keshavarzi
  • 56
  • 1
  • 1
  • 5
  • This one has worked in my case. Thanks. – SemirAdam Jun 23 '23 at 07:01
  • This is pointlessly complex -- the `echo` and the backticks basically cancel each other out (other than adding more opportunities for weird parsing behavior), so this is mostly equivalent to `arr=($items)`. See [Shellcheck warning SC2116: "Useless echo? Instead of `cmd $(echo foo)`, just use `cmd foo`"](https://www.shellcheck.net/wiki/SC2116) (and obviously, if you run the script through [shellcheck.net](https://www.shellcheck.net), it will point this out). – Gordon Davisson Jun 24 '23 at 08:17
0

Assuming space is the separator

IFS=" " a=( $items )
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134