1

I have a bash script and I have a string with some \n:

interfaces="auto lo\niface lo inet loopback\n\n..."

Then I try to write this into the interfaces file like so:

sudo bash -c "echo -e $interfaces > /etc/network/interfaces"

I use -e to display the \n's but if I open the file it doesn't show right but if I just output it to the terminal it works:

auto loniface lo inet loopbacknn...

WasteD
  • 758
  • 4
  • 24
  • Look at http://stackoverflow.com/questions/9139401/trying-to-embed-newline-in-a-variable-in-bash – Dmitry Feb 13 '17 at 09:44
  • 2
    @KenY-N That won't work when the string gets substituted into the `bash -c` argument. `bash` will see it as a literal newline, which is a command delimiter. – Barmar Feb 13 '17 at 09:46
  • @KenY-N I mean if I `echo` it to the terminal it works but not in the file. I'll try the solution of @Barmar now. – WasteD Feb 13 '17 at 09:46
  • 1
    Hmm, given the answer below, I've changed my mind about it being a dup - the extra level of quotes is missing from the linked dup. – Ken Y-N Feb 13 '17 at 09:46

1 Answers1

5

Put quotes around the variable.

sudo bash -c "echo -e '$interfaces' > /etc/network/interfaces"

Outside of a quoted string, \n gets replaced with n.

Barmar
  • 741,623
  • 53
  • 500
  • 612