Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Although this is a basic stuff, but still i wonder. Consider these two examples.

Case 1:

[root@dhcppc0 practice]# cat file1 > wc -l
cat: invalid option -- l
Try `cat --help' for more information.

Case 2:

[root@dhcppc0 practice]# cat file1 | wc -l
7

I wonder, why doesn't redirection work in first case? when to use redirect and when to use pipes? I have been Linux for a long time, but still this basic stuff baffles me.

Please help.

share|improve this question

migrated from stackoverflow.com Jul 31 '11 at 12:29

This question came from our site for professional and enthusiast programmers.

1  
Useless use of cat! (wc -l < file1 would have done the same) – slhck Jul 31 '11 at 12:36
4  
wc -l file1 is even better. – Delan Azabani Jul 31 '11 at 12:48
    
@Delan In that particular example, yes (it'll even show you the name of the file) -- otherwise, depends on the command. – slhck Jul 31 '11 at 13:14
up vote 5 down vote accepted

The redirection operator is used to stream a command's stdout to a file (>), or to stream a file's contents to stdin for a command (<).

The pipe operator (|) streams the processes' output (stdout) to the next processes' stdin.

The only way to make your first case work would be to use a temporary file, so you would need to use two steps:

cat file1 > tmpfile
wc -l < tmpfile
share|improve this answer
    
Sorry for the stuff lost in the edit! Easier to grasp with an example though :) – slhck Jul 31 '11 at 12:42
    
@slhck no worries man, that's why we have revisions :) – Breakthrough Jul 31 '11 at 12:44

You use pipes when you want to connect a FD of one executable to a FD of another. You use redirection when you want to connect a FD of an executable to a file.

share|improve this answer
    
Can you please explain me in terms of commands, what you say is more understandable in case of pipes( ). – kingsmasher1 Jul 31 '11 at 12:31
1  
somecommand | someothercommand somecommand > somefile somecommand < somefile – Ignacio Vazquez-Abrams Jul 31 '11 at 12:32
    
Ohhh !! i got it. Thank you. – kingsmasher1 Jul 31 '11 at 12:35
    
I accept the second answer due to his example, but upvote both. – kingsmasher1 Jul 31 '11 at 12:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .