Bash STDIN, STDOUT and STDERR explained


Example

Commands have one input (STDIN) and two kinds of outputs, standard output (STDOUT) and standard error (STDERR).

For example:

STDIN

root@server~# read
Type some text here

Standard input is used to provide input to a program. (Here we're using the read builtin to read a line from STDIN.)

STDOUT

root@server~# ls file
file

Standard output is generally used for "normal" output from a command. For example, ls lists files, so the files are sent to STDOUT.

STDERR

root@server~# ls anotherfile
ls: cannot access 'anotherfile': No such file or directory

Standard error is (as the name implies) used for error messages. Because this message is not a list of files, it is sent to STDERR.

STDIN, STDOUT and STDERR are the three standard streams. They are identified to the shell by a number rather than a name:

0 = Standard in
1 = Standard out
2 = Standard error

By default, STDIN is attached to the keyboard, and both STDOUT and STDERR appear in the terminal. However, we can redirect either STDOUT or STDERR to whatever we need. For example, let's say that you only need the standard out and all error messages printed on standard error should be suppressed. That's when we use the descriptors 1 and 2.

Redirecting STDERR to /dev/null
Taking the previous example,

root@server~# ls anotherfile 2>/dev/null
root@server~#

In this case, if there is any STDERR, it will be redirected to /dev/null (a special file which ignores anything put into it), so you won't get any error output on the shell.