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...
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.
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 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.
Use printf
instead:
printf "%s\n" "${testa[@]}" > file.txt cat file.txt 1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With