Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this echo construct does not work?

Tags:

bash

echo

When I do this:

$ /bin/echo 123 | /bin/echo

I get no o/p. Why is that?

like image 860
Ankur Agarwal Avatar asked Dec 22 '22 09:12

Ankur Agarwal


2 Answers

You ask why it doesn't work. In fact, it does work; it does exactly what you told it to do. Apparently that's not what you expected. I think you expected it to print 123, but you didn't actually say so.

(Note: "stdin" is standard input; "stdout" is standard output.)

/bin/echo 123 | /bin/echo

Here's what happens. The echo command is executed with the argument 123. It writes "123", followed by a newline, to its stdout.

stdout is redirected, via the pipe (|) to the stdin of the second echo command. Since the echo command ignores its stdin, the output of the first echo is quietly discarded. Since you didn't give the second echo command any arguments, it doesn't print anything. (Actually, /bin/echo with no arguments typically prints a single blank line; did you see that?)

Normally pipes (|) are used with filters, programs that read from stdin and write to stdout. cat is probably the simplest filter; it just reads its input and writes it, unchanged, to its output (which means that some-command | cat can be written as just some-command).

An example of a non-trivial filter is rev, which copies stdin to stdout while reversing the characters in each line.

echo 123 | rev

prints

321

rev is a filter; echo is not. echo does print to stdout, so it makes sense to have it on the left side of a pipe, but it doesn't read from stdin, so it doesn't make sense to use it on the right side of a pipe.

like image 153
Keith Thompson Avatar answered Dec 30 '22 02:12

Keith Thompson


"echo" reads from command line, not standard input. So pipeline is not working here.

From bash manual:

echo [-neE] [arg ...]

Output the args, separated by spaces, terminated with a newline.

So your first echo did print "123" to stand output, however, the second echo didn't make use of it so "123" is dropped. Then an empty line is printed as if you run "echo".

You can use cat as Keith Thompson suggested:

echo 123|cat
like image 20
Mu Qiao Avatar answered Dec 30 '22 02:12

Mu Qiao