Redirection and Pipes
Redirection and Pipes
This chapter is the heart of what the Unix mentality is all about. If you took everything else away from Unix but left redirection and pipes, you'd still be doing okay. These are the concepts from which Unix derives its strength and character, and attention paid now will be well rewarded later. I promise. This is a short chapter, but one that contains the ideas which have allowed Unix to flourish for decades while other systems have fallen by the wayside.
The material here is deceptively simple, in that none of these concepts are difficult or take any time to learn. The full power of Unix, however, lies in the informed application of these simple ideas. Practice these concepts until pipes and redirection are a reflex.
When I speak of redirection on Unix, I'm speaking of redirecting input and output of individual programs. Redirecting the input and output presupposes that there's a normal place from which data comes and a normal place to which it goes.
The Three Musketeers: STDIN, STDOUT, STDERR
And, in fact, this is the case. We could say that data normally goes from the terminal keyboard through the program and back out to the terminal's display. This does cover the typical case but is technically inaccurate: Data comes from STDIN and goes to STDOUT. STDIN is an abbreviation for standard input, and STDOUT is short for standard output.
Both STDIN and STDOUT can be considered as files: streams of bytes. STDIN is a stream being read by the program, and STDOUT is a stream of data being written by the program. Under normal circumstances, these point to the display and keyboard of the user's terminal. If I run cat without any filename on the command line, it reads its file from STDIN (normally the keyboard); cat always writes to STDOUT (normally the screen):
[ jon@frogbog thinkunix ]$ cat This is a test. This is a test. I'm typing this in one line at a time. I'm typing this in one line at a time. All right I've had enough. All right I've had enough. ^D [ jon@frogbog thinkunix ]$
As you can see, cat is designed to read text in from STDIN, one line at a time, and send it back to STDOUT. It stops reading its data when it reaches an end-of-file marker (EOF), which on standard Unix systems is represented by Ctrl+D.1 One more important stream is STDERR, which stands for standard error. This is where error messages go, as you'll often find that it's convenient to send errors somewhere different than STDOUT or that it's convenient to send errors the same place as STDOUT, when they'd tend to go elsewhere.
1. The more-or-less standard notation for control characters is to put a caret (^) in front of the key to be pressed.
Reading, Writing, Appending
Let's say Elvis wants to take a quick note by catting some text into a file: He's on the phone with Devo about a possible collaboration, and (like us) hasn't yet learned to use a text editor.
[ elvis@frogbog elvis]$ cat > devo.txt Country-Western "Whip It"? Flowerpot Hats: Jerry's House of Weird Stuff, Pierpont, MI Get Eddie V.H. to play guitar on new "Jailhouse Rock" album? ^D [ elvis@frogbog elvis]$
A single right-angle bracket (>) redirects STDOUT to a file; it even looks like an arrow pointing into a file. Not surprisingly, to redirect STDIN from a file requires a single left-angle bracket (<). Elvis now wants to see the names in west.txt in alphabetical order because he knows we need a convenient example for redirecting STDIN from a file:
[ elvis@frogbog elvis ]$ sort < west.txt Aristotle Heraclitus Plato Plotinus Socrates
All done, without a troublesome complaint from the system or a good reason why.
Appending to a file is easy, too: It's simply a pair of right-angle brackets without spaces (>>). With appending, Elvis can add to his reading list of Western philosophers:
[ elvis@frogbog elvis ]$ cat >> west.txt Kierkegaard Pascal Descartes Sartre ^D [ elvis@frogbog elvis ]$ cat west.txt Socrates Plato Aristotle Heraclitus Plotinus Kierkegaard Pascal Descartes Sartre
And the additional names have been added to the list.
Now that I've explained what >, <, and >> do, the obvious question is what << does. The answer is that it makes a herefile.
"A herefile, huh?" you say. "Never heard of it. What's it do, anyway?" That's a pretty good question. A herefile lets you input a whole bunch of lines of text to STDIN until you reach a predefined marker, like so:
[ elvis@frogbog elvis ]$ cat > newfile.txt << STOPHERE > This is a new file. I can put lots of text in it. > > I can put text in it all day, if that's what I want to do. > > Why would I do this? Because the system will let me. > > Of course, the system lets me do all sorts of stupid and worthless things. > > Garbage In, Garbage Out, I guess. > STOPHERE
It's immediately apparent that herefiles are more convenient than simply catting from STDIN. For one thing, they provide a nice-looking prompt at the beginning of each line, so that we know what to expect from them. For another thing, they avoid our having to remember that Ctrl+D is the EOF marker on Unix, though an EOF will still stop input even without the herefile keyword.2
2. Nothing works in all shells, but we're not trying to cover all shells: Our reference platform is the bash shell, though almost everything we do in this book works identically under ksh as well.
In this particular case, csh doesn't provide a prompt when entering text into a herefile, although the newer tcsh does. We discuss shells in more detail in Chapter 6.
Even so, herefiles don't really become important until I talk about shell scripts in Part II. Still, this is the logical place to talk about them in the book. And if I hadn't, you'd still be wondering precisely what << could possibly be used for.
Now that we've used <, >, <<, and >>, how might we redirect the standard error stream?
Unfortunately, the easy way to redirect STDERR doesn't work in the Bourne Shell, which is what almost everyone uses to write shell scripts. Additionally, the simple and perhaps logical answer would be to extend the existing syntax, using >>>, or to use another symbol, such as ], }, or ) that bears some visual resemblance to our original symbol. There are actually two ways to do this on Unix: the easy (but not quite so useful) way, and the hard (but more useful) way.
The Easy Way
The easy way to redirect STDERR is to redirect STDERR to STDOUT to a file. You can accomplish this by using >& to redirect to a file. Let's say that we were running a find to list all the files on the system, and we wanted to see the error messages inside our output, which we were sending to a file. We could use the command find / -name '*' -print >& ~/allfiles.txt. All the output, including find's error messages, would be in that file.
Unfortunately, if we wanted to redirect only the error messages but see find's normal output on the screen, we'd have some difficulty with that. To do that, we must redirect STDERR the hard way.
The Hard Way
The hard way to redirect STDERR relies on a feature present in only some Unix shells: numbered file handles. The Bourne, Korn, and Bash Shells all have this feature. The C Shell and tcsh don't. For more about shells, see Chapter 6. For now, simply type the following command to find out which shell you have:3
cat /etc/passwd|grep ^ username:|cut -d : -f 7
3. Assuming your site doesn't use NIS to keep track of accounts. NIS is beyond the scope of this book; however, you can get the NIS account list by typing ypcat passwd instead of cat /etc/passwd.
Replace username with your own username. That command should print a file and path name. If the program referenced is csh or tcsh, this section doesn't apply to you, unless you change your shell. If it's sh, ksh, or bash, it does.4 The fact that you can't redirect particular file handles with csh or tcsh leads many Unix experts to pronounce those shells "broken." I take no position on this other than to note that I don't cover those shells. Even if you run those shells and you're not willing to switch, this section is probably still worth reading, just for the theory.
4. This seems as good a point as any to point out that Unix shells have two names: their "real names" and the names of the commands that run the shells. The Bourne Shell is also known as sh, the Korn Shell is ksh, the Bourne Again Shell is bash, the C Shell is csh, and tcsh is tcsh.
A file handle is an abstract representation of a file. That is, when a computer program needs to access a file, it doesn't use the name of the file being accessed each time. Instead, the program creates a named file handle. Essentially, the programmer says "Whenever I talk about MY_OPEN_FILE, I'm really talking about /some/really/long/path/to/a/particular/file." This has a whole bunch of advantages for the programmer: first, she doesn't need to type that really long filename each time she wants to read or write from that file. Second, if the file changes its name or directory before the program is finished being written, there's less to change. Third, and more importantly, if the file changes its name or directory while the program is running, or if the program doesn't know the filename beforehand, it can still deal with it.
Most programming languages use names for file handles, but Unix shells use numbers. Names might be convenient, albeit longwinded, but it would be a lot trickier to figure out what part of the command line is a file handle and what part is not. Numbers make this part easy.
All redirection is actually done with numbered file handles (also known as file descriptors); most redirection commands simply have a default file descriptor. The generalized format is simply the file descriptor immediately to the left of the redirection command. STDIN is 0, STDOUT is 1, and STDERR is 2. When we run the command cat < ourfile.txt, we're really running cat 0< ourfile.txt. Similarly, when we run ls > whatever, what we're really doing is ls 1> whatever.
Therefore, if we want to direct only STDERR to a file in our previous example with find, we should find / -name '*' -print 2> errors.txt. This prints the normal output of find to the console while sending the errors to errors.txt.
This enables us to get even more complicated and send normal output to one file while getting rid of error messages entirely. find / -name '*' -print > find.txt 2> /dev/null sends the useful output from find to find.txt and sends all the error messages to the bit bucket.
1. cat /etc/passwd > something.txt. What is contained in something.txt after this command?
2. Using a redirection from a file, display the contents of /etc/group onscreen.
3. Through cat, redirect from /etc/group to something.txt.
4. Using cat, redirect input from /dev/null to a file named null.txt. What are the contents of null.txt after you've done this?
5. Assuming that no directory is named zip in your current directory, change your directory to zip, redirecting standard error to null.txt. (If your system gives you an error when you attempt this, feel free to rm null.txt and try again.) What are the contents of null.txt when this is done?
6. rm something.txt and, using a herefile, create a file named something.txt with the following text:This file is named something. Presumably, that means something should be in it. All I see here is a whole bunch of nothing. How can that possibly be?