The pipe and redirect commands are some of the most useful commands when using the terminal on Linux. The Pipe command or “|” is one type of redirection that can be used to take the output on one command and input it into another. You can also take standard input/output and move it to a file. In this tutorial, we will be going over different examples of using redirection.
The different types of I/O streams in Linux. A stream is information or text on a terminal going from one command to another.
- standard input (stdin) – Input that can be recalled later
- standard output (stdout) – The output of a command
- standard error (stderr) – Errors generated
Redirection commands. Or commands used to write to a file.
- > - standard output
- < - standard input
- 2> - standard error
command1 > command1_output.txt
systemctl status apache2 > webserver_status.txt
Above we created a file called webserver_status.txt to write the output of the status of the Apache webserver. If you would like to append output to a file, use “>>”. This will not overwrite the data but add it to the file.
systemctl status apache2 >> webserver_status.txt
command1 < file.txt
cat < webserver_status.txt
Above shows the cat command using "<" stdin which would be the same as executing cat webserver_status.txt
command1 2> error1.txt
apt update 2> error1.txt
The above shows, when running cat error.txt, the permission errors that were saved to error1.txt
Like stdout, stdin and stderr can have data appended to the files as well:
- >> - standard output
- << - standard input
- 2>> - standard error
The Pipe command
The pipe command or “|” can take the output of a command to be used as input for another command. Here is the syntax below:
command1 | command 2
In this example, we will take the cat command’s output and use it as the input for grep to filter for a string of text.
cat -n /etc/php/7.4/apache2/php.ini | grep max
The above output shows filtering for the word ‘max’ in the php.ini file. This is helpful to find a variable.
Article is closed for comments.