I want to write out a bash array variable to a file, with each element on a new line. I could do this with a for loop, but is there another (cleaner) way to join the elements with \n
?
Bash – Convert Array Variable to String Delimited with Newlines
bashnewlines
Best Answer
Here's a way that utilizes bash parameter expansion and its
IFS
special variable.We use a subshell to avoid overwriting the value of
IFS
in the current environment. In that subshell, we then modify the value ofIFS
so that the first character is a newline (using$'...'
quoting). Finally, we use parameter expansion to print the contents of the array as a single word; each element is separated by the first charater ofIFS
.To capture to a variable:
If your bash is new enough (4.2 or later), you can (and should) still use
printf
with the-v
option:In either case, you may not want the final newline in
var
. To remove it: