Linux Bash Pipe Command Usage with Examples For Redirection
Linux Bash provides a lot of useful features and commands. Pipe or
| is one of them. Bash provides command line interface facility which mainly used to concatenate command output to another command.
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.
Pipe will redirect the command STDOUT or standard output into the given next command STDIN or standard input. Syntax is like below. In this example COMMAND1 output will be feed into COMMAND2 as input.
COMMAND1 | COMMAND2
Now lets 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 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
One of the most popular usage of 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
less command is another use case for bash pipe. We generally use
cat to print a file context into
less command. In this example we want to look into log file of
$ cat /var/log/firewalld | less