What is the difference between the following commands:
$ input.txt > grep foo
$ grep foo < input.txt
$ cat input.txt | grep foo
$ grep foo input.txt
And not just grep
. Other commands too.
What is the difference between the following commands:
$ input.txt > grep foo
$ grep foo < input.txt
$ cat input.txt | grep foo
$ grep foo input.txt
And not just grep
. Other commands too.
input.txt > grep foo
This is probably an error. It runs the command input.txt
and redirects the output to a file called grep
. The foo
is an argument to the command input.txt
.
grep foo < input.txt
This looks for the string foo
in the input coming from input.txt
. grep
does not get a filename on the command line, so it will work on standard input instead. The shell will, through the redirection, ensure that the contents of the file input.txt
is delivered on the standard input stream for grep
.
cat input.txt | grep foo
This is similar to the previous, but the standard input stream of grep
is now connected to a pipe through which the cat
command delivers the contents of the file input.txt
. The cat
command writes to its standard output stream, which is connected to the standard input stream of grep
by the pipe.
grep foo input.txt
This makes grep
open the file input.txt
and look for the string foo
in it. It does not use the standard input stream.
In general:
A pipe (|
) connects the standard output stream of its left side with the standard input stream of its right side.
A input redirection (<
) redirects from a file to the standard input stream.
An output redirection (>
) redirects the standard output to a file.
Input and output streams may be redirected at the same time, e.g. using commandname <inputfile >outputfile
, and a command may both read and write to a pipe, as the second command in command1 | command2 | command3
.
Redirection and piping may be combined: cat <input.txt | grep foo >output.txt
.
Many Unix utilities takes an input filename as an optional argument, and will use standard input if no filename was given.
Some Unix utilities only works on standard input, like tr
for example.
Bash and some other shells, like ksh
, also supports redirection from a string to standard input using <<<"string"
(called a here-string), and most shells understands here-documents (look these up).
input.txt > grep foo > output.txt?
or grep foo < input.txt > output.txt
– vikarjramun
Aug 24 '16 at 12:36
commandname >outputfile <inputfile
or commandname <inputfile >outputfile
. The first word on the command line will always be interpreted as a command, so inputfile >commandname
won't work.
– Kusalananda
Aug 24 '16 at 12:38