What is I/O Redirection?
I/O redirection is a Linux feature that enables you to determine which standard input/output device to send input/output to. The different input/output devices available on Linux are;
– stdin device which is the Keyboard
– stdout device which is the Screen
– stderr device which is reserved for error outputs
Output Redirection
The ‘>’ symbol is used for output (stdout) redirection. Take the following command for example;
1 |
$ ls -al > list.txt |
The output of command ‘ls -al’ is re-directed to file ‘list.txt’ instead of your screen. Take note that the redirection symbol ‘>’ overwrites any contents in the file. Therefore, If you need to append the output to an existing file, use ‘>>’ instead.
1 |
$ ls -al >> list.txt |
Input redirection
The ‘<‘ symbol is used for input (stdin) redirection. The example below redirects the contents of ‘/etc/passwd’ to grep command so that grep can filter the input.
1 |
$ grep -nr "root" < /etc/passwd |
In Linux/Unix, everything is a file. Every File has an associated number called File Descriptor (FD). The file discriptors are as below
File File Discriptor
stdin ———> 0
stdout ———> 1
stder ———> 2
By default, error stream is displayed on the screen. Error redirection is routing the errors to a file other than the screen.
Error Redirection
When a Linux command/script you are executing encounters an error, you can redirect the output to a file as below.
1 |
$ ls -fake 2> error.log |
In this example, ‘-e’ is an invalid option for the ls command. Therefore, instead of displaying the error on the screen, the error is redirected to the ‘error.log’ file.
harun
Latest posts by harun (see all)
- Linux Input/Output Redirection - May 28, 2020
- Reset Linux Root Password Using Rescue CD - September 21, 2018
- Extending Linux Root Partition using LVM - June 14, 2018