Linux Bash provides a lot of useful features and commands. Pipe or
| is one of them. Bash provides a command-line interface facility which mainly used to concatenate command output to another command.
Bash Pipe Concept
In Linux everything is file. This may seem odd but it is. Every command executed will have three type of streams which can be used to provide or output data into and from a command.
- STDIN (0) Standard input where command reads from. In bash default is bash shell
- STDOUT (1) Standard output where command output written. In bash default output is bash shell generally.
- STDERR (2) Standard error where command errors are written.
Bash Pipe Usage
The pipe will redirect the command STDOUT or standard output into the given next command STDIN or standard input. The syntax is like below. In this example, COMMAND1 output will be feed into COMMAND2 as input.
COMMAND1 | COMMAND2
Now let’s make a simple example. We will use
cat command to print file named
names.txt into command
sort as input.
$ cat names.txt | sort
Pipe Multiple Commands
In the previous example, we have used only one pipe but we can use multiple pipes without a problem to make things better. We just put them in a string like below. In this example, we will pipe commands
$ cat names.txt | sort | grep "a"
Pipe To Grep Command
One of the most popular usages of the pipe is with
grep command. We will use multiple grep commands in this example where we will filter line those contains
$ cat names.txt | grep "a" | grep "i"
Pipe To Less Command
less command is another use case for the bash pipe. We generally use cat command to print a file context into less command. In this example, we want to look into the log file of
$ cat /var/log/firewalld | less