Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Linux Error Redirection

  • Last Updated : 02 Dec, 2020

Redirection is a feature in Linux which can be used to change the standard input device (keyboard) or standard output device (screen) during the execution of a command. The basic process of any Linux command is that it takes an input and gives output but the standard/input and output can be changed using the redirection technique.

Error Redirection

There are mainly two types of output streams in Linux- standard output and standard error. The redirection operator (command > file) only redirects standard output and hence, the standard error is still displayed on the terminal. The default standard error is the screen. The standard error can also be redirected so that error messages do not clutter up the output of the program. ‘2’ denotes the stderr of a program.

2> stderr

‘2>’ redirects the error of an output to a file. The error messages are redirected and clean output is displayed. The Syntax of this operator is as follows:

command 2> file

Consider an example:

eccho "gfg" 2>file.txt
echo "gfg" 2>file.txt

There is no command as echo and hence error message will be displayed. But if 2>file.txt is used, then the error will be redirected to file.txt and no error is displayed on the screen. The cat command can be used to display the content of the file named file.txt which is the error message for the previous command. While executing the second command, gfg is displayed as the echo is a command in Linux to display. Hence, 2> does not redirect standard output.

2>stderr error redirection” srcset=”, ” sizes=”100vw” width=”445″></figure>
<p style=2>&1

When 2>& is used both standard error and standard output get redirected to the same file.

command > file 2>&

Consider an example:

eccho "gfg" >error.txt 2>&1
echo "gfg" >error.txt 2>&1

There is no command as echo and hence the error message is redirected to the file error.txt and no error is displayed. The second command echo “gfg” is correct but still, no output is displayed, as the standard output is also redirected to the file error.txt. The content of the file can be displayed after each step using the cat command.

Note: >& can be used to redirect both standard output and standard error, but it is not supported in all shells. sh and ksh do not support >& while bash and zsh support it.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!