Now that we have a handle on what standard input and standard output are, it's time to expand a little.
Redirection means causing the shell to change what it considers standard input or where the standard output is going.
We used cat before to demonstrate the idea behind standard input and standard output. Now, let's use cat to see how standard output can be redirected.
To redirect standard output, we'll use the > symbol. Placing > after the cat command (or after any utility or application that writes to standard output) will direct its output to the filename following the symbol.
Let's try it. In an Xterm window type:
[newuser@localhost newuser]$ cat > sneakers.txt buy some sneakers then go to the coffee shop then buy some coffee |
Now press Enter to go to an empty line, and use the Ctrl-D keys to quit cat.
Notice the difference (see Figure 13-12)? For one thing, there are no double entries. That's because the standard output from cat was redirected. That redirection was to a brand new file you made called sneakers.txt.
You can find the file in your login directory (may we suggest using ls if you want to see it listed?).
You can even use cat to read the file, by typing:
cat sneakers.txt |
at the prompt.
Don't overwrite files | |
---|---|
Be careful when you redirect the output to a file, because you can easily overwrite an existing file! Make sure the name of the file you're creating doesn't match the name of a pre-existing file, unless you want to replace it. |
Let's use output redirection for another file and call it home.txt.
[newuser@localhost newuser]$ cat > home.txt bring the coffee home take off shoes put on sneakers make some coffee relax! |
Now, on an empty line, use the Ctrl-D keys again to quit cat.
We can check the file again by typing:
cat home.txt |
at the prompt.
Let's use cat again to join home.txt with sneakers.txt and redirect the output of both files to a brand new file we'll call saturday (you'll find an example in Figure 13-13).
[newuser@localhost newuser]$ cat sneakers.txt home.txt > saturday |
That's it.
Now it's time to check our handiwork. Type:
[newuser@localhost newuser]$ cat saturday |
and you should see something like this:
[newuser @localhost newuser]$ cat saturday buy some sneakers then go to the coffee shop then buy some coffee bring the coffee home take off shoes put on sneakers make some coffee relax! [newuser @localhost newuser]$ |
You can see that cat has added home.txt where sneakers.txt left off.
Combining files with cat | |
---|---|
Creating and combining short files with cat can be a convenient alternative to using a text editor like Pico. |
Summary | |
---|---|
By using the output redirection symbol (>) you can send the output to a file instead of the terminal. The cat utility can be used along with output redirection to join files together into a single, unified file with one filename. |