How to display newline in ssh

巧了我就是萌 提交于 2019-12-14 01:07:11

问题


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


来源:https://stackoverflow.com/questions/17148688/how-to-display-newline-in-ssh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!