Redirecting Streams

Posted by Daksh on Monday, February 7, 2022

Redirecting Streams

The shell has three inbuilt streams: stdin, stdout, and stderr.

stdin

Is the standard input stream. It is used to read input from the user. Represented by 0 in the shell. To write to this stream, we use < operator. e.g. cat < file.txt write the input, then press ctrl+d to end the input.

stdout

Is the standard output stream. It is used to write output to the user. Represented by 1 in the shell. To read from this stream, we use > operator. e.g. ls -l > file.txt write the output to the file.

stderr

Is the standard error stream. It is used to write error messages to the user. Represented by 2 in the shell. To read from this stream, we use 2> operator. To combine stderr and stdout. we use 2>&1 operator.

It may happen that an error occurs when you are outputting data to a text file. Note that the error will not correspond with the output stream. It will change to use the error stream, which is represented by two.

Example:

$ ls -l /imaginery_dir > error.txt
ls: cannot access '/imaginery_dir': No such file or directory

$ ls -l /imaginery_dir 2> error.txt
$ less error.txt
ls: cannot access '/imaginery_dir': No such file or directory

$ ls -l /imaginery_dir > error_output.txt 2>&1
$ less error_output.txt
ls: cannot access '/imaginery_dir': No such file or directory