Home > Articles

Redirection and Pipes

📄 Contents

  1. Redirection and Pipes
  2. 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.

Redirection

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.

Herefiles

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.

Redirecting STDERR

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.

Practice Problems

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?

 

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020