Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I saw this usage of redirection somewhere, and thought it was a typo:

grep root < /etc/passwd

But after I run it, I saw that it gives the same output with grep root /etc/passwd:

$ grep root < /etc/passwd
root:x:0:0:root:/root:/bin/bash

$ grep root   /etc/passwd
root:x:0:0:root:/root:/bin/bash

The same thing happens with

cat < /etc/passwd
cat   /etc/passwd

However, redirection is ignored when used with ls:

ls < /etc/passwd

does not print the same output with

ls  /etc/passwd

What is happening?

share|improve this question
2  
If the command requires standard input, you must use redirection. If the command requires file name parameter, you must not use redirection. If the command accepts both file name parameter and standard input, you may use redirection, but is preferable to let the command handle the file operation. –  manatwork Sep 9 '11 at 9:20
1  
Trying another explanation: ls < /etc/passwd not works for the same reason why neither cat /etc/passwd | ls works. If you run grep '' or cat from the command prompt (no input, no parameters), they will wait for you to enter the input from the keyboard. But ls will not do that as it expects no input. –  manatwork Sep 9 '11 at 10:31
add comment

1 Answer

up vote 8 down vote accepted

Many utilities which work with files will accept stdin (standard input) as streamed input, or accept the file-name as a parameter.. Your < file examples are redirecting the output of the file to the utility. The file was opened by the shell and passed on to your utility via stdin ..

On the other hand, with cat file, cat is handling the opening and reading of file, and no redirection is involved.

ls never reads a file, therefore it does not take a file name as a parameter with a view to opening and reading the file.. (it accepts file-name masks) ... For ls, the redirection action is, in effect, ignored because nothing in the process reads the shell-opened file...

To determine how any utility behaves, just type man utility-name in the terminal... man is a contraction of manual ... eg. man cat presents you with cat's manual

share|improve this answer
4  
I always think wc is a useful program to serve as a demonstration, because it behaves slightly differently with a file to a redirection: in the former case the filename is printed. With a redirection you can capture the output in a subshell and use it as an integer. –  jmtd Sep 9 '11 at 9:26
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.