Using Redirection

In addition to supporting pipes, Ubuntu allows you to redirect output using the > and < symbols. Using the first, you can, for example, send the output from a program directly to a file, whereas the second accepts input from a program.

The following command creates a file called files.txt in your home folder containing the output from ls -al:

ls -al > ~/files.txt

If files.txt already exists, it will be overwritten; otherwise, it will be created.

When you issue that command, you won’t see anything on the screen, because the output that would have been displayed has been redirected to a file. But you can verify that the command worked by entering the following, which displays the file’s contents:

cat ~/files.txt

The result of issuing this command will look something like Figure 7-15.

But what if you want to know which files and folders were created first? The answer would be to sort them by column 6, and you could use this command to do it:

ls -al | sort -k6 > ~/files.txt

If you need to keep the file sorted alphabetically but still wish to sometimes view the lines in date order, you can issue the following command on it instead:

sort -k6 < ~/files.txt

This opens up files.txt, reads it in, and passes its contents to the command immediately preceding the < symbol.

You could even extend that to use the less command by adding the | operator:

sort -k6 < ~/files.txt | less

This works because the > and < operators work on files and devices, whereas the | operator creates pipes between commands. Therefore, sort -k6 < ~/files.txt is seen as a complete command in its own right, the output of which can be displayed or, as in this case, piped to another command.

You should now see that a pipe is the equivalent of combining two separate redirection commands. For example, take a look at the following simple command, which pages the output from a file listing:

ls -al | more

This is actually equivalent to these two lines:

ls -al > tempfile
more < tempfile

Actually, to make these commands fully identical in action, you should also add the following command afterward to remove the temporary file:

rm tempfile

So, all told, each pipe can represent the equivalent of three separate commands.

You can also append to an existing file by stringing two > symbols together, like this:

ls -al >> ~/files.txt

If files.txt already exists, the output is appended to the end of it; otherwise, the file is created first.