Pipes
Pipes
A pipe is a mechanism that allows the output of one command to be used as the input to another command. Pipes are used to combine multiple commands to perform more complex operations. In a pipeline, each command is executed in a separate process, and the standard output of the previous command is used as the standard input of the next command.
The symbol used to represent a pipe is the vertical bar |
. To use a pipe, simply place it between the commands that you want to combine. For example:
$ ls | grep txt
In this example, the ls
command lists all files in the current directory, and the grep
command searches for lines containing the string "txt" in the output of the ls
command. The result is a list of files that have "txt" in their names.
Here's another example that uses multiple pipes:
$ ps aux | grep firefox | awk '{print $2}' | xargs kill -9
In this example, the ps
command lists all running processes, and the grep
command searches for lines containing the string "firefox" in the output of the ps
command. The awk
command extracts the second field (the process ID) from each matching line, and the xargs
command passes the process IDs as arguments to the kill
command, which terminates the processes.
Pipes can be nested to create even more complex pipelines. For example:
$ cat file.txt | sort | uniq | wc -l
In this example, the cat
command outputs the contents of the file file.txt
, the sort
command sorts the lines in alphabetical order, the uniq
command removes duplicate lines, and the wc
command counts the number of lines in the output. The result is the number of unique lines in the file.
Pipes are a powerful feature of the command line, and they allow you to combine simple commands in creative ways to accomplish complex tasks.