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

1

2

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.
Levileviable answered 9/3, 2020 at 23:45 Comment(0)
P
4

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
Peanut answered 9/3, 2020 at 23:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.