Redirecting Output

a minute read

Linux_logo_errorbits.com

Each Linux/Unix command has 3 communication channels: input, output and error. The output can be filtered and then redirected and by this way parts of it can be captured, depending on the needs.

Redirecting the output to a file, using > or >>:

> – if the file mentioned does not exist it will be created, and if it does exist it will be overwritten;

ls -la > testfile1.txt

>> – if the file mentioned does not exist it will be created, and if it does exist the information it will be added at the end, without affecting existing data (append);

ls -la >> testfile2.txt

Redirecting the errors to a file, using > or >>:

Identification ID for errors channel is “2“, to capture the error output we must add this digit to our command:

ls -la 2> testfile3.txt

ls -la 2>> testfile4.txt

If we want to remove the output and/or the errors created by a command, we can send them to a special folder /dev/null;

Keep the output, remove the errors:

ls -la 2> /dev/null

Keep the errors, remove the output:

ls -la > /dev/null

Remove output, remove errors:

ls -la > /dev/null 2>&1

Commands, used to redirect the output and the errors, can be combined:

ls -la > testfile5.txt 2> testfile6.txt
ls -la >>testfile5.txt 2> testfile6.txt
ls -la >>testfile5.txt 2> /dev/null

And examples can continue, as you can see, there are a lot of variations.

If you  want to get the output/error on both console and file, you must use the command below:

ls -la 2>&1 | tee testfile7.txt

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

The ifconfig command is used to view the current network configuration for ethernet cards and iwconfig displays the network configuration for wireless cards. Because this is the output from a Virtual Machine the ethernet is called enp0s3, on hardware machines ...
In a Unix system, the two fundamental notion is that things are either a file or a process. A file is just a destination for or a source of a stream of data. A process on the other hand is a program that is currently running and this program may be associated ...