By default, information flows through the standard streams, but can be directed to other other locations. For example, we already saw that pipelines can be used to direct the stdout of one command to the stdin of another.
Redirection provides a mechanism through which standard streams can be combined and/or sent to another location.
For example, by default stdout is generally connected to the terminal, so that command output is displayed in the terminal. Suppose you want to save the command output to a file. One option would be to copy and paste it from the screen, but this is manual and error-prone. In this case, it makes more sense to redirect the command's output to a file.
Redirecting stdout
Redirecting stdout can be achieved using the following call signature:
{command} > {filename}
where command
is the command to execute, >
indicates that stdout should be redirected, and
filename
is the file to direct the output to. Let's see this in action:
First, repeat the simple "Hello World!" example and redirect the output to output.txt:
Note that unlike the original example the "Hello World!" text is not displayed in the terminal. Let's now cat the output file to see the content:
Note that if filename already exists, it will be overwritten, which may not be what is desired. As an alternative, you can append output to the specified file using the following call signature:
{command} >> {filename}
Let's execute that command:
then see the result:
Redirecting stdin
In a similar way, we can also redirect content to a command's stdin using the call signature:
{command} < {filename}
which is similar to the previous case, except the <
indicates that stdin should be
redirected.
As expected, executing this sorts this lines from output.txt, sorts them, and prints the result to the terminal:
Note that there are two additional variations of stdin redirection, which support here documents and strings, but will not be discussed here.
Multiple Redirection
Both stdin and stdout can be redirected by combining these two features into a single call, using the call signature:
{command} < {input file} > {output file}
As an example, let's now sort our file in reverse and redirect the result into a new file, reversed.txt:
Now we can display the new file contents:
which confirms that the command executed as expected.
Now that we have learned the basics of working with the command line, let's next look at how to combine multiple commands into shell scripts, which we can execute like a single, customized command.