Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

2 Answers

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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.