Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write bash array to file with newlines

Tags:

arrays

bash

How do I write an array to a file such that each element is separated by a newline?

The following does not work:

testa=( 1 2 3 ) echo "${testa[@]}" > file.txt 

(now the elements are separated by spaces on a single line) I would like avoid writing a for loop for this...

like image 800
Håkon Hægland Avatar asked Nov 27 '13 13:11

Håkon Hægland


People also ask

How do I print an entire array in Bash?

Print Bash Array We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.

How do you print an array element in a new line in Shell?

To print each word on a new line, we need to use the keys “%s'\n”. '%s' is to read the string till the end. At the same time, '\n' moves the words to the next line. To display the content of the array, we will not use the “#” sign.

How do I echo an array element in Bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


1 Answers

Use printf instead:

printf "%s\n" "${testa[@]}" > file.txt  cat file.txt  1 2 3 
like image 148
anubhava Avatar answered Oct 09 '22 00:10

anubhava