Interesting behaviour of echo -n command when used in the beginning

放肆的年华 提交于 2020-05-31 04:02:31

问题


I'm seeing one interesting behaviour with some commands which need manual interruption when piped with echo -n command.

bash-3.2$ openssl
OpenSSL> exit

bash-3.2$ echo -n | openssl
OpenSSL> bash-3.2$

bash-3.2$ telnet 10.207.139.8 22
Trying 10.207.139.8...
Connected to 10.207.139.8.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.4
^]
telnet> Connection closed.

bash-3.2$ echo -n | telnet 10.207.139.8 22
Trying 10.207.139.8...
Connected to 10.207.139.8.
Escape character is '^]'.
Connection closed by foreign host.
bash-3.2$

When used with echo -n it will not prompt for user input. What is happening behind the scene?

The man page of echo command says this

 -n    Do not print the trailing newline character.  This may also be achieved by appending `\c' to the end of the string, as is done by iBCS2
           compatible systems.  Note that this option as well as the effect of `\c' are implementation-defined in IEEE Std 1003.1-2001 (``POSIX.1'')
           as amended by Cor. 1-2002.  Applications aiming for maximum portability are strongly encouraged to use printf(1) to suppress the newline
           character.

回答1:


When you connect two commands into a pipeline, foo | bar, the output of the first command is passed as the input to the second command.

By contrast, when you just run the second command on its own, bar, its input is inherited from the environment. In your case, that means the input comes from you typing at the console.

So, this:

openssl

runs openssl and lets you type input to it, whereas this:

echo -n | openssl

runs openssl with completely empty input — so it immediately sees end-of-file and exits.

(In many cases, it's still possible for a program to access the console and interact directly with you. But usually Unix-y programs are designed not to force themselves on you that way. If you redirect standard input to come from somewhere else, most Unix-y programs will respect that.)

Incidentally, a more conventional way to pass empty input to a command is to use the special always-empty file /dev/null:

openssl </dev/null


来源:https://stackoverflow.com/questions/60609763/interesting-behaviour-of-echo-n-command-when-used-in-the-beginning

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