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?
Best Answer
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) ... Forls
, 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