开发者

Why this echo construct does not work?

When I do this:

$ /bin/echo 123 | /bin/ec开发者_开发百科ho

I get no o/p. Why is that?


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.


"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


/bin/echo 123 < /bin/echo

the pipe = concate

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html

Pipes let you use the output of a program as the input of another one

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜