Main menu

Linux redirection

Linux redirection is a way to redirect output and error of a command into a file.

# cmd > output_file.txt

This will redirect the output of a command into output_file.txt.

You can display the content of file using cat command

# cat output_file.txt

Each open file get assigned a file descriptor (a numeric value)which represent what kind of communication is done by the system. Let’s see some file descriptor

Name Value Discritption Operation
STDIN 0 Standard Input Get input of a command from file or device.
STDOUT 1 Standard Output Redirect Output of a command In a file or device.
STDERR 2 Standard Error Redirect Error of a command In a file or device.

Let’s have a list of examples which show you how can we use these redirection

Redirect output of a command into a file

# command > output_file.txt

Append output of a command into a file.

If we continuously redirect output of a command into a file it will overwrite the existing content. If we want to append output use

# command >> output_file.txt

Redirect error of a command into a file

# command 2> error_file.txt

Note: If command don’t generate any error output will be nothing. In you want to check it’s working or not you can use a wrong command or incorrect syntax

Redirect output and error to different files

#command > output.txt 2>  error.txt

Redirect output and error to same file

# command > output.txt  2>&1

& is the syntax to redirect a stream to another file descriptor

Writing output to /dev/null.

In Linux or Unix /dev/null is a device file which discard any data written to it and send true signal that data is written.

If we want suppress warning or error messages during command and don’t want to write it on any file we can redirect it to /dev/null.

#command > /dev/null

If we check anything written in /dev/null

# cat /dev/null

And it will show nothing is written here.

Linux standard input

mail zolan@sector19.net < mail_body.txt

Combine standard input and standard output

#aspell < file.txt > error.txt

It will check grammar from file.txt as standard input and redirect on error.txt

tee command

tee command  read from standard input and write to standard output (screen) and files simultaneously

# command | tee output_file.txt

Redirect output and error and also display on screen

command1 2>&1 | tee log.txt

xargs command

xargs command read from standard input and parse it to another command. Let’s look it from some examples

ls /etc/*.ini | xargs grep php

search word “php” from all .ini files in /etc directory

FacebookTwitterGoogle+RSS