Redirecting output streams in bash

  • avatar
  • 1.5K Views
  • 1 Like
  • 3 mins read

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 Linux stream is data traveling in a Linux shell from one process to another through a pipe, or from one file to another as a redirect. The input stream provides information to the program, generally using the keyboard. The program output goes to the standard output stream and error messages go to the standard error stream. By default, both streams are printed on the screen.

Redirecting the output

Redirection is a way to capture program output and send it as input to another program or file. Streams can be redirected using a special operator and file descriptor number. When the number is omitted, it defaults to 1, the standard output stream.

Following two commands do the same, both will redirect the command output to a file:

command > file
command 1> file

To redirect the standard error to a file use the operator below:

command 2> file

Error messages can be ignored redirecting them to /dev/null:

command 2> /dev/null

Both outputs can be used together:

command 2> error_file > output_file

Redirecting stderr to stdout

When redirecting the output of a command you might notice that error messages are printed on the screen. It's quite common to redirect stderr to stdout when saving to file so you have everything in one place.

To redirect stdout to a file and stderr to the current location of stdout use the following command:

command > file 2>&1

Note: redirection order is important as stderr can be wrongly redirected before defining desired stdout.

Another way to redirect stderr to stdout is using &> operator:

command &> file

In Bash &> has the same meaning as 2>&1.

Conclusion

Understanding redirections and file descriptors is very important when working with the command line. It's common to pipe processes redirecting outputs to other commands input or saving execution results to a file.

 Join Our Monthly Newsletter

Get the latest news and popular articles to your inbox every month

We never send SPAM nor unsolicited emails

0 Comments

Leave a Reply

Your email address will not be published.

Replying to the message: View original

Hey visitor! Unlock access to featured articles, remove ads and much more - it's free.