5

I'm trying to do the following:

#!/bin/sh
ssh user@server "echo \"Test \n for newline\""

This displays:

test \n for newline

How do I get the shell to interpret \n as an actual newline?

nullByteMe
  • 6,141
  • 13
  • 62
  • 99
  • `echo` disables interpretation of backslash escapes by default. – devnull Jun 17 '13 at 13:33
  • possible duplicate of [How can I have a newline in a string in sh?](http://stackoverflow.com/questions/3005963/how-can-i-have-a-newline-in-a-string-in-sh) – devnull Jun 17 '13 at 13:34
  • Note that the accepted answer for the linked duplicate is specific to `bash`. – chepner Jun 17 '13 at 13:51

4 Answers4

4

Try using the -e option, e.g., echo -e "Test \n for newline".

If your echo doesn't have a -e option, then I'd use printf. It's widely available and it does not have nearly as many variations in it's implementations.

cmt
  • 1,475
  • 9
  • 11
  • this doesn't work. Man page says `-n Do not print the trailing newline character.` That's the only option I have. The description in the beginning does say, "The echo utility writes any specified operands, separated by single `(` ')` characters and followed by a newline `(`\n')` character, to the standard output." – nullByteMe Jun 17 '13 at 13:45
  • If your `echo` doesn't have a `-e` option, then I'd use `printf`. It's widely available and it does not have nearly as many variations in it's implementations. – cmt Jun 17 '13 at 13:49
2

For greater portability, use printf instead of echo.

#!/bin/sh
ssh user@server 'printf "Test \n for newline"'

According to the POSIX standard, echo should process \n as a newline character. The bash built-in echo does not, unless you supply the -e option.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

Just use one of

#!/bin/sh
ssh user@server "echo -e \"Test \n for newline\""

or

#!/bin/sh
ssh user@server 'echo  -e "Test \n for newline"'

or

#!/bin/sh
ssh user@server "echo  -e 'Test \n for newline'"

or even

#!/bin/sh
ssh user@server "echo 'Test 
 for newline'"

All of those will display

Test 
 for newline

(note the trailing space after the first line and the leading space before the second one - I just copied your code)

mschilli
  • 1,884
  • 1
  • 26
  • 56
0

Before exectuning ssh command update the IFS environment variable with new line character.

IFS='                                  
'

Store the ssh command output to a varaible

CMD_OUTPUT=$(ssh userName@127.0.0.1 'cat /proc/meminfo')

iterate the output per line

for s in $CMD_OUTPUT; do echo "$s"; done
nix
  • 744
  • 9
  • 16