Tags

, , , , , , , , ,

Piping and redirection are two powerful tools in the Unix kit. | is the pipe operator. > is the redirect operator.

Piping connects the standard out of one program to the standard in of another. You can think of it as a literal pipe: There’s a stream of data from the leftmost command to the right.

For example:

$ foo | bar

This connects foo’s standard out to bar’s standard in. What foo outputs, bar receives. You can build pipelines:

$ foo | bar | baz

This connect’s foo to bar and bar to baz. For a real example, the following chains together four commands to print all of the processes that are running on your system with more than one instance:

$ ps ax | awk ‘{ print $5 }’ | sort | uniq -dc

There is a little shell work here to set things up, but pipes mostly rely on existing kernel functionality.

Redirects are about files, not just processes:

$ foo > file

The standard out from foo is stored in the file named “file” instead of displaying on the console. The shell implements this by opening the file, setting it as standard in, and then running the new process.

Summary: Piping chains together two or more processes by connecting the outputs of an antecedent process to the input of the immediately subsequent process. Redirection is a shell feature that saves a process’s output in a file or copies a file into a process’s input.

You use pipes with processes, redirects with a process and a file.

-By Robert Love on Quora

About these ads