1.7.1: Read User Input and Print to Output
one.7. Input and Output
The software field -- really, whatever scientific field -- tends to advance most rapidly and impressively on those few occasions when someone (i.east., not a committee) comes up with an thought that is small in concept even so enormous in its implications. The standard input and output scheme of Unix has to be on the curt list of such ideas, along with such classic innovations as the LISP linguistic communication, the relational data model, and object-oriented programming.
The Unix I/O scheme is based on two dazzlingly simple ideas. First, Unix file I/O takes the class of arbitrarily long sequences of characters (bytes). In dissimilarity, file systems of older vintage take more than complicated I/O schemes (e.thousand., "block," "record," "card paradigm," etc.). 2d, everything on the system that produces or accepts data is treated as a file; this includes hardware devices like disk drives and terminals. Older systems treated every device differently. Both of these ideas have made systems programmers' lives much more pleasant.
1.7.ane. Standard I/O
By convention, each Unix program has a unmarried fashion of accepting input called standard input, a single way of producing output called standard output, and a single way of producing fault messages chosen standard error output, usually shortened to standard error. Of grade, a program tin can take other input and output sources every bit well, equally nosotros will meet in Affiliate 7.
Standard I/O was the first scheme of its kind that was designed specifically for interactive users, rather than the older batch manner of use that usually involved decks of dial-cards. Since the Unix shell provides the user interface, it should come as no surprise that standard I/O was designed to fit in very neatly with the shell.
All shells handle standard I/O in basically the aforementioned way. Each program that you invoke has all iii standard I/O channels set to your terminal or workstation window, and so that standard input is your keyboard, and standard output and error are your screen or window. For example, the post utility prints messages to you on the standard output, and when you use information technology to send messages to other users, it accepts your input on the standard input. This ways that you lot view messages on your screen and type new ones in on your keyboard.
When necessary, you can redirect input and output to come up from or go to a file instead. If you desire to ship the contents of a preexisting file to someone equally mail, you redirect mail'due south standard input and then that information technology reads from that file instead of your keyboard.
Y'all can as well hook upward programs into a pipeline, in which the standard output of one program feeds directly into the standard input of another; for example, you could feed mail output straight to the lp programme and so that messages are printed instead of shown on the screen.
This makes it possible to use Unix utilities equally edifice blocks for bigger programs. Many Unix utility programs are meant to be used in this way: they each perform a specific type of filtering operation on input text. Although this isn't a textbook on Unix utilities, they are essential to productive shell utilize. The more popular filtering utilities are listed in Tabular array 1-5.
Table 1-v. Pop Unix data filtering utilities
| Utility | Purpose |
|---|---|
| cat | Copy input to output |
| grep | Search for strings in the input |
| sort | Sort lines in the input |
| cut | Extract columns from input |
| sed | Perform editing operations on input |
| tr | Interpret characters in the input to other characters |
You may have used some of these before and noticed that they take names of input files as arguments and produce output on standard output. You may not know, all the same, that all of them (and most other Unix utilities) have input from standard input if y'all omit the argument.[xiii]
[xiii] If a particular Unix utility doesn't accept standard input when you lot go out out the filename argument, endeavor using - every bit the argument. This is a common, although not universal, convention.
For example, the near basic utility is cat, which but copies its input to its output. If y'all type cat with a filename statement, it will impress out the contents of that file on your screen. But if you invoke it with no arguments, it volition read standard input and copy it to standard output. Try it: cat will wait for you to blazon a line of text; when you lot blazon ENTER, cat volition parrot the text back at you. To stop the process, striking CTRL-D at the beginning of a line (see below for what this grapheme means). You lot will see ^D when you type CTRL-D. Hither's what this should look like:
$ true cat Here is a line of text. Here is a line of text. This is another line of text. This is another line of text. ^D $
1.7.2. I/O Redirection
cat is actually short for "catenate," i.e., link together. Information technology accepts multiple filename arguments and copies them to the standard output. Simply let'due south pretend, for the moment, that cat and other utilities don't take filename arguments and accept only standard input. Every bit we said higher up, the shell lets you redirect standard input so that it comes from a file. The notation control < filename does this; information technology sets things upwardly so that command takes standard input from a file instead of from a terminal.
For instance, if you have a file called fred that contains some text, then cat < fred will print fred's contents out onto your terminal. sort < fred will sort the lines in the fred file and impress the effect on your terminal (call up: we're pretending that utilities don't take filename arguments).
Similarly, command > filename causes command's standard output to exist redirected to the named file. The classic "canonical" example of this is appointment > now: the date command prints the current engagement and time on the standard output; the higher up control saves it in a file called now.
Input and output redirectors can be combined. For instance, the cp control is normally used to copy files; if for some reason information technology didn't exist or was broken, you could utilise true cat in this way:
cat < file1 > file2
This would exist similar to cp file1 file2.
As a mnemonic device, think of < and > as "information funnels." Information goes into the large cease and comes out the small end.
When used interactively, the Korn beat lets y'all utilize a shell wildcard afterwards an I/O redirection operator. If the pattern matches exactly i file, that file is used for I/O redirection. Otherwise, the pattern is left unchanged, and the vanquish attempts to open up a file whose name is exactly what you typed. In addition, it is invalid to endeavor a redirection with the null string as the filename (such as might happen when using the value of a variable, and the variable happens to be empty).
Finally, it is tempting to employ the same file for both input and output:
sort < myfile > myfile Sort myfile in place? No!
This does non work! The shell truncates myfile when opening information technology for output, and there won't exist whatsoever data at that place for sort to process when information technology runs.
1.7.3. Pipelines
It is besides possible to redirect the output of i command into the standard input of another running command instead of a file. The construct that does this is called the pipe, notated as |. A control line that includes two or more commands connected with pipes is called a pipeline.
Pipes are very often used with the more control, which works just similar cat except that it prints its output screen past screen, pausing for the user to type Infinite (next screen), ENTER (next line), or other commands. If y'all're in a directory with a large number of files and you lot want to encounter details near them, ls -50 | more will give y'all a detailed listing a screen at a fourth dimension.
Pipelines can get very complex (run into, for example, the lsd office in Chapter 4 or the pipeline version of the C compiler driver in Chapter 7); they can also be combined with other I/O redirectors. To run into a sorted list of the file fred a screen at a time, type sort < fred | more. To print it instead of viewing it on your concluding, type sort < fred | lp.
Here'due south a more complicated example. The file /etc/passwd stores information virtually users' accounts on a Unix arrangement. Each line in the file contains a user's login name, user ID number, encrypted password, home directory, login vanquish, and other info. The first field of each line is the login name; fields are separated by colons (:). A sample line might look similar this:
billr:5Ae40BGR/tePk:284:93:Bill Rosenblatt:/home/billr:/bin/ksh
To get a sorted list of all users on the system, type:
cut -d: -f1 < /etc/passwd | sort
(Actually, yous can omit the <, since cutting accepts input filename arguments.) The cut command extracts the first field (-f1), where fields are separated by colons (-d:), from the input. The entire pipeline prints a list that looks like this:
al billr bob chris dave
ed frank ...
If you want to send the list directly to the printer (instead of your screen), y'all can extend the pipeline like this:
cut -d: -f1 < /etc/passwd | sort | lp
Now you should run across how I/O redirection and pipelines support the Unix building block philosophy. The notation is extremely terse and powerful. Simply as important, the pipe concept eliminates the need for messy temporary files to shop output of commands before information technology is fed into other commands.
For instance, to practice the same sort of affair as the above command line on other operating systems (assuming that equivalent utilities were bachelor), you would need three commands. On Compaq's OpenVMS organization, they might look like this:
$ cut [etc]passwd /d=":" /f=ane /out=temp1 $ sort temp1 /out=temp2 $ impress temp2
Afterward sufficient practice, y'all volition find yourself routinely typing in powerful command pipelines that exercise in i line what in other operating systems would require several commands (and temporary files) to accomplish.
Copyright © 2003 O'Reilly & Assembly. All rights reserved.
kernanthipstrealm1972.blogspot.com
Source: https://docstore.mik.ua/orelly/unix3/korn/ch01_07.htm
0 Response to "1.7.1: Read User Input and Print to Output"
Post a Comment