Course


Input and output redirection

Learn how to use input-output redirections in Linux

Introduction

Linux system commands take input from your terminal and send the resulting output back to your terminal. A command normally reads its input from the standard input, which happens to be your terminal by default. Similarly, a command normally writes its output to standard output, which is again your terminal by default.

Redirection Commands

Following is a complete list of commands which you can use for redirection.

Command Description
pgm > file Output of pgm is redirected to file
pgm < file Program pgm reads its input from file
pgm >> file Output of pgm is appended to file
n > file Output from stream with descriptor n redirected to file
n >> file Output from stream with descriptor n appended to file
n >& m Merges output from stream n with stream m
n < & m Merges input from stream n with stream m
< < tag Standard input comes from here through next tag at the start of line
| Takes output from one program, or process, and sends it to another

Output Redirection

The output from a command normally intended for standard output can be easily diverted to a file instead. This capability is known as output redirection. If the notation > file is appended to any command that normally writes its output to standard output.

Example

Check the following who command which redirects the complete output of the command in the users file.

The above command will redirect the output the root users home folder file called users.txt.

Discard the output

Sometimes you will need to execute a command, but you don't want the output displayed on the screen. In such cases, you can discard the output by redirecting it to the file /dev/null.

To discard both output of a command and its error output, use standard redirection to redirect STDERR to STDOUT.

file descriptor 0is normally standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).

Input Redirection

Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file. The less-than character < is used to redirect the input of a command.

In the above command, we count the number of lines in the file by redirecting the standard input of the wc command from the file /etc/passwd.