Home > Software engineering >  How to convert bash array to list and save to a file?
How to convert bash array to list and save to a file?

Time:10-26

I'm having array and I want to convert it in the form of list and save it to a file.

Here is what I tried:

export arrVal=(a,b,c)
echo NEWLIST="${arrVal[@]}" >> newtextfile

Output:

NEWLIST=a,b,c

Expected Output:

NEWLIST=[a,b,c]

CodePudding user response:

You can add the square brackets to your expression, something like that:

export arrVal=(a,b,c)    
echo NEWLIST="[${arrVal[@]}]"

Output:

NEWLIST=[a,b,c]

CodePudding user response:

As @pmf wrotes in comment...

arrVal=(a,b,c)

...is only one value of key 0.

Look...

array=(a,b,c)
echo ${#array[@]} # puts out: 1
# Or only key 0...
echo ${array[0]} # puts out: a,b,c

Now...

array=(a b c)
echo ${#array[@]} # puts out: 3

# You can loop over it with...
for key in ${array[@]}; do echo ${key}; done
# That puts out...
a
b
c
  •  Tags:  
  • bash
  • Related