Skip to content

Redirection

Redirection is often used in linux system. It is used to put output into other files or programs. There will not be an exercise for this section but redirection is important for most all tasks.

Buffers

Before we get started with redirection we need to understand buffers. In a terminal there are 2 main buffers these buffers are stdout and stderr. Output from a command that is not an error gets output to stdout. All error output will get sent out to stderr. In most terminals you can not tell the difference between stdout and stderr with your eyes. By default redirection only send stdout to the file or command.

pipe

The pipe redirection redirects the output of one command into the input of another command. The symbol to use pipe is |. This is used to chain multiple commands together. If you want to redirect both stderr and stdout on a pipe you do it with command 2>&1 | next_command. Below is some examples of commands do not worry about the individual commands you will learn those later.

pipe examples

ls -al | less  #this list files in a directory and sends them to the less command
ls -al 2>&1 | less #this does the same thing but also sends the errors

Create file

Often we want to create a file from the output of a command. We can do that with redirection. To redirect we use the > symbol. To do this we use a command like command > filename. If we want to do both stderr and stdout we use it like command > filename 2>&1. One other special condition. Some terminals have a setting called no clobber set. This would keep a file from overwriting an existing file. If you want to override that, you can use the >| symbol. See examples below

create examples

ls -al > filelist
ls -al > filelist 2>&1
ls -al >| filelist

Append file

This works much the same as the create file, but the symbol for this one is >>. This makes it so the file is not over written just added to. Clobber does not come into play on this one because you are not creating a file you are adding to. See examples below.

append examples

ls -al >> filelist
ls -al >> filelist 2>&1