By the end of this chapter, you should be able to:
Sometimes instead of simply displaying the output from a command to the terminal, it's useful to take the result output of a command and send it somewhere else. We call this "redirection" and it is denoted by
>. Let's start with a simple example using the
echo command is useful for displaying text to the terminal, but many times it is more useful to take that text and redirect it to a file. In Terminal, type the command
echo Hello World > hello.txt. Then, using the
cat command, let's see what we just did by typing
cat hello.txt. All we did here is take the text "Hello World" and instead of displaying it to the terminal, we sent it to a file called
Run the same command again but with slightly different text:
echo Hello Universe > hello.txt. Now cat the file again. Notice that your new text completely overwrote the old text: you should see that "Hello World" has been replaced by "Hello Universe." In other words, when you use
>, whatever text you're echoing into the file will completely overwrite any text that might already be in the file.
Maybe this is what you want, but maybe not. What if you're trying to append some text to the end of the file, rather than overwriting the text? In this case, use
>> instead. Try it out:
echo Hello World >> hello.txt. Now cat the file. You should see the following:
Hello Universe Hello World
One very common use case for redirection is to put small pieces of text in a file. Instead of opening a text editor, typing in some text, saving it and closing the file we can do this all in one step.
So far we have seen redirection using
>>. These arrows indicate redirection with standard output (take something and output it to something else). However, we can also use redirection with input as well using the
< arrow. Let's use a command called
sort, which sorts a file alphabetically. Imagine we have a file called
names.txt with the following names:
Bob Tom Jim Amy
If we want to sort this file, we can type
sort names.txt and it will output
Amy Bob Jim Tom
Now what if we want to take the contents of
names.txt, redirect that to the
sort command, and then send that output to a file called
sorted.txt? The redirection will look like this:
sort < names.txt > sorted.txt. This will now create a new file called
sorted.txt with the names sorted alphabetically!
This might seem a bit strange, but try typing these commands and see what information you can output and redirect. As we see right now, we are only using the
sort command, but what would happen if we wanted to use other commands along with sort? We would somehow need to connect each of these commands together. We connect these commands together through something called "pipes."
When you're ready, move on to Piping