8

Can anyone tell me the difference? for example:
if I have a file a.txt with the following content:

a
b
c

what would be the difference between cat a.txt | cat and cat < a.txt
It seems to me that they all simulate STDIN, is that correct, or are there differences? Thanks a lot.

user685275
  • 2,097
  • 8
  • 26
  • 32
  • 2
    Voting to move to Super User, this is not a programming question. – unwind Apr 27 '11 at 10:54
  • 1
    @unwind uh..yeah it is. Bash is a programming language. This is programming- at a high level. – Dennis Jun 17 '11 at 20:18
  • 2
    The question exists here (where it's more suitable): http://askubuntu.com/questions/172982/what-is-the-difference-between-redirection-and-pipe – Ofer Zelig May 16 '14 at 04:37

3 Answers3

11

Piping works from one process to another (the cats in the first example), and hence requires two processes cooperating. Redirection is handled by the shell itself. This can matter when doing things in the shell such as working with variables.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

The redirection does not "simulate STDIN". When you redirect, the file is the stdin for the process. In particular, many programs have different behavior if the input is a regular file than if it is a pipe or a tty, so you may get different behavior. For example:

$ < file perl -E 'say "is a regular file" if -f STDIN'
is a regular file
$ cat file | perl -E 'say "is a regular file" if -f STDIN'
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • sorry, I am new to this, is it possible that you could explain a bit about your example program, thanks. – user685275 Apr 27 '11 at 15:47
  • 1
    @user685275 The program just checks whether its input stream (stdin) is a regular file. If it is, it prints "is a regular file". If not, it does nothing. When you redirect from a file, the file is the input stream for the program. When you pipe from a another process, the read side of the pipe is the input stream. When you run without piping or redirections from a tty, the tty is the input stream. – William Pursell Apr 27 '11 at 17:10
  • Thanks for answering, appreciate it. – user685275 Apr 28 '11 at 11:08
1

Firstly, two results are same. Nothing to say.

For the work principle of cat a.txt | cat, the first cat takes argument a.txt, then prints its content. You pipe the stdout of the first to stdin of the second. The second cat finds no argument so it reads content from stdin, and prints it.

Because you use < in the second command, system replaces stdin of cat with file stream of a.txt. Anything else is same as the second cat in the first case.

Wizard Z.
  • 61
  • 2