Home > Articles

This chapter is from the book

Standard Output and Input

Course Objectives Covered

  1. Executing Commands at the Command Line (3036)

  2. Common Command Line Tasks (3036)

  3. Piping and Redirection (3036)

Standard output is where displays usually go—to your screen. When you give the following command

ls -F

a listing of the subdirectories and files beneath the current directory is displayed on your screen. The default location for standard output, therefore, is to your screen. If you do not want the results displayed on your screen, however, you can redirect them to another location, such as a file. Redirection of standard output is possible through the use of the greater-than sign (>). For example, to send the results to a file, the command would be

ls -F > myfile

The first order of business the shell undertakes when given this command is that it creates a file named myfile with a size of zero. It then allows the ls utility to run and places the output within the newly created file rather than on your screen. It is important to note the order of operations. Suppose you give a nonexistent command, such as this one:

ls -z > myfile

The file named myfile is still created with a size of zero that then stays at zero. The error appears on your screen, but this is after the file was created. This is also important because if you attempt to add more information to the file, the file will be overwritten first. To add more information, you must append to the file using two greater-than signs (>>):

ls -l >> myfile

This adds the new information to the end of the existing file and keeps the original contents intact. In some situations, you want a command to run but don't care at all about what the results are. For example, I might want a database to compile and need to run a utility for this to happen. I don't care about the messages generated—I just want the utility to run. When this is the case, you can send the results to nowhere by specifying /dev/null:

ls -F > /dev/null

The results are sent to this device, which is also known as the trashcan, never to be saved or displayed.

Standard input is typically the keyboard, or interpreted to be among the arguments given on the command line. You can, however, specify redirection of standard input using the less-than sign (<). Rarely is there ever a need for this, but it is available. For example

cat myfile

will give the same results as

cat < myfile

In the world of Linux, numerical values exist for these items as well. Standard input (abbreviated stdin) is 0, and standard output (abbreviated stdout) is 1. These numbers can be used with the redirection, but this is rarely done. An example would be

ls -F 1> myfile

NOTE

There can be no space between 1 and the > sign. If there is, the meaning is changed.

This example states that standard output is to be redirected to the file named myfile. The numbers are important for one reason only—because a third possibility exists as well. Standard error (abbreviated stderr) has a value of 2. For an example of standard error, think of the ls -z command you saw earlier. Even though the output was being sent to a file, the command was a nonexistent one and the error message appeared on the screen. The error could be sent to the file with the following command:

ls -z 2> myfile

The problem is that now the error will be sent there, but the output (in the absence of an error) will appear on the screen. To send both output and errors to the same file, the command becomes

ls -z > myfile 2>&1

This states that the output is to go to a file named myfile and further that standard error (2) is to go to the same location as standard output (1). Another alternative is to send errors to one location and output to another, like this:

ls -z > myfile 2>errors

Let's look at the order of operations here: The shell first creates two files (myfile and errors) with zero sizes (whether or not they existed before). If the command is successful, the output goes to myfile. If the command is unsuccessful, the errors go to errors. If these were truly log files, the only other modification might be to append versus zero each time the operation is run:

ls -z >> myfile 2>>errors

tee for Two

There is a miscellaneous utility that really stands alone and does not fit well with any section: tee. This utility, as the name implies, sends output in two directions. The default for most processes is to write their output to the screen. Using redirection (>), you can divert the output to a file, but what if you want to do both?

The tee utility allows output to go to the screen and to a file as well. The utility must always be followed by the name of the file which you want output to write to, for example

$ ps -f | tee example
UID    PID PPID C STIME TTY     TIME CMD
root   19605 19603 0 Aug10 pts/0  00:00:34 bash
root   30089 19605 0 Aug20 pts/0  00:00:00 vi fileone
root   30425 19605 0 Aug20 pts/0  00:00:00 paste -d
  fileone filetwo?
root   32040 19605 0 Aug22 pts/0  00:00:00 cat
root   1183 19605 0 Aug23 pts/0  00:00:00 awk -F:
  questions
root   30778 19605 0 14:25 pts/0  00:00:00 ps -f
$
$ cat example
UID    PID PPID C STIME TTY     TIME CMD
root   19605 19603 0 Aug10 pts/0  00:00:34 bash
root   30089 19605 0 Aug20 pts/0  00:00:00 vi fileone
root   30425 19605 0 Aug20 pts/0  00:00:00 paste -d
  fileone filetwo?
root   32040 19605 0 Aug22 pts/0  00:00:00 cat
root   1183 19605 0 Aug23 pts/0  00:00:00 awk -F:
  questions
root   30778 19605 0 14:25 pts/0  00:00:00 ps -f
$

As illustrated, the output appears on the screen, and is written to the file as well. This can be an extremely useful utility whenever a file is needed and you also want to view the output.

xargs

Another powerful utility to know is xargs. To understand the power of this utility, consider the find utility, which is limited in the results it can return to values within the filesystem structure. The only real text within the structure is the name of the entity and not the data itself (the pointer points to that). To illustrate, suppose the user edulaney put out a memo several months back on acceptable use of the company refrigerator in the break room. Since then, user edulaney has quit the company and several new employees (who would benefit from knowing this policy) have joined. You want to find the file and reprint it.

About the closest you can get to accomplishing this with find (and its results) would be

$ find / -user edulaney -type f -exec grep -i refrigerator {}
  \;
stored in the refrigerator overnight will be thrown out 
$

The type f option must be used or else errors will occur every time grep tries to search a directory. In this case, the line from the file is found, but there is no way of knowing what file it is contained in—rendering the result pretty much useless.

Enter the xargs utility: Analogous to a pipe, it feeds output from one command directly into another. Arguments coming into it are passed through with no changes, and turned into input into the next command. Thus, the command can be modified to

$ find / -user edulaney -type f | xargs grep -i refrigerator
/home/edulaney/fileone:stored in the refrigerator overnight will be thrown out 
$

The desired file is indicated, and can now be found and printed for the new employees.

Food for thought: If xargs works like a pipe, why wouldn't the following command suffice?

$ find / -user edulaney -type f | grep -i refrigerator

Answer: Because the grep operation would take place on the names of the files, not the content of the files. The xargs utility pipes the entire name (thus the contents) into the next command in succession (grep, in this case), not just the resulting filename.

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