When redirecting the output of a command to a file or piping it to another command, you might notice that the error messages are printed on the screen.

In Bash and other Linux shells, when a program is executed, it uses three standard I/O streams. Each stream is represented by a numeric file descriptor:

  • 0 - stdin, the standard input stream.
  • 1 - stdout, the standard output stream.
  • 2 - stderr, the standard error stream.

A file descriptor is just a number representing an open file.

The input stream provides information to the program, generally by typing in the keyboard.

The program output goes to the standard input stream and the error messages goes to the standard error stream. By default, both input and error streams are printed on the screen.

Redirecting Output

Redirection is a way to capture the output from a program and send it as input to another program or file.

Streams can be redirected using the n> operator, where n is the file descriptor number.

When n is omitted, it defaults to 1, the standard output stream. For example, the following two commands are the same; both will redirect the command output (stdout) to the file.

command > file
command 1> file

To redirect the standard error (stderr) use the 2> operator:

command 2> file

You can write both stderr and stdout to two separate files:

command 2> error.txt 1> output.txt

#bash #stderr #stdout

How to Redirect stderr to stdout in Bash
1.35 GEEK