Write array contents to file

Hi,

I have a bash script that currently holds some data. I am trying to write all the contents to a file called temp.txt.

I am using

echo ${array[@]} > temp.txt

The problem that I am experiencing is that the elements are being written horizontally in the file. I want them written vertically.

This code writes it correctly but it appends the file which I don't want it to do.

for j in "${array[@]}"
do
  echo $j >>temp.txt
done

By changing the line to echo $j > temp.txt, the file only contains the last array element.

Example

array[0] = 5
array[1] = 6
array[2] = 1
array[3] = 3

File contents

5 6 1 3

What I want is

5
6
1
3

Thanks.

You can move your redirection to the end of the loop, and use a single redirection that will overwrite the file:

for j in "${array[@]}"
do
      echo $j 
done >tmp.txt
1 Like
echo ${x[@]} | sed 's/ /\n/g' > temp.txt
1 Like

Thanks Agama

Your suggestion worked perfectly.

> temp.txt   # clear file or create
for j in ${array[@]}
do
     echo $j >>temp.txt
done
for j in ${array[@]}
do
   echo $j 
done >> temp.txt  # append   or  done > temp.txt to overwrite

No need to use loops or sed to separate an array on newlines. The shell can do this by itself by changing the IFS variable into a newline, letting you print the entire array in a single operation.

OLDIFS="$IFS"; IFS=$'\n'
        echo "${ARRAY[*]}" > file
IFS="$OLDIFS"

Note that "${ARRAY[*]}" must be in quotes for IFS to have the right effect here.