How to display newline in ssh

2019-07-07 04:52发布

问题:

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?

回答1:

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.



回答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.



回答3:

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)



回答4:

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