Redirect output – using > symbol

Reading Time: 3 minutes

The > symbol is used to redirect the output of a command.

Redirecting stdout, stdin and stderr (> <)

Unless a command is piped into another the output normally goes to the standard output (stdout) which is normally the screen. The input is normally taken from standard input (stdin) which is normally the keyboard. To automate processes it is sometimes required to change this so that for example the output from a command is sent to a file or the printer, or the input to a command is taken from a file. This is done by redirecting the stdout and stdin streams.

Redirect command output (stdout) into a file

command > filename

Redirect error output (stderr) to a file

command 2> filename

It is also possible to write both stdout and the standard error stream to the same file. This can be achieved by redirecting the error data stream to the stdout data stream using 2>&1.

command >output.file 2>&1
output of grep command written into c112.txt file

Using a Temporary File

Sometimes the output would have to be redirected to a temporary file and then renamed to the required name. the sort from file1 cannot be directly stored in file1

sort file1 >/temp/tmp$$
mv /tmp/tmp$$ file1

The file ending in $$ will actually be created by the system with a unique number. This is useful for temporary files as it prevents you overwriting a temporary file in use by a different process.

The >> symbol

The single greater-than (>) can be replaced by double greater-than symbol (>>) if you would like the output to be appended to the file rather than to overwrite the file.

The tee command

Sometimes it is necessary for someone to monitor the output of the command but also for it to be duplicated into a file for logging purposes or to perform further processing on.

The tee command is used within a pipeline and whatever input it receives it both puts outputs into a file and forwards on the pipeline.

command | tee file1

The line above will take any output from the command and put a copy in file1 as well as sending it to the screen. This could be combined further by allowing the output to be further processed by another command. The tee command can be used any number of times in a pipeline. If you want tee to append to a file rather than overwrite it the -a option is used.

command1 | tee file1 | command2

For example, let us use cat, grep, tee and wc command to read the particular entry from user and store in a file and print line count.

$ cat result.txt | grep "iExpertify" | tee -a file2.txt | wc -l

This command select iExpertify and store them in file2.txt and print total number of lines matching iExpertify