In Bash, pipes (|
) are used to connect the output of one command to the input of another command, allowing you to create powerful data processing and transformation pipelines. Pipes enable you to chain multiple commands together, where the output of one command becomes the input for the next command. Here’s how pipes work:
Syntax:
command1 | command2
Explanation:
- The output of
command1
is sent as input tocommand2
. command1
is executed, and its output is streamed directly to the input ofcommand2
.command2
processes the input received fromcommand1
.
Example: Let’s say you have a log file called access.log
, and you want to filter out the lines containing a specific IP address and then count the occurrences of that IP address. You can use pipes to achieve this:
grep "192.168.0.100" access.log | wc -l
Explanation:
- The
grep
command filters the lines ofaccess.log
that contain the IP address “192.168.0.100”. - The output of
grep
is then piped (|
) to thewc -l
command. wc -l
counts the number of lines in the input received fromgrep
.- The final result is the count of lines that match the IP address.
Pipes can be used to build complex command pipelines by connecting multiple commands together. Each command in the pipeline processes the input received from the previous command, allowing you to perform various operations on the data, such as filtering, sorting, transforming, and aggregating. Pipes are a powerful feature of Bash that enable efficient and flexible data processing in the command-line environment.