2

I have a script (in Node.js) named script.js which outputs the following string:

(1, 2, 3)

I want to read it in a loop in the following way:

INDICES=$(node script.js)
for i in "{INDICES[@]}"
do
    echo $i
done

Instead of printing

1
2
3

I get

(1, 2, 3)

Since the script output is read as string.

How do I make it an array?

  • I suggest you ask this on stackoverflow... – djsmiley2k Apr 5 '17 at 14:58
  • @djsmiley2k Why? Bash questions are on topic here. – DavidPostill Apr 5 '17 at 15:14
  • @DavidPostill they are? ok. :) – djsmiley2k Apr 6 '17 at 7:44
2
#!/bin/bash

inputstr="(1, 2, 3)"

newstr=$(echo $inputstr | sed 's/[()]//g' ) # remove ( and )

IFS=', ' read -r -a myarray <<< "$newstr" # delimiter is ,

for index in "${!myarray[@]}"
do
    # echo "$index ${myarray[index]}"  #  shows index and value
      echo        "${myarray[index]}"  #  shows           value
done

which give this output

./string_to_array.sh
1
2
3
2

Solution by Scott is pretty good, but it uses external processes. Here is a method that uses bash build-ins only:

#!/bin/bash

inputstr="(one, two, three)"
tempvar=$(echo $inputstr)
array=(${tempvar//[\(\),]/})

for value in "${array[@]}"; do
  echo "${value}"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.