Documente Academic
Documente Profesional
Documente Cultură
UNIX
Programming
Environment
Brian W. Kernighan
R o b Pike
Bell Laboratories
Murray Hill, New Jersey
PRENTICE-HALL, INC.
Englewood Cliffs, New Jersey 07632
Prentice-Hall S o f t w a r e Series
Brian
W. K ernighan,
Advisor
19
ISBN
ISBN
18
17
16
15
14
Q-13-^37^-2
- 1 3 - e J 3 7 b f l l - X -CPBK>
P R E N T I C E - H A L L I N T E R N A T I O N A L , I N C . , London
P R E N T I C E - H A L L O F A U S T R A L I A PTY. L I M I T E D , Sydney
E D I T O R A P R E N T I C E - H A L L DO B R A S I L , LTDA., Rio de Janeiro
P R E N T I C E - H A L L C A N A D A INC., Toronto
P R E N T I C E - H A L L O F I N D I A PRIVATE L I M I T E D , NewDelhi
P R E N T I C E - H A L L O F J A P A N , I N C . , Tokyo
P R E N T I C E - H A L L O F S O U T H E A S T A S I A P T E . LTD., Singapore
W H I T E H A L L B O O K S L I M I T E D , Wellington, New Zea/and
CONTENTS
Preface
1.
UNIX
1.1
1.2
1.3
1.4
1.5
vii
for Beginners
Getting started
Day-to-day use: files and common commands
More about files: directories
The shell
The rest of the UNIX system
1
2
11
21
26
38
2.
41
41
46
48
52
57
63
65
3.
71
71
74
80
82
86
88
92
94
97
99
4.
Filters
4.1 The g r e p family
4.2 Other filters
101
102
106
iii
iv
CONTENTS
108
114
130
5.
Shell Programming
5.1 Customizing the c a l command
5.2 Which command is w h i c h ?
5.3 w h i l e and u n t i l loops: watching for things
5.4 Traps: catching interrupts
5.5 Replacing a file: o v e r w r i t e
5.6 z a p : killing processes by ame
5.7 The p i c k command: blanks vs. arguments
5.8 The n e w s command: community service messages
5.9 g e t and p u t : tracking file changes
5.10 A look back
133
133
138
144
150
152
156
159
162
165
169
6.
171
172
174
176
180
186
187
190
192
199
7.
UNIX
7.1
7.2
7.3
7.4
7.5
8.
System Calis
Low-level I/O
File system: directories
File system: inodes
Processes
Signis and interrupts
Program Development
8.1 Stage 1: A four-function calculator
8.2 Stage 2: Variables and error recovery
8.3 Stage 3: Arbitrary variable ames; built-in functions
8.4 Stage 4: Compilation into a machine
8.5 Stage 5: Control flow and relational operators
8.6 Stage 6: Functions and procedures; input/output
8.7 Performance evaluation
8.8 A look back
201
201
208
214
220
225
233
234
242
245
258
266
273
284
286
COlNlblNIb
Document Preparation
9.1 The ms macro package
9.2 The t r o f f level
9.3 The t b l and e q n preprocessors
9.4 The manual page
9.5 Other document preparation tools
289
290
297
301
308
313
Epilog
315
319
329
335
Index
349
iv
CONTENTS
108
114
130
5.
Shell Programming
5.1 Customizing the c a l command
5.2 Which command is w h i c h ?
5.3 w h i l e and u n t i l loops: watching for things
5.4 Traps: catching interrupts
5.5 Replacing a file: o v e r w r i t e
5.6 z a p : killing processes by ame
5.7 The p i c k command: blanks vs. arguments
5.8 The n e w s command: community service messages
5.9 g e t and p u t : tracking file changes
5.10 A look back
133
133
138
144
150
152
156
159
162
165
169
6.
171
172
174
176
180
186
187
190
192
199
7.
UNIX
7.1
7.2
7.3
7.4
7.5
8.
System Calis
Low-level I/O
File system: directories
File system: inodes
Processes
Signis and interrupts
Program Development
8.1 Stage 1: A four-function calculator
8.2 Stage 2: Variables and error recovery
8.3 Stage 3: Arbitrary variable ames; built-in functions
8.4 Stage 4: Compilation into a machine
8.5 Stage 5: Control flow and relational operators
8.6 Stage 6: Functions and procedures; input/output
8.7 Performance evaluation
8.8 A look back
201
201
208
214
220
225
233
234
242
245
258
266
273
284
286
CONTENTS
Document Preparation
9.1 The ms macro package
9.2 The t r o f f level
9.3 The t b l and e q n preprocessors
9.4 The manual page
9.5 Other document preparation tools
289
290
297
301
308
313
Epitog
315
319
329
335
Index
349
PREFACE
"The number of UNIX installations has grown to 10, with more expected."
(The UNIX Programmer's Manual, 2nd Edition, June, 1972.)
The UNixt operating system started on a cast-off DEC PDP-7 at Bell Laboratories in 1969. Ken Thompson, with ideas and support from Rudd Canaday,
Doug Mcllroy, Joe Ossanna, and Dennis Ritchie, wrote a small generalpurpose time-sharing system comfortable enough to attract enthusiastic users
and eventually enough credibility for the purchase of a larger machine a
PDP-11/20. One of the early users was Ritchie, who helped move the system
to the PDP-11 in 1970. Ritchie also designed and wrote a compiler for the C
programming language. In 1973, Ritchie and Thompson rewrote the UNIX kernel in C, breaking from the tradition that system software is written in assembly language. With that rewrite, the system became essentially what it is
today.
Around 1974 it was licensed to universities "for educational purposes" and
a few years later became available for commercial use. During this time, UNIX
systems prospered at Bell Labs, finding their way into laboratories, software
development projects, word processing centers, and operations support systems
in telephone companies. Since then, it has spread world-wide, with tens of
thousands of systems installed, from microcomputers to the largest mainframes.
What makes the UNIX system so successful? We can discern several reasons. First, because it is written in C, it is portable UNIX systems run on a
range of computers from microprocessors to the largest mainframes; this is a
strong commercial advantage. Second, the source code is available and written
in a high-level language, which makes the system easy to adapt to particular
requirements. Finally, and most important, it is a good operating system,
t UNIX is a trademark of Bell Laboratories, "UNIX" is not an acronym, but a weak pun on MULTICS, the operating system that Thompson and Ritchie worked on before UNIX.
vii
Vii
PRF.FACE
PREFACE
The command interpreter, or shell, is a fundamental tool, not only for running programs, but also for writing them. Chapter 3 describes how to use the
shell for your own purposes: creating new commands, command arguments,
shell variables, elementary control flow, and input-output redirection.
Chapter 4 is about filters: programs that perform some simple transformation on data as it flows through them. The first section deals with the g r e p
pattern-searching command and its relatives; the next discusses a few of the
more common filters such as sort; and the rest of the chapter is devoted to
two general-purpose data transforming programs called s e d and awk. s e d is
a stream editor, a program for making editing changes on a stream of data as
it flows by. awk is a programming language for simple information retrieval
and report generation tasks. It's often possible to avoid conventional programming entirely by using these programs, sometimes in cooperation with the
shell.
Chapter 5 discusses how to use the shell for writing programs that will
stand up to use by other people. Topics include more advanced control flow
and variables, traps and interrupt handling. The examples in this chapter
make considerable use of s e d and awk as well as the shell.
Eventually one reaches the limits of what can be done with the shell and
other programs that already exist. Chapter 6 talks about writing new programs
using the standard I/O library. The programs are written in C, which the
reader is assumed to know, or at least be learning concurrently. We try to
show sensible strategies for designing and organizing new programs, how to
build them in manageable stages, and how to make use of tools that already
exist.
Chapter 7 deals with the system calis, the foundation under all the other
layers of software. The topics include input-output, file creation, error processing, directories, inodes, processes, and signis.
Chapter 8 talks about program development tools: y a c c , a parsergenerator; m a k e , which controls the process of compiling a big program; and
l e x , which generates lexical analyzers. The exposition is based on the
development of a large program, a C-like programmable calculator.
Chapter 9 discusses the document preparation tools, illustrating them with a
user-level description and a manual page for the calculator of Chapter 8. It
can be read independently of the other chapters.
Appendix 1 summarizes the standard editor e d . Although many readers
will prefer some other editor for daily use, ed is universally available, efficient
and effective. Its regular expressions are the heart of other programs like
g r e p and s e d , and for that reason alone it is worth learning.
Appendix 2 contains the reference manual for the calculator language of
Chapter 8.
Appendix 3 is a listing of the final versin of the calculator program,
presenting the code all in one place for convenient reading.
PREFACE
Some practical matters. First, the UNIX system has become very popular,
and there are a number of versions in wide use. For example, the 7th Edition
comes from the original source of the UNIX system, the Computing Science
Research Center at Bell Labs. System III and System V are the official Bell
Labs-supported versions. The University of California at Berkeley distributes
systems derived from the 7th Edition, usually known as UCB 4.xBSD. In
addition, there are numerous variants, particularly on small computers, that
are derived from the 7th Edition.
We have tried to cope with this diversity by sticking closely to those aspects
that are likely to be the same everywhere. Although the lessons that we want
to teach are independent of any particular versin, for specific details we have
chosen to present things as they were in the 7th Edition, since it forms the
basis of most of the UNIX systems in widespread use. We have also run the
examples on Bell Labs' System V and on Berkeley 4.1BSD; only trivial changes
were required, and only in a few examples. Regardless of the versin your
machine runs, the differences you find should be minor.
Second, although there is a lot of material in this book, it is not a reference
manual. We feel it is more important to teach an approach and a style of use
than just details. The UNIX Programmer's Manual is the standard source of
information. You will need it to resolve points that we did not cover, or to
determine how your system differs from ours.
Third, we believe that the best way to learn something is by doing it. This
book should be read at a terminal, so that you can experiment, verify or contradict what we say, explore the limits and the variations. Read a bit, try it
out, then come back and read some more.
We believe that the UNIX system, though certainly not perfect, is a marvelous computing environment. We hope that reading this book will help you
to reach that conclusin too.
We are grateful to many people for constructive comments and criticisms,
and for their help in improving our code. In particular, Jon Bentley, John
Linderman, Doug Mcllroy, and Peter Weinberger read mltiple drafts with
great care. We are indebted to Al Aho, Ed Bradford, Bob Flandrena, Dave
Hanson, Ron Hardin, Marin Harris, Gerard Holzmann, Steve Johnson, Nico
Lomuto, Bob Martin, Larry Rosler, Chris Van Wyk, and Jim Weythman for
their comments on the first draft. We also thank Mike Bianchi, Elizabeth
Bimmler, Joe Carfagno, Don Crter, Tom De Marco, Tom Duff, David Gay,
Steve Mahaney, Ron Pinter, Dennis Ritchie, Ed Sitar, Ken Thompson, Mike
Tilson, Paul Tukey, and Larry Wehr for valuable suggestions.
Brian
Kernighan
Rob Pike
CHAPTER
1:
UNIX F O R ESEGINNERS
What is " U N I X " ? In the narrowest sense, it is a time-sharing operating system kernel: a program that controls the resources of a computer and allocates
them among its users. It lets users run their programs; it controls the peripheral devices (discs, terminis, printers, and the like) connected to the
machine; and it provides a file system that manages the long-term storage of
information such as programs, data, and documents.
In a broader sense, " U N I X " is often taken to include not only the kernel,
but also essential programs like compilers, editors, command languages, programs for copying and printing files, and so on.
Still more broadly, "UNIX" may even include programs developed by you or
other users to be run on your system, such as tools for document preparation,
routines for statistical analysis, and graphics packages.
Which of these uses of the ame " U N I X " is correct depends on which level
of the system you are considering. When we use " U N I X " in the rest of this
book, context should indcate which meaning is implied.
The U N I X system sometimes looks more difficult than it is it's hard for a
newcomer to know how to make the best use of the facilities available. But
fortunately it's not hard to get started knowledge of only a few programs
should get you off the ground. This chapter is meant to help you to start using
the system as quickly as possible. It's an overview, not a manual; we'll cover
most of the material again in more detail in later chapters. We'll talk about
these major areas:
basics logging in and out, simple commands, correcting typing mistakes,
mail, inter-terminal communication.
day-to-day use files and the file system, printing files, directories,
commonly-used commands.
the command interpreter or shell filename shorthands, redirecting input
and output, pipes, setting erase and kill characters, and defining your own
search path for commands.
If you've used a UNIX system before, most of this chapter should be familiar ;
you might want to skip straight to Chapter 2.
1
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 1
about terminis
and typing
CHAPTER 1
UNIX FOR B E G I N N E R S
advanees the cursor to the next tab stop, much as on a regular typewriter. Tab
stops on U N I X systems are eight spaces apart. Both the backspace and tab characters have their own keys on most terminis.
T w o other keys have special meaning: DELETE, sometimes called RUBOUT
or some abbreviation, and BREAK, sometimes called INTERRUPT. On most
UNIX systems, the DELETE key stops a program immediately, without waiting
for it to finish. On some systems, ctl-c provides this service. A n d on some
systems, depending on how the terminis are connected, BREAK is a synonym
f o r DELETE or ctl-c.
A Session with UNIX
Let's begin with an annotated dialog between you and your U N I X system.
T h r o u g h o u t the examples in this book, what you type is printed in slanted
letters,
computer responses are i n t y p e w r i t e r - s t y l e c h a r a c t e r s , and
e x p l a n a t i o n s a r e in italics.
Establish a connection: dial a phone or turn on a switch as necessary.
Your system should say
login: you
Type your rame, then press RETURN
Password:
Your password won't be echoed as you type it
You have mail.
There's mail to be read after you log in
$
The system is now reay for your commands
$
Press RETURN a couple of times
$ date
What's the date and time?
Sun Sep 25 23:02:57 EDT 1983
$ who
Who's using the machine?
ttyO
Sep 25 13:: 59
jlb
tty2
Sep 25 23:: 01
you
tty4
Sep 25 19:: 03
mary
Sep 25 19:: 22
doug
tty5
Sep 25 17:: 17
egb
tty7
Sep 25 20:: 48
tty8
bob
Read your f
$ mail
From dougr Sun Sep 25 20:: 53 EDT 1983
give me a cali sometime monday
?
RETURN moves on to the next message
From mary Sun Sep 25 19:07 EDT 1983
Next message
Lunch at noon tomorrow?
? d
$
$ mail mary
lunch
at 12 is
ctl-d
$
CHAPTER I
some work too. The rest of this section will discuss the session above, plus
other programs that make it possible to do useful things.
Logging in
You must have a login ame and password, which you can get from your
system administrator. The UNIX system is capable of dealing with a wide
variety of terminis, but it is strongly oriented towards devices with lower case;
case distinctions matter! If your terminal produces only upper case (like some
video and portable terminis), life will be so difficult that you should look for
another terminal.
Be sure the switches are set appropriately on your device: upper and lower
case, full dplex, and any other settings that local experts advise, such as the
speed, or baud rate. Establish a connection using whatever magic is needed
for your terminal; this may involve dialing a telephone or merely flipping a
switch. In either case, the system should type
login:
If it types garbage, you may be at the wrong speed; check the speed setting and
other switches. If that fails, press the BREAK or INTERRUPT key a few times,
slowly. If nothing produces a login message, you will have to get help.
When you get the l o g i n : message, type your login ame in lower case.
Follow it by pressing RETURN. If a password is required, you will be asked
for it, and printing will be turned off while you type it.
The culmination of your login efforts is a prompt, usually a single character, indicating that the system is ready to accept commands from you. The
prompt is most likely to be a dollar sign $ or a percent sign %, but you can
change it to anything you like; we'll show you how a little later. T h e prompt is
actually printed by a program called the command interpreter or shell, which is
your main interface to the system.
There may be a message of the day just before the prompt, or a notification
that you have mail. You may also be asked what kind of terminal you are
using; your answer helps the system to use any special properties the terminal
might have.
Typing commands
Once you receive the prompt, you can type commands, which are requests
that the system do something. We will use program as a synonym for command. When you see the prompt (let's assume it's $), type d a t e and press
RETURN. T h e system should reply with the date and time, then print another
prompt, so the whole transaction will look like this on your terminal:
$ date
Mon Sep 26 12:20:57 EDT 1983
CHAPTER 1
UNIX FOR B E G I N N E R S
ignored, press RETURN; something should happen. RETURN won't be mentioned again, but you need it at the end of every line.
The next command to try is who, which tells you everyone who is currently
logged in:
$ who
rlm
pjw
gerard
mark
you
$
ttyO
tty4
tty7
tty9
ttya
Sep
Sep
Sep
Sep
Sep
26
26
26
26
26
11 : 17
11 : 30
10 : 27
07 : 59
12 : 20
The first column is the user ame. The second is the system's ame for the
connection being used ( " t t y " stands for "teletype," an archaic synonym for
"terminal"). The rest tells when the user logged on. You might also try
$ who
you
$
am i
ttya
Sep 26 12:20
If you make a mistake typing the ame of a command, and refer to a nonexistent command, you will be told that no command of that ame can be
found:
$ whom
whom: not found
$
-tabs
and the system will convert tabs into the right number of spaces. If your terminal does have computer-settable tab stops, the command t a b s will set them
correctly for you. (You may actually have to say
$ tabs
terminal-type
CHAPTER 1
Mistak.es in typing
If you make a typing mistake, and see it before you have pressed RETURN,
there are two ways to recover: erase characters one at a time or kill the whole
line and re-type it.
If you type the line kill character, by default an at-sign @, it causes the
whole line to be discarded, just as if you'd never typed it, and starts you over
on a new line:
$ ddtae(
Completely botched; start over
date
on a new line
Mon Sep 26 12:23:39 EDT 1983
$
The sharp character # erases the last character typed; each # erases one
more character, back to the beginning of the line (but not beyond). So if you
type badly, you can correct as you go:
$ dd#atte##e
Fix it as you go
Mon Sep 26 12:24:02 EDT 1983
$
The particular erase and line kill characters are very system dependent. On
many systems (including the one we use), the erase character has been changed
to backspace, which works nicely on video terminis. You can quickly check
which is the case on your system:
$ dateedatee*-: not found
$ datee#
Mon Sep 26 12:26:08 EDT 1983
$
Try *It'snot*Try #
It is #
(We printed the backspace as - so you can see it.) Another common choice is
ctl-\i for line kill.
We will use the sharp as the erase character for the rest of this section
because it's visible, but make the mental adjustment if your system is different.
Later on, in "tailoring the environment," we will tell you how to set the erase
and line kill characters to whatever you like, once and for all.
What if you must enter an erase or line kill character as part of the text? If
you precede either # or @ by a backslash \, it loses its special meaning. So to
enter a # or @, type \# or \@. The system may advance the terminal's cursor
to the next line after your @, even if it was preceded by a backslash. Don't
worry the at-sign has been recorded.
The backslash, sometimes called the escape character, is used extensively to
indcate that the following character is in some way special. To erase a
backslash, you have to type two erase characters: \ # # . Do you see why?
The characters you type are examined and interpreted by a sequence of programs before they reach their destination, and exactly how they are interpreted
CHAPTER 1
UNIX FOR B E G I N N E R S
depends not only on where they end up but how they got there.
Every character you type is immediately echoed to the terminal, unless
echoing is turned off, which is rare. Until you press RETURN, the characters
are held temporarily by the kernel, so typing mistakes can be corrected with
the erase and line kill characters. When an erase or line kill character is preceded by a backslash, the kernel discards the backslash and holds the following
character without interpretation.
When you press RETURN, the characters being held are sent to the program that is reading from the terminal. That program may in turn interpret
the characters in special ways; for example, the shell turns off any special
interpretation of a character if it is preceded by a backslash. We'll come back
to this in Chapter 3. For now, you should remember that the kernel processes
erase and line kill, and backslash only if it precedes erase or line kill; whatever
characters are left after that may be interpreted by other programs as well.
Exercise 1-1. Explain what happens with
$ date\@
Exercise 1-2. Most shells (though not the 7th Edition shell) interpret # as introducing a
comment, and ignore all text from the # to the end of the line. Given this, explain the
following transcript, assuming your erase character is also #:
$ date
Mon Sep 26 12:39:56 EDT 1983
$ /date
Mon Sep 26 12:40:21 EDT 1983
$ \#date
$ \\#date
#date: not found
$
Type-ahead
The kernel reads what you type as you type it, even if it's busy with something else, so you can type as fast as you want, whenever you want, even when
some command is printing at you. If you type while the system is printing,
your input characters will appear intermixed with the output characters, but
they will be stored away and interpreted in the correct order. You can type
commands one after another without waiting for them to finish or even to
begin.
Stopping a program
You can stop most commands by typing the character DELETE. The
BREAK key found on most terminis may also work, although this is system
dependent. In a few programs, like text editors, DELETE stops whatever the
program is doing but leaves you in that program. Turning off the terminal or
CHAPTER 1
Your mail will be printed, one message at a time, most recent first. A f t e r each
item, m a i l waits for you to say what to do with it. The two basic responses
are d, which deletes the message, and RETURN, which does not (so it will still
be there the next time you read your mail). Other responses include p to
reprint a message, s filename to save it in the file you n a m e d , and q to quit
f r o m m a i l . (If you don't know what a file is, think of it as a place where you
can store information under a ame of your choice, and retrieve it later. Files
are the topic of Section 1.2 and indeed of much of this book.)
m a i l is one of those p r o g r a m s that is likely to differ f r o m what we describe
here; there are many variants. Look in your manual for details.
Sending mail to someone is straightforward. Suppose it is to go to the person with the login a m e n i c o . T h e easiest way is this:
$ mail
nico
Now type in the text of the letter
on as many lines as you like ...
After the last line of the letter
type a control-d.
ctl-d
$
The ctl-d signis the end of the letter by telling the m a i l c o m m a n d that there
is no more input. If you change your mind half-way through composing the
letter, press DELETE instead of ctl-d. T h e half-formed letter will be stored in
a file called d e a d . l e t t e r instead of being sent.
CHAPTER 1
UNIX FOR B E G I N N E R S
For practice, send mail to yourself, then type m a i l to read it. (This isn't
as aberrant as it might sound it's a handy reminder mechanism.)
There are other ways to send mail you can send a previously prepared
letter, you can mail to a number of people all at once, and you may be able to
send mail to people on other machines. For more details see the description of
the m a i l command in Section 1 of the UNIX Programmer's
Manual.
Henceforth we'll use the notation m a i l ( l ) to mean the page describing m a i l in
Section 1 of the manual. All of the commands discussed in this chapter are
found in Section 1.
There may also be a calendar service (see c a l e n d a r ( 1)); we'll show you in
Chapter 4 how to set one up if it hasn't been done already.
Writing to other users
If your UNIX system has mltiple users, someday, out of the blue, your terminal will print something like
Message from mary tty7...
accompanied by a startling beep. Mary wants to write to you, but unless you
take explicit action you won't be able to write back. To respond, type
$ write mary
This establishes a two-way communication path. Now the lines that Mary
types on her terminal will appear on yours and vice versa, although the path is
slow, rather like talking to the moon.
If you are in the middle of something, you have to get to a state where you
can type a command. Normally, whatever program you are running has to
stop or be stopped, but some programs, such as the editor and w r i t e itself,
have a ' ! ' command to escape temporarily to the shell see Table 2 in
Appendix 1.
The w r i t e command imposes no rules, so a protocol is needed to keep
what you type from getting garbled up with what Mary types. One convention
is to take turns, ending each turn with ( o ) , which stands for " o v e r , " and to
signal your intent to quit with ( o o ) , for "over and o u t . "
10
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
Mary's terminal:
$ write
you
CHAPTER 1
Your terminal:
$ Message from mary tty7...
write
mary
(o)
You can also exit f r o m w r i t e by pressing DELETE. Notice that your typing
errors do not appear on M a r y ' s terminal.
If you try to write to someone who isn't logged in, or who doesn't want to
be disturbed, you'11 be told. If the target is logged in but doesn't answer after
a decent interval, the person may be busy or away f r o m the terminal; simply
type ctl-d or DELETE. If you don't want to be disturbed, use m e s g ( l ) .
News
M a n y UNIX systems provide a news service, to keep users abreast of
interesting and not so interesting events. Try typing
$ news
T h e r e is also a large network of UNIX systems that keep in touch through telephone calis; ask a local expert about n e t n e w s and USENET.
The manual
The UNIX Programmer's
Manual describes most of what you need to know
about the system. Section 1 deals with c o m m a n d s , including those we discuss
in this chapter. Section 2 describes the system calis, the subject of C h a p t e r 7,
and Section 6 has information about games. The remaining sections talk about
functions for use by C p r o g r a m m e r s , file f o r m a t s , and system m a i n t e n a n c e .
( T h e n u m b e r i n g of these sections vares f r o m system to system.) D o n ' t forget
the p e r m u t e d ndex at the beginning; you can skim it quickly for c o m m a n d s
that might be relevant to what you want to do. T h e r e is also an introduction
to the system that gives an overview of how things work.
O f t e n the manual is kept on-line so that you can read it on your t e r m i n a l .
If you get stuck on something, and can't find an expert to help, you can print
any manual page on your terminal with the c o m m a n d man command-name.
CHAPTER 1
UNIX FOR B E G I N N E R S
11
who
and, of course,
$ man man
If l e a r n exists on your system, it will tell you what to do from there. If that
fails, you might also try t e a c h .
Gomes
It's not always admitted officially, but one of the best ways to get comfortable with a computer and a terminal is to play games. The U N I X system comes
with a modest supply of games, often supplemented locally. Ask around, or
see Section 6 of the manual.
1.2 Day-to-day use: files and common commands
Information in a U N I X system is stored in files, which are much like ordinary office files. Each file has a ame, contents, a place to keep it, and some
administrative information such as who owns it and how big it is. A file might
contain a letter, or a list of ames and addresses, or the source statements of a
program, or data to be used by a program, or even programs in their executable form and other non-textual material.
The U N I X file system is organized so you can maintain your own personal
files without interfering with files belonging to other people, and keep people
from interfering with you too. There are myriad programs that maniplate
files, but for now, we will look at only the more frequently used ones.
Chapter 2 contains a systematic discussion of the file system, and introduces
many of the other file-related commands.
Creating files the editor
If you want to type a paper or a letter or a program, how do you get the
information stored in the machine? Most of these tasks are done with a text
editor, which is a program for storing and manipulating information in the
computer. Almost every U N I X system has a screen editor, an editor that takes
advantage of modern terminis to display the effects of your editing changes in
context as you make them. Two of the most popular are vi and e m a c s . We
12
CHAPTER 1
won't describe any specific screen editor here, however, partly because of typographic limitations, and partly because there is no standard one.
There is, however, an older editor called ed that is certain to be available
on your system. It takes no advantage of special terminal features, so it will
work on any terminal. It also forms the basis of other essential programs
(including some screen editors), so it's worth learning eventually. Appendix 1
contains a concise description.
No matter what editor you prefer, you'll have to learn it well enough to be
able to create files. We'll use ed here to make the discussion concrete, and to
ensure that you can make our examples run on your system, but by all means
use whatever editor you like best.
To use ed to create a file called j u n k with some text in it, do the following:
$ ed
a
now type in
whatever text you want ...
w junk
39
<
$
Of course, you can edit the text you typed in, to correct spelling mistakes,
change wording, rearrange paragraphs and the like. When you're done, the q
command ( " q u i t " ) leaves the editor.
UNIX FOR B E G I N N E R S
CHAPTER 1
13
or
not
to
be
w junk
19
q
$ ed
a
That
is
the
question.
w temp
22
<1
The character counts from ed include the character at the end of each line,
called newline, which is how the system represents RETURN.
The ls command lists the ames (not contents) of files:
$ ls
junk
temp
$
which are indeed the two files just created. (There might be others as well
that you didn't create yourself.) The ames are sorted into alphabetical order
automatically.
l s , like most commands, has options that may be used to alter its default
behavior. Options follow the command ame on the command line, and are
usually made up of an initial minus sign
and a single letter meant to suggest
the meaning. For example, ls -t causes the files to be listed in " t i m e " order:
the order in which they were last changed, most recent first.
$ ls -t
temp
junk
$
The -1 option gives a " l o n g " listing that provides more information about each
file:
$ ls -1
total 2
- r w - r r -- 1 you
-rw-r--r -- 1 you
$
14
CHAPTER 1
" t o t a l 2" tells how many blocks of disc space the files occupy; a block is
usually either 512 or 1024 characters. The string - r w - r - - r tells who has
permission to read and write the file; in this case, the owner ( y o u ) can read
and write, but others can only read it. The " 1 " that follows is the number of
links to the file; ignore it until Chapter 2. " y o u " is the owner of the file, that
is, the person who created it. 19 and 22 are the number of characters in the
corresponding files, which agree with the numbers you got from e d . The date
and time tell when the file was last changed.
Options can b e grouped: l s - l t gives the same data a s l s - 1 , but sorted
with most recent files first. The -u option gives information on when files
were used: ls - l u t gives a long ( - 1 ) listing in the order of most recent use.
The option -r reverses the order of the output, so ls - r t lists in order of
least recent use. You can also ame the files you're interested in, and ls will
list the information about them only:
$ ls -1 junk
- r w - r ~ r 1 you
$
The strings that follow the program ame on the command line, such as -1
and j u n k in the example above, are called the program's arguments.
Arguments are usually options or ames of files to be used by the command.
Specifying options by a minus sign and a single letter, such as -t or the
combined - l t , is a common convention. In general, if a command accepts
such optional arguments, they precede any filename arguments, but may otherwise appear in any order. But UNIX programs are capricious in their treatment
of mltiple options. For example, standard 7th Edition ls won't accept
$ ls
-1
-t
UNIX FOR B E G I N N E R S
CHAPTER 1
$ ed junk
19
1,$p
To be or not to be
<7
$
15
T h e named file or files are catenatedf (henee the ame " c a t " ) o n t o the terminal one after another with nothing between.
T h e r e ' s no problem with short files, but for long ones, if you have a highspeed connection to your c o m p u t e r , you have to be quick with ctl-s to stop
output f r o m c a t before it flows off your screen. T h e r e is no " s t a n d a r d " command to print a file on a video terminal one screenful at a t i m e , though almost
every UNIX system has o n e . Your system might have one called pg or m o r e .
O u r s is called p; we'll show you its implementation in Chapter 6.
Like c a t , the c o m m a n d pr prints the contents of all the files n a m e d in a
list, but in a form suitable for line printers: every page is 66 linefe (11 inches)
long, with the date and time that the file was c h a n g e d , the page n u m b e r , and
the filename at the top of each page, and extra lines to skip over the fold in
the p a p e r . T h u s , to print j u n k neatly, then skip to the top of a new page and
print t e m p neatly:
16
CHAPTER 1
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
$ pr junk
temp
junk Page
To be or not to be
temp Page 1
prints each file in 3-column format. You can use any reasonable number in
place of " 3 " and pr will do its best. (The word filenames is a place-holder for
a list of ames of files.) pr -m will print a set of files in parallel columns.
See p r ( l ) .
It should be noted that pr is not a formatting program in the sense of rearranging lines and justifying margins. The true formatters are n r o f f and
t r o f f , which are discussed in Chapter 9.
There are also commands that print files on a high-speed printer. Look in
your manual under ames like lp and l p r , or look up " p r i n t e r " in the permuted index. Which to use depends on what equipment is attached to your
machine, p r and l p r are often used together; after p r formats the information properly, l p r handles the mechanics of getting it to the line printer. We
will return to this a little later.
Moving, copying, removing files mv, cp, rm
Let's look at some other commands. The first thing is to change the ame
of a file. Renaming a file is done by " m o v i n g " it from one ame to another,
like this:
$ mv junk
precious
This means that the file that used to be called j u n k is now called p r e c i o u s ;
the contents are unchanged. If you run ls now, you will see a different list:
j u n k is not there but p r e c i o u s is.
UNIX FOR B E G I N N E R S
CHAPTER 1
17
3> ls
precious
temp
$ cat junk
cat: can't open junk
$
Beware that if you move a file to another one that already exists, the target file
is replaced.
To make a copy of a file (that is, to have two versions of something), use
the cp command:
$ cp precious
precious.save
Finally, when you get tired of creating and moving files, the rm command
removes all the files you ame:
$ rm temp junk
rm: junk nonexistent
$
You will get a warning if one of the files to be removed wasn't there, but otherwise rm, like most UNIX commands, does its work silently. There is no
prompting or chatter, and error messages are curt and sometimes unhelpful.
Brevity can be disconcerting to newcomers, but experienced users find talkative
commands annoying.
What's in a filename?
So far we have used filenames without ever saying what a legal ame is, so
it's time for a couple of rules. First, filenames are limited to 14 characters.
Second, although you can use almost any character in a filename, common
sense says you should stick to ones that are visible, and that you should avoid
characters that might be used with other meanings. We have already seen, for
example, that in the ls command, ls -t means to list in time order. So if
you had a file whose ame was - t , you would have a tough time listing it by
ame. (How would you do it?) Besides the minus sign as a first character,
there are other characters with special meaning. To avoid pitfalls, you would
do well to use only letters, numbers, the period and the underscore until you're
familiar with the situation. (The period and the underscore are conventionally
used to divide filenames into chunks, as in p r e c i o u s . s a v e above.) Finally,
don't forget that case distinctions matter j u n k , J u n k , and JUNK are three
different ames.
A handful of useful commands
Now that you have the rudiments of creating files, listing their ames, and
printing their contents, we can look at a half-dozen file-processing commands.
18
CHAPTER 1
To make the discussion concrete, we'll use a file called poem that contains a
familiar verse by Augustus De Morgan. Let's create it with e d :
$ ed
a
Great fleas have little fleas
upon their backs to bite 'em,
And little fleas have lesser fleas,
and so ad infinitum.
And the great fleas themselves, in turn,
have greater fleas to go on;
While these again have greater still,
and greater still, and so on.
w poem
263
5
$
The first command counts the lines, words and characters in one or more
files; it is named wc after its word-counting function:
$ wc poem
8
$
46
263 poem
That is, poem has 8 lines, 46 words, and 263 characters. The definition of a
" w o r d " is very simple: any string of characters that doesn't contain a blank,
tab or newline.
wc will count more than one file for you (and print the totals), and it will
also suppress any of the counts if requested. See w c ( l ) .
The second command is called g r e p ; it searches files for lines that match a
pattern. (The ame comes from the ed command q/regular-expression/p,
which is explained in Appendix 1.) Suppose you want to look for the word
" f l e a s " in poem:
$ grep fleas poem
Great fleas have little fleas
And little fleas have lesser fleas,
And the great fleas themselves, in turn,
have greater fleas to go on;
$
g r e p will also look for lines that don't match the pattern, when the option -v
is used. (It's named 'v' after the editor command; you can think of it as
inverting the sense of the match.)
UNIX FOR B E G I N N E R S
CHAPTER 1
19
The third command is s o r t , which sorts its input into alphabetical order
line by line. This isn't very interesting for the poem, but let's do it anyway,
just to see what it looks like:
$ sort poem
and greater still, and so on.
and so ad infinitum.
have greater fleas to go on;
upon their backs to bite 'em,
And little fleas have lesser fleas,
And the great fleas themselves, in turn,
Great fleas have little fleas
While these again have greater still,
$
The sorting is line by line, but the default sorting order puts blanks first, then
upper case letters, then lower case, so it's not strictly alphabetical.
s o r t has zillions of options to control the order of sorting reverse
order, numerical order, dictionary order, ignoring leading blanks, sorting on
fields within the line, etc. but usually one has to look up those options to be
sure of them. Here are a handful of the most common:
sort
sort
sort
sort
sort
-r
-n
-nr
-f
+n
20
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 1
$ tail -1 poem
and greater still, and so on.
$
The final pair of commands is for comparing files. Suppose that we have a
variant of poem in the file new_poem:
$ cat poem
Great fleas have little fleas
upon their backs to bite 'em,
And little fleas have lesser fleas,
and so ad infinitum.
And the great fleas themselves, in turn,
have greater fleas to go on;
While these again have greater still,
and greater still, and so on.
$ cat new_poem
Great fleas have little fleas
upon their backs to bite them,
And little fleas have lesser fleas,
and so on ad infinitum.
And the great fleas themselves, in turn,
have greater fleas to go on;
While these again have greater still,
and greater still, and so on.
$
There's not much difference between the two files; in fact you'll have to look
hard to find it. This is where file comparison commands come in handy. cmp
finds the first place where two files differ:
$ cmp poem new_poem
poem new.poem differ: char 58, line 2
$
This says that the files are different in the second line, which is true enough,
but it doesn't say what the difference is, or does it identify any differences
beyond the first.
The other file comparison command is d i f f , which reports on all lines that
are changed, added or deleted:
CHAPTER 1
UNIX FOR B E G I N N E R S
21
and so on ad infinitum.
This says that line 2 in the first file (poem) has to be changed into line 2 of the
second file ( n e w _ p o e m ) , and similarly for line 4.
Generally speaking, cmp is used when you want to be sure that two files
really have the same contents. It's fast and it works on any kind of file, not
just text. d i f f is used when the files are expected to be somewhat different,
and you want to know exactly which lines differ. d i f f works only on files of
text.
A summary of file system commands
Table 1.1 is a brief summary of the commands we've seen so far that deal
with files.
1.3 More about files: directories
The system distinguishes your file called j u n k from anyone else's of the
same ame. The distinction is made by grouping files into directories, rather
in the way that books are placed on shelves in a library, so files in different
directories can have the same ame without any conflict.
Generally each user has a personal or home directory, sometimes called
login directory, that contains only the files that belong to him or her. When
you log in, you are " i n " your home directory. You may change the directory
you are working in often called your working or current directory but
your home directory is always the same. Unless you take special action, when
you create a new file it is made in your current directory. Since this is initially
your home directory, the file is unrelated to a file of the same ame that might
exist in someone else's directory.
A directory can contain other directories as well as ordinary files ( " G r e a t
directories have lesser directories . . . " ) . The natural way to picture this organization is as a tree of directories and files. It is possible to move around within
this tree, and to find any file in the system by starting at the root of the tree
and moving along the proper branches. Conversely, you can start where you
are and move toward the root.
Let's try the latter first. Our basic tool is the command pwd ("print working directory"), which prints the ame of the directory you are currently in:
22
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
Table 1.1:
ls
l sf i l e n a m e s
ls
ls
ls
ls
-t
-1
-u
-r
e d filename
cp filel file2
mv filel file2
rmfilenames
c a tf i l e n a m e s
p rf i l e n a m e s
pr -n filenames
pr
-mfilenames
CHAPTER 1
wcfilenames
w c - 1f i l e n a m e s
g r e p pattern f i l e n a m e s
g r e p - v pattern f i l e s
s o r tf i l e n a m e s
t a i l f i l e ame
tail
tail
-nfilename
+nfilename
cmpfilelfile2
d i f f filie 1file2
$ pwd
/usr/you
$
This says that you are currently in the directory y o u , in the directory u s r ,
which in turn is in the root directory, which is conventionally called just
The / characters separate the components of the ame; the limit of 14 characters mentioned above applies to each component of such a ame. On many
systems, / u s r is a directory that contains the directories of all the normal
users of the system. (Even if your home directory is not / u s r / y o u , pwd will
print something analogous, so you should be able to follow what happens
below.)
If you now type
CHAPTER 1
UNIX FOR B E G I N N E R S
23
$ ls /usr/you
you should get exactly the same list of file ames as you get from a plain l s .
When no arguments are provided, ls lists the contents of the current directory; given the ame of a directory, it lists the contents of that directory.
Next, try
$ ls /usr
This should print a long series of ames, among which is your own login directory y o u .
The next step is to try listing the root itself. You should get a response
similar to this:
$ ls /
bin
boot
dev
etc
lib
tmp
unix
usr
$
(Don't be confused by the two meanings of /: it's both the ame of the root
and a separator in filenames.) Most of these are directories, but u n i x is actually a file containing the executable form of the UNIX kernel. More on this in
Chapter 2.
Now try
$ cat /usr/you/junk
is called the pathname of the file. " P a t h n a m e " has an intuitive meaning: it
represents the full ame of the path from the root through the tree of directories to a particular file. It is a universal rule in the UNIX system that wherever you can use an ordinary filename, you can use a pathname.
The file system is structured like a genealogical tree; here is a picture that
may make it clearer.
24
CHAPTER 1
dev
etc
usr
tmp
you
mike
pal
mary
bin
junk
junk
temp
unix
junk
boot
data
/usr/you/junk
Similarly, you can find out what files Mary has by saying
$ ls /usr/mary
data
junk
$
data
If Mary doesn't want you poking around in her files, or vice versa, privacy
can be arranged. Each file and directory has read-write-execute permissions
for the owner, a group, and everyone else, which can be used to control access.
(Recall ls - 1 . ) In our local systems, most users most of the time find openness of more benefit than privacy, but policy may be different on your system,
so we'll get back to this in Chapter 2.
As a final set of experiments with pathnames, try
$ ls /bin /usr/bin
Do some of the ames look familiar? When you run a command by typing its
ame after the prompt, the system looks for a file of that ame. It normally
looks first in your current directory (where it probably doesn't find it), then in
/ b i n , and finally in / u s r / b i n . There is nothing special about commands
UNIX FOR B E G I N N E R S
CHAPTER 1
25
like c a t or l s , except that they have been collected into a couple of directories to be easy to find and administer. To verify this, try to execute some of
these programs by using their full pathnames:
$ /bin/date
Mon Sep 26 23:29:32 EDT
$ /bin/who
srm
ttyl
Sep 26
cvw
.^tty4
Sep 26
you
tty5
Sep 26
$
1983
22:20
22:40
23:04
/usr/games
and do whatever comes naturally. Things might be more fun outside of normal working
hours.
Changing directory cd
If you work regularly with Mary on information in her directory, you can
say "I want to work on Mary's files instead of my o w n . " This is done by
changing your current directory with the cd command:
$ cd
/usr/mary
Make a directory
Go to it
Make sure you're in the right place
Write the book (several minutes pass)
$ cd . .
$ pwd
/usr/you
$
refers to the parent of whatever directory you are currently in, the directory one level closer to the root.
' is a synonym for the current directory.
$ cd
26
CHAPTER 1
all by itself will take you back to your home directory, the directory where you
log in.
Once your book is published, you can clean up the files. To remove the
directory b o o k , remove all the files in it (we'll show a fast way shortly), then
cd to the parent directory of b o o k and type
$ rmdir
book
which is the organization we used for this book. With a systematic naming
convention, you can tell at a glance where a particular file fits into the whole.
What if you want to print the whole book? You could say
CHAPTER 1
UNIX FOR B E G I N N E R S
$ p r ch1.
1 ch1.2
ch1.3
27
...
but you would soon get bored typing filenames and start to make mistakes.
This is where filename shorthand comes in. If you say
$ p r ch*
ch1. , *
113
562
935
4081
974
4191
378
1561
1293
5298
33
194
75
323
16210
3801
3200
22435
22756
8481
28841
1 190
2030
88933
ch1 ,
.0
ch1 ,
.1
ch1 .
.2
ch1 . 3
ch1 .
.4
ch1 ,
,5
ch1 ,
,6
total
There is a program called e c h o that is especially valuable for experimenting with the meaning of the shorthand characters. As you might guess, e c h o
does nothing more than echo its arguments:
$ echo
helio
helio world
$
world
ch1.*
28
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
ra
CHAPTER 1
removes all files in your current directory. (You had better be very sure that's
what you wanted to say!)
The * is not limited to the last position in a filename *'s can be anywhere and can occur several times. Thus
$ rm *.save
Note that the patterns match only existing filenames. In particular, you cannot
make up new filenames by using patterns. For example, if you want to expand
ch to c h a p t e r in each filename, you cannot do it this way:
$ mv ch.*
chapter.*
Doesn't work!
'?
UNIX FOR B E G I N N E R S
CHAPTER 1
$ ls
29
\?
ls
ls
ls
ls
ls
junk
/
$
$
$
$
$
echo junk
echo /
echo
echo
echo
Input-output
redirection
M o s t o f t h e c o m m a n d s w e h a v e seen s o f a r p r o d u c e o u t p u t o n t h e t e r m i n a l ;
s o m e , like t h e e d i t o r , also t a k e their i n p u t f r o m the t e r m i n a l . I t i s n e a r l y
u n i v e r s a l t h a t t h e t e r m i n a l can be r e p l a c e d by a file for e i t h e r or b o t h of input
and output. As one example,
$ ls
m a k e s a list of f i l e n a m e s on y o u r t e r m i n a l .
$ ls
>filelist
f1
f2 f3
>temp
f1
f2
f3
>>temp
mary
joe
tom
bob
<let
30
CHAPTER 1
Y o u can p r i n t t h e
>temp
-3 < t e m p
<temp
<temp
s o r t s t h e c o n t e n t s o f t h e file t e m p , a s d o e s
$ sort
temp
t e m p 1 temp2
temp3
but if no f i l e n a m e s a r e g i v e n , it s o r t s its s t a n d a r d i n p u t . T h i s is an e s s e n t i a l
p r o p e r t y of m o s t c o m m a n d s : if no f i l e n a m e s a r e s p e c i f i e d , t h e s t a n d a r d i n p u t is
p r o c e s s e d . T h i s m e a n s t h a t you can simply t y p e a t c o m m a n d s t o see h o w t h e y
UNIX FOR B E G I N N E R S
CHAPTER 1
work.
31
For example,
$ sort
ghi
abe
def
ctl-d
abe
def
ghi
$
>ls.out
who I sort
who I wc -1
ls I wc -1
ls I pr -3
who ! grep mary
A n y p r o g r a m t h a t r e a d s f r o m t h e t e r m i n a l can r e a d f r o m a p i p e i n s t e a d ;
a n y p r o g r a m t h a t w r i t e s on the t e r m i n a l can w r i t e to a p i p e . T h i s is w h e r e the
c o n v e n t i o n o f r e a d i n g the s t a n d a r d i n p u t w h e n n o files are n a m e d p a y s o f f : a n y
p r o g r a m t h a t a d h e r e s t o t h e c o n v e n t i o n can b e u s e d i n p i p e l i n e s . g r e p , p r ,
s o r t a n d w c are all u s e d that w a y i n t h e pipelines a b o v e .
Y o u can h a v e as m a n y p r o g r a m s in a pipeline as you w i s h :
32
$ ls
/ pr
-3
CHAPTER 1
/ Ipr
c r e a t e s a 3 - c o l u m n list of f i l e n a m e s on t h e line p r i n t e r , a n d
$ who
I grep
mary
I wc -1
c o u n t s h o w m a n y t i m e s M a r y i s logged in.
T h e p r o g r a m s in a pipeline actually r u n at the s a m e t i m e , not o n e a f t e r
a n o t h e r . T h i s m e a n s that the p r o g r a m s in a pipeline can be i n t e r a c t i v e ; the
kernel looks after whatever scheduling and synchronization is needed to m a k e
it all w o r k .
A s you p r o b a b l y suspect b y n o w , the shell a r r a n g e s t h i n g s w h e n you ask f o r
a pipe; t h e i n d i v i d u a l p r o g r a m s are oblivious t o t h e r e d i r e c t i o n . O f c o u r s e ,
p r o g r a m s h a v e t o o p e r a t e sensibly i f t h e y a r e t o b e c o m b i n e d this w a y . M o s t
c o m m a n d s f o l l o w a c o m m o n d e s i g n , so t h e y will fit p r o p e r l y i n t o p i p e l i n e s at
a n y p o s i t i o n . N o r m a l l y a c o m m a n d invocation looks like
command
optional-arguments
optional-filenames
I f n o f i l e n a m e s are g i v e n , t h e c o m m a n d r e a d s its s t a n d a r d i n p u t , w h i c h i s b y
d e f a u l t the t e r m i n a l ( h a n d y for e x p e r i m e n t i n g ) but w h i c h can b e r e d i r e c t e d t o
c o m e f r o m a file or a p i p e . At the s a m e t i m e , on t h e o u t p u t s i d e , m o s t c o m m a n d s w r i t e t h e i r o u t p u t on t h e standard output, w h i c h is by d e f a u l t sent to t h e
t e r m i n a l . But it t o o c a n be r e d i r e c t e d to a file or a p i p e .
Error messages f r o m commands have to be handled differently, however,
or t h e y m i g h t d i s a p p e a r i n t o a file or d o w n a p i p e . So e a c h c o m m a n d h a s a
standard
error o u t p u t as well, which is n o r m a l l y d i r e c t e d to y o u r t e r m i n a l .
O r , as a p i c t u r e :
s t a n d a r d input
or files
standard
output
standard
error
A l m o s t all o f t h e c o m m a n d s w e h a v e t a l k e d a b o u t s o f a r fit t h i s m o d e l ; t h e
only e x c e p t i o n s a r e c o m m a n d s like d a t e a n d w h o t h a t r e a d n o i n p u t , a n d a
f e w like c m p a n d d i f f that h a v e a fixed n u m b e r o f file i n p u t s . ( B u t look a t
the
option on these.)
Exercise 1-7. Explain the difference between
$ who I sort
UNIX FOR B E G I N N E R S
CHAPTER 1
33
$ who >sort
Processes
T h e shell d o e s q u i t e a f e w t h i n g s b e s i d e s setting u p p i p e s . Let u s t u r n
b r i e f l y to t h e basics of r u n n i n g m o r e t h a n o n e p r o g r a m at a t i m e , since we
h a v e a l r e a d y seen a bit of t h a t with p i p e s . F o r e x a m p l e , you can r u n t w o p r o g r a m s with o n e c o m m a n d line b y s e p a r a t i n g t h e c o m m a n d s with a s e m i c o l o n ;
t h e shell r e c o g n i z e s t h e s e m i c o l o n a n d b r e a k s the line i n t o t w o c o m m a n d s :
$ date;
who
T u e S e p 27 0 1 : 0 3 : 1 7 EDT
ttyO
ken
S e p 27
tty 1
S e p 26
dmr
tty2
rob
S e p 26
tty3
bwk
S e p 27
tty4
jj
S e p 26
you
tty5
S e p 26
tty7
ber
S e p 26
1983
0 0 : : 43
2 3 :: 4 5
2 3 : : 59
0 0 : : 06
23: : 31
23: : 04
23: : 34
>wc.out
&
Process-id printed by the shell
34
$ pr
6951
$
ch*
/ lpr
CHAPTER 1
&
Process-id of l p r
6944
CN
O
$ p s -ag
P I D TTY
36 CO
6423 5
6704 1
6722 1
4430 2
6612 7
6628 7
6843 2
6949 4
6952 5
6951 5
6959 5
6844 1
CMD
/etc/cron
-sh
-sh
vi paper
-sh
-sh
rogue
w r i t e dmr
l o g i n bimmler
pr ch1.1 ch1.2 ch1.3 ch1.4
lpr
ps - a g
write rob
P I D is t h e p r o c e s s - i d ; TTY is t h e t e r m i n a l a s s o c i a t e d with t h e p r o c e s s ( a s in
w h o ) ; TIME is t h e p r o c e s s o r t i m e u s e d in m i n u t e s a n d s e c o n d s ; a n d t h e rest is
the c o m m a n d being r u n . ps is one of those c o m m a n d s that is different on diff e r e n t v e r s i o n s o f the s y s t e m , s o y o u r o u t p u t m a y not b e f o r m a t t e d like t h i s .
E v e n the a r g u m e n t s m a y b e d i f f e r e n t see t h e m a n u a l p a g e p s ( l ) .
P r o c e s s e s h a v e t h e s a m e sort o f h i e r a r c h i c a l s t r u c t u r e t h a t files d o : e a c h
p r o c e s s h a s a p a r e n t , a n d m a y well h a v e c h i l d r e n . Y o u r shell w a s c r e a t e d by a
p r o c e s s a s s o c i a t e d with w h a t e v e r t e r m i n a l line c o n n e c t s you t o t h e s y s t e m . A s
UNIX FOR B E G I N N E R S
CHAPTER 1
35
you run c o m m a n d s , those processes are the direct children of your shell. If
you run a p r o g r a m f r o m within one of those, for example with the ! c o m m a n d
to escape f r o m e d , that creates its own child process which is thus a grandchild
of the shell.
Sometimes a process takes so long that you would like to start it r u n n i n g ,
then turn off the terminal and go h o m e without waiting for it to finish. But if
you turn off your terminal or break your connection, the process will normally
be killed even if you used &. T h e c o m m a n d n o h u p ( " n o h a n g u p " ) was
created to deal with this situation: if you say
$ nohup
command &
the c o m m a n d will continu to run if you log out. A n y output f r o m the command is saved in a file called n o h u p . o u t . T h e r e is no way to n o h u p a comm a n d retroactively.
If your process will take a lot of processor resources, it is kind to those who
share your system to run your job with lower than normal priority; this is done
b y another p r o g r a m called n i c e :
$ n i c e expensive-command
&
This is the typical usage, but of course the c o m m a n d s could come f r o m a file:
$ at
$
3am <file
where e is whatever character you want for erase and k is for line kill. But it's
36
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 1
erase
W e ' r e u s i n g - h e r e so you can see it, but you could put a literal b a c k s p a c e in
y o u r . p r o f i l e . s t t y also u n d e r s t a n d s the n o t a t i o n
f o r c / - x , s o you can
get t h e s a m e e f f e c t with
stty
erase
//v
h'
erase
'*h'
-tabs
! wc - 1
Some people
/usr/games/fortune
A f t e r a w h i l e you m a y d e c i d e t h a t it is t a k i n g t o o
. p r o f i l e back t o the b a r e necessities.
S o m e of the p r o p e r t i e s of t h e shell a r e actually
variables,
w i t h v a l e s that you can access a n d set
p r o m p t s t r i n g , w h i c h we h a v e b e e n s h o w i n g as $,
v a r i a b l e called PS 1, a n d you can set it to a n y t h i n g
PS1='Yes dear?
'
T h e q u o t e s a r e n e c e s s a r y since t h e r e a r e s p a c e s i n t h e p r o m p t s t r i n g . Spaces
a r e not p e r m i t t e d a r o u n d the = in this c o n s t r u c t i o n .
T h e shell also t r e a t s t h e v a r i a b l e s H O M E a n d M A I L specially. H O M E i s the
a m e o f y o u r h o m e d i r e c t o r y ; i t i s n o r m a l l y set p r o p e r l y w i t h o u t h a v i n g t o b e
i n .profile. T h e v a r i a b l e M A I L a m e s the s t a n d a r d file w h e r e y o u r mail i s
k e p t . If you d e f i n e it f o r the shell, you will be n o t i f i e d a f t e r e a c h c o m m a n d if
new mail has arrived:t
t This is implemented badly in the shell. Looking at the file after every command adds perceptibly
to the system load. Also, if you are working in an editor for a long time you won't learn about
CHAPTER 1
UNIX FOR B E G I N N E R S
37
MAIL=/usr/spool/mail/you
( T h e m a i l file m a y b e d i f f e r e n t o n y o u r s y s t e m ; / u s r / m a i l / y o u i s also c o m mon.)
P r o b a b l y t h e m o s t u s e f u l shell v a r i a b l e i s t h e o n e t h a t c o n t r o l s w h e r e t h e
shell l o o k s f o r c o m m a n d s . R e c a l l t h a t w h e n you t y p e the a m e o f a c o m m a n d ,
t h e shell n o r m a l l y l o o k s for i t first i n t h e c u r r e n t d i r e c t o r y , t h e n i n / b i n , a n d
t h e n in / u s r / b i n . T h i s s e q u e n c e of d i r e c t o r i e s is called t h e search path, a n d
is s t o r e d in a shell v a r i a b l e called PATH. If the d e f a u l t s e a r c h p a t h isn't w h a t
you w a n t , you can c h a n g e it, a g a i n u s u a l l y i n y o u r . p r o f i l e . F o r e x a m p l e ,
this line sets t h e p a t h t o t h e s t a n d a r d one plus / u s r / g a m e s :
PATH= . : / b i n : / u s r / b i n : / u s r / g a m e s
T h e s y n t a x is a bit s t r a n g e : a s e q u e n c e of d i r e c t o r y a m e s s e p a r a t e d by c o l o n s .
R e m e m b e r that
is t h e c u r r e n t d i r e c t o r y . Y o u can omit t h e
a nuil c o m p o n e n t in PATH m e a n s t h e c u r r e n t d i r e c t o r y .
An a l t e r n a t e w a y to set PATH in this specific c a s e is s i m p l y to a u g m e n t t h e
previous valu:
PATH=$PATH : / u s r / g a m e s
38
CHAPTER 1
TERM=adm3
t o y o u r . p r o f i l e file.
It is also possible to use v a r i a b l e s for a b b r e v i a t i o n . If you f i n d y o u r s e l f f r e q u e n t l y r e f e r r i n g t o s o m e d i r e c t o r y with a long a m e , i t m i g h t b e w o r t h w h i l e
a d d i n g a line like
d=/horribly/long/directory/ame
to y o u r p r o f i l e , so t h a t you can say t h i n g s like
$ cd
$d
P e r s o n a l v a r i a b l e s like d
t h e m f r o m t h o s e used by
F i n a l l y , it's n e c e s s a r y
o t h e r p r o g r a m s ; this i s
r e t u r n in C h a p t e r 3:
export
a r e c o n v e n t i o n a l l y spelled in l o w e r c a s e to d i s t i n g u i s h
the shell itself, like PATH.
to tell the shell that you i n t e n d to use the v a r i a b l e s in
d o n e with the c o m m a n d e x p o r t , t o w h i c h w e will
CHAPTER 1
UNIX FOR B E G I N N E R S
39
CHAPTER 2:
E v e r y t h i n g in the U N I X system is a file. T h a t is less of an oversimplification than you might t h i n k . W h e n the first versin of the system was being
d e s i g n e d , b e f o r e it even had a a m e , the discussions focused on the structure
of a file system that would be clean and easy to use. T h e file system is central
to the success and convenience of the U N I X system. It is one of the best e x a m ples of the " k e e p it s i m p l e " philosophy, showing the power achieved by c a r e f u l
i m p l e m e n t a t i o n of a f e w well-chosen ideas.
To talk c o m f o r t a b l y about c o m m a n d s and their interrelationships, we need
a good b a c k g r o u n d in the structure and outer workings of t h e file system. T h i s
chapter covers most of the details of using the file system what files are,
h o w they are r e p r e s e n t e d , directories and the file system h i e r a r c h y , permissions, inodes ( t h e system's internal record of files) and device files. Because
most use of the U N I X system deals with m a n i p u l a t i n g files, t h e r e are m a n y
c o m m a n d s for file investigation or r e a r r a n g e m e n t ; this chapter introduces the
m o r e c o m m o n l y used ones.
2 . 1 T h e bascs of files
A file is a s e q u e n c e of bytes. (A byte is a small chunk of i n f o r m a t i o n , typically 8 bits long. For our p u r p o s e s , a byte is equivalent to a c h a r a c t e r . ) No
s t r u c t u r e is imposed on a file by the s y s t e m , and no m e a n i n g is attached to its
c o n t e n t s the m e a n i n g of the bytes d e p e n d s solely on the p r o g r a m s that interpret the file. F u r t h e r m o r e , as we shall see, this is true not just of disc files but
of peripheral devices as well. M a g n e t i c tapes, mail m e s s a g e s , c h a r a c t e r s typed
on the k e y b o a r d , line printer o u t p u t , data flowing in pipes each of t h e s e
files is just a sequence of bytes as far as the system and the p r o g r a m s in it are
concerned.
T h e best way to learn about files is to play with t h e m , so start by creating a
small file:
41
42
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
$ ed
a
now is the time
for all
good people
w junk
36
<1
$ ls -1 junk
- r w - r r 1 you
$
36 Sep 27 0 6 : 1 1
junk
n
f
p
o
o
i
a
r
1
s
l
t
l
h
g
e
o
t
o
m
p
e \ n
o
\n
junk
n
156
f
o
w
157 167 0 4 0
o
r
146 157
p
1
160 154
i
151
162 0 4 0 141
e
\n
145
012
s
t
163 040 164
a
l
l
h
e
t
150 1 4 5 0 4 0 164
g
o
o
d
154
147
154
040
157
157
i
151
144 0 4 0
m
e \ n
155 145 012
p
e
o
160
145 157
0000044
CHAPTER 2
T H E FILE SYSTEM
43
o r d i n a l n u m b e r o f t h e n e x t c h a r a c t e r s h o w n , i n octal.
By the way, the
e m p h a s i s on octal n u m b e r s is a h o l d o v e r f r o m t h e PDP-11, for w h i c h octal w a s
t h e p r e f e r r e d n o t a t i o n . H e x a d e c i m a l i s b e t t e r suited for o t h e r m a c h i n e s ; t h e
- x o p t i o n tells o d t o p r i n t i n h e x .
N o t i c e t h a t t h e r e i s a c h a r a c t e r a f t e r each line, with octal v a l u 0 1 2 . T h i s
is t h e ASCII newline c h a r a c t e r ; it is w h a t t h e s y s t e m p l a c e s in t h e input w h e n
you p r e s s t h e R E T U R N k e y . B y a c o n v e n t i o n b o r r o w e d f r o m C , t h e c h a r a c t e r
r e p r e s e n t a t i o n of a n e w l i n e is \ n , but this is only a c o n v e n t i o n u s e d by p r o g r a m s like od to m a k e it e a s y to r e a d t h e v a l u s t o r e d in t h e file is t h e single b y t e 0 1 2 .
N e w l i n e is t h e m o s t c o m m o n e x a m p l e of a special character.
Other charact e r s a s s o c i a t e d with s o m e t e r m i n a l c o n t r o l o p e r a t i o n i n c l u d e b a c k s p a c e (octal
valu 0 1 0 , printed a s \ b ) , tab ( 0 1 1 , \ t ) , and carriage return ( 0 1 5 , \ r ) .
It is i m p o r t a n t in e a c h case to distinguish b e t w e e n h o w t h e c h a r a c t e r is
s t o r e d in a file a n d h o w it is i n t e r p r e t e d in v a r i o u s s i t u a t i o n s . F o r e x a m p l e ,
w h e n you t y p e a b a c k s p a c e o n y o u r k e y b o a r d ( a n d a s s u m i n g t h a t y o u r e r a s e
c h a r a c t e r is b a c k s p a c e ) , t h e k e r n e l i n t e r p r e t s it to m e a n t h a t you w a n t to discard w h a t e v e r c h a r a c t e r you typed p r e v i o u s l y . Both t h a t c h a r a c t e r a n d t h e
b a c k s p a c e d i s a p p e a r , but t h e b a c k s p a c e is e c h o e d to y o u r t e r m i n a l , w h e r e it
m a k e s t h e c u r s o r m o v e o n e position b a c k w a r d s .
If you t y p e t h e s e q u e n c e
\( i . e . , \ f o l l o w e d by a b a c k s p a c e ) , h o w e v e r , t h e k e r n e l i n t e r p r e t s t h a t to m e a n
t h a t you w a n t a literal b a c k s p a c e in y o u r i n p u t , so t h e \ is d i s c a r d e d a n d t h e
b y t e 0 1 0 w i n d s u p i n y o u r file. W h e n t h e b a c k s p a c e i s e c h o e d o n y o u r t e r m i n a l , it m o v e s t h e c u r s o r to sit on t o p of the \.
W h e n you print a file t h a t c o n t a i n s a b a c k s p a c e , t h e b a c k s p a c e is p a s s e d
u n i n t e r p r e t e d t o y o u r t e r m i n a l , which a g a i n will m o v e t h e c u r s o r o n e position
b a c k w a r d s . W h e n you u s e od to d i s p l a y a file that c o n t a i n s a b a c k s p a c e , it
a p p e a r s a s a b y t e with v a l u 0 1 0 , o r , with the - c o p t i o n , a s \ b .
T h e s t o r y for tabs is m u c h t h e s a m e : on i n p u t , a t a b c h a r a c t e r is e c h o e d to
y o u r t e r m i n a l a n d sent t o the p r o g r a m t h a t i s r e a d i n g ; o n o u t p u t , t h e t a b i s
s i m p l y s e n t to t h e t e r m i n a l for i n t e r p r e t a t i o n t h e r e . T h e r e is a d i f f e r e n c e ,
t h o u g h you can tell the k e r n e l that you w a n t it to i n t e r p r e t t a b s for you on
o u t p u t ; in t h a t c a s e , e a c h t a b t h a t w o u l d be p r i n t e d is r e p l a c e d by t h e right
n u m b e r o f b l a n k s t o get t o t h e n e x t t a b stop. T a b stops a r e set a t c o l u m n s 9 ,
17, 2 5 , e t c . T h e c o m m a n d
$ stty
-tabs
44
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
T H E FILE SYSTEM
CHAPTER 2
$ cat
123
456
789
ctl-d
123
456
789
$ cat
123
123
456
456
789
789
ctl-d
45
-u
46
2.2
CHAPTER 2
W h a t ' s in a file?
T h e f o r m a t of a file is d e t e r m i n e d by
w i d e v a r i e t y of file t y p e s , p e r h a p s b e c a u s e
But since file t y p e s a r e not d e t e r m i n e d b y
you t h e t y p e of a file: it d o e s n ' t k n o w it.
c a t e d g u e s s ( w e ' l l explain h o w s h o r t l y ) :
t h e p r o g r a m s t h a t use it; t h e r e is a
t h e r e is a w i d e v a r i e t y of p r o g r a m s .
t h e file s y s t e m , t h e k e r n e l c a n ' t tell
T h e file c o m m a n d m a k e s an e d u -
$ f i l e /bin
/bin/ed
/usr/src/cmd/ed.c
/usr/man/man
/bin:
directory
/bin/ed:
pur executable
/usr/src/cmd/ed.c:
c program t e x t
/usr/man/man1/ed.1:
r o f f , n r o f f , o r eqn i n p u t
1/ed.
text
T H E FILE SYSTEM
CHAPTER 2
s o t h a t , for e x a m p l e , s o r t i s n e v e r given / b i n / e d a s i n p u t .
avoid f o r e c l o s i n g s o m e u s e f u l c o m p u t a t i o n . A l t h o u g h
$ sort
47
One reason is to
/bin/ed
d o e s n ' t m a k e m u c h s e n s e , t h e r e a r e m a n y c o m m a n d s t h a t can o p e r a t e o n a n y
file a t all, a n d t h e r e ' s n o r e a s o n t o restrict t h e i r c a p a b i l i t i e s . o d , w c , c p , e m p ,
f i l e a n d m a n y o t h e r s p r o c e s s files r e g a r d l e s s o f their c o n t e n t s . B u t t h e f o r m a t l e s s idea goes d e e p e r t h a n t h a t . I f , s a y , n r o f f i n p u t w e r e d i s t i n g u i s h e d
f r o m C s o u r c e , t h e editor w o u l d be f o r c e d to m a k e t h e distinction w h e n it
c r e a t e d a f i l e , a n d p r o b a b l y w h e n it r e a d in a file for e d i t i n g a g a i n . A n d it
w o u l d c e r t a i n l y m a k e it h a r d e r for us to t y p e s e t t h e C p r o g r a m s in C h a p t e r s 6
t h r o u g h 8!
I n s t e a d of c r e a t i n g d i s t i n c t i o n s , t h e UNIX s y s t e m t r i e s to e f f a c e t h e m . All
text consists o f lines t e r m i n a t e d b y n e w l i n e c h a r a c t e r s , a n d m o s t p r o g r a m s
u n d e r s t a n d this s i m p l e f o r m a t . M a n y t i m e s while w r i t i n g this b o o k , w e r a n
c o m m a n d s t o c r e a t e text files, p r o c e s s e d t h e m with c o m m a n d s like t h o s e listed
a b o v e , a n d u s e d a n e d i t o r t o m e r g e t h e m i n t o the t r o f f i n p u t for t h e b o o k .
T h e t r a n s c r i p t s you see o n a l m o s t e v e r y p a g e are m a d e b y c o m m a n d s like
$ od -c junk
$ ed ch2. 1
1534
r temp
168
>temp
48
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
Directories and f i l e n a m e s
T H E FILE SYSTEM
CHAPTER 2
49
$ pwd
/usr/you
$ mkdir
recipes
$ cd recipes
$ pwd
/usr/you/recipes
$ mkdir
pie cookie
$ ed pie/apple
$ ed cookie/choc.chip
$
Notice that it is simple to refer to subdirectories. p i e / a p p l e has an obvious
m e a n i n g : the apple pie r e c i p e , i n d i r e c t o r y / u s r / y o u / r e c i p e s / p i e .
You
could i n s t e a d h a v e put t h e recipe in, say, r e c i p e s / a p p l e . p i e , r a t h e r t h a n
in a s u b d i r e c t o r y of r e c i p e s , but it s e e m s b e t t e r o r g a n i z e d to put all the pies
together,
too.
For
example,
the
crust
recipe
could
be
kept
in
r e c i p e s / p i e / c r u s t r a t h e r t h a n d u p l i c a t i n g i t i n e a c h pie r e c i p e .
A l t h o u g h the file s y s t e m is a p o w e r f u l o r g a n i z a t i o n a l t o o l , you can f o r g e t
w h e r e you put a f i l e , or e v e n w h a t files y o u ' v e g o t . T h e o b v i o u s solution is a
c o m m a n d o r t w o t o r u m m a g e a r o u n d i n d i r e c t o r i e s . T h e l s c o m m a n d i s certainly h e l p f u l for f i n d i n g f i l e s , but it d o e s n ' t look in s u b - d i r e c t o r i e s .
$ cd
$ ls
junk
recipes
$ file *
junk:
ascii
recipes:
$ ls recipes
cookie
pie
$ ls recipes/pie
apple
crust
$
text
directory
50
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
/usr/you
junk
recipes
pie
apple
cookie
crust
choc.chip
./recipes/pie
./recipes/cookie
./recipes
T h e f i l e n a m e s a r e o b v i o u s ; t h e n u m b e r s a r e the n u m b e r o f disc b l o c k s typically 5 1 2 or 1024 b y t e s each of s t o r a g e f o r e a c h file. T h e v a l u for a d i r e c t o r y i n d i c a t e s h o w m a n y b l o c k s a r e c o n s u m e d b y all t h e files i n that d i r e c t o r y
a n d its s u b d i r e c t o r i e s , i n c l u d i n g the d i r e c t o r y itself.
d u h a s a n o p t i o n - a , for " a l l , " t h a t c a u s e s i t t o print out all t h e files i n a
d i r e c t o r y . If o n e of t h o s e is a d i r e c t o r y , du p r o c e s s e s t h a t as well:
$ du - a
2
3
6
3
4
11
1
13
$
./recipes/pie/apple
./recipes/pie/crust
./recipes/pie
./recipes/cookie/choc.chip
./recipes/cookie
./recipes
./junk
I grep choc
./recipes/cookie/choc.chip
R e c a l l f r o m C h a p t e r 1 that the a m e
is a d i r e c t o r y e n t r y t h a t r e f e r s to t h e
d i r e c t o r y itself; it p e r m i t s access to a d i r e c t o r y w i t h o u t h a v i n g to k n o w t h e f u l l
T H E FILE SYSTEM
CHAPTER 2
51
.
4
;
\0
064 073 056 000
(
273
2 7 3 050 0 5 6 0 5 6
252
r
e
;
2 5 2 0 7 3 162 1 4 5
=
j
230
u
2 3 0 0 7 5 152 1 6 5
\0
\0
0 0 0 000
\0
\0
000 000
c
i
143 151
n
k
156 1 5 3
\0
\0
\0
000 000 000
\0
\0
\0
000 000 000
e
s
P
160 1 4 5 1 6 3
\0
\0
\0
\0
\0
\0
\0
000 000 000 000 000 000 000
\0
\0
\0
\0
\0
\0
\0
000 000 000 000 000 000 000
\0
\0
\0
\0
\0
\0
\0
000 000 000 000 000 000 000
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
000 000 000 000 000 000 000 000 000 000
0000100
See t h e f i l e n a m e s b u r i e d in t h e r e ? T h e d i r e c t o r y f o r m a t is a c o m b i n a t i o n of
b i n a r y a n d t e x t u a l d a t a . A d i r e c t o r y c o n s i s t s of 16-byte c h u n k s , t h e last 14
b y t e s o f w h i c h h o l d t h e f i l e n a m e , p a d d e d with ASCII N U L ' s ( w h i c h h a v e v a l u
0 ) a n d the first t w o o f w h i c h tell t h e s y s t e m w h e r e the a d m i n i s t r a t i v e i n f o r m a tion f o r t h e file r e s i d e s w e ' l l c o m e back t o t h a t . E v e r y d i r e c t o r y b e g i n s
with t h e t w o e n t r i e s
( " d o t " ) and
("dot-dot").
$ cd
$ cd recipes
$ pwd
/usr/you/recipes
$ cd . . ; pwd
/usr/you
$ cd . . ; pwd
/usr
$ cd . . ; pwd
/
$ cd . . ; pwd
/
Home
Up one level
Up another level
Up another level
Up another level
Can't go any higher
52
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
Permissions
CHAPTER 2
53
p e r m i s s i o n s g r a n t e d t o y o u r uid a n d g r o u p - i d .
T h e file / e t c / p a s s w d is the password file; it c o n t a i n s all the login i n f o r m a t i o n a b o u t e a c h u s e r . Y o u can d i s c o v e r your uid a n d g r o u p - i d , a s d o e s t h e
system, by looking up your ame in / e t c / p a s s w d :
$ grep you /etc/passwd
you:gkmbCTrJ04C()M: 6 0 4 : 1 : Y . O . A . P e o p l e : / u s r / y o u :
$
shell
5 1 1 5 Aug 3 0 1 0 : 4 0 / e t c / p a s s w d
5 1 1 5 Aug 3 0 1 0 : 4 0 / e t c / p a s s w d
54
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
i n t h e n e x t s e c t i o n ) . S o m e v e r s i o n s o f l s give b o t h o w n e r a n d g r o u p i n o n e
invocation.
T h e s t r i n g - r w - r - - r - - i s h o w l s r e p r e s e n t s the p e r m i s s i o n s o n t h e file.
T h e first - i n d i c a t e s that it is an o r d i n a r y file. If it w e r e a d i r e c t o r y , t h e r e
w o u l d be a d t h e r e . T h e next t h r e e c h a r a c t e r s e n c o d e t h e file o w n e r ' s ( b a s e d
o n uid) r e a d , write and execute permissions. r w - m e a n s that r o o t (the
o w n e r ) m a y r e a d o r w r i t e , but not e x e c u t e t h e f i l e . A n e x e c u t a b l e file w o u l d
h a v e an x instead of a d a s h .
T h e next t h r e e c h a r a c t e r s ( r - ~ ) e n c o d e g r o u p p e r m i s s i o n s , i n this case t h a t
p e o p l e i n g r o u p adra, p r e s u m a b l y the s y s t e m a d m i n i s t r a t o r s , can r e a d t h e file
but not w r i t e o r e x e c u t e it. T h e next t h r e e (also r - - ) d e f i n e t h e p e r m i s s i o n s
f o r e v e r y o n e else t h e rest of the u s e r s on the s y s t e m . On this m a c h i n e ,
t h e n , only r o o t can c h a n g e t h e login i n f o r m a t i o n f o r a u s e r , but a n y b o d y m a y
r e a d t h e file to d i s c o v e r the i n f o r m a t i o n . A p l a u s i b l e a l t e r n a t i v e w o u l d be f o r
g r o u p a d m t o also h a v e w r i t e p e r m i s s i o n o n / e t c / p a s s w d .
T h e file / e t c / g r o u p e n c o d e s g r o u p a m e s a n d g r o u p - i d ' s , a n d d e f i n e s
w h i c h u s e r s a r e i n w h i c h g r o u p s . / e t c / p a s s w d i d e n t i f i e s o n l y y o u r login
group; the n e w g r p command changes your group permissions to another
group.
A n y b o d y can say
$ ed /etc/passwd
a n d edit t h e p a s s w o r d f i l e , but only r o o t can w r i t e back t h e c h a n g e s . Y o u
m i g h t t h e r e f o r e w o n d e r h o w you can c h a n g e y o u r p a s s w o r d , since t h a t i n v o l v e s
e d i t i n g the p a s s w o r d file. T h e p r o g r a m t o c h a n g e p a s s w o r d s i s called p a s s w d ;
you will p r o b a b l y f i n d it in / b i n :
$ ls -1 /bin/passwd
-rwsr-xr-x 1 root
8454 J a n
1983 / b i n / p a s s w d
T H E FILE SYSTEM
CHAPTER 2
55
6 3 4 8 Mar 2 9
1983 / b i n / w h o
w h o i s e x e c u t a b l e b y e v e r y b o d y , a n d w r i t a b l e b y r o o t a n d the o w n e r ' s g r o u p .
W h a t " e x e c u t a b l e " m e a n s i s this: w h e n you t y p e
$ who
to the shell, it looks in a set of d i r e c t o r i e s , o n e of w h i c h is / b i n , f o r a file
n a m e d " w h o . " If it f i n d s such a file, a n d if t h e file h a s e x e c u t e p e r m i s s i o n ,
the shell calis the k e r n e l t o r u n it. T h e k e r n e l c h e c k s t h e p e r m i s s i o n s , a n d , i f
they are v a l i d , r u n s the p r o g r a m . N o t e t h a t a p r o g r a m is j u s t a file with e x e cute p e r m i s s i o n . I n t h e next c h a p t e r w e will s h o w you p r o g r a m s t h a t a r e j u s t
text files, but t h a t can b e e x e c u t e d a s c o m m a n d s b e c a u s e t h e y h a v e e x e c u t e
p e r m i s s i o n set.
D i r e c t o r y p e r m i s s i o n s o p e r a t e a little d i f f e r e n t l y , but t h e b a s i c idea is t h e
same.
$ ls -Id .
d r w x r w x r - x 3 you
80 S e p 27 0 6 : 1 1
create
I n s t e a d t h e r e a r e s y s t e m calis t h a t c r e a t e a n d r e m o v e f i l e s , a n d o n l y t h r o u g h
t h e m is it possible to c h a n g e the c o n t e n t s of a d i r e c t o r y . T h e p e r m i s s i o n s i d e a ,
56
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
permissions filenames
...
T h e s y n t a x of t h e permissions
is c l u m s y , h o w e v e r . T h e y can be s p e c i f i e d in
t w o w a y s , e i t h e r a s octal n u m b e r s o r b y s y m b o l i c d e s c r i p t i o n . T h e octal
n u m b e r s are easier to use, although the symbolic descriptions are sometimes
c o n v e n i e n t b e c a u s e t h e y can s p e c i f y r e l a t i v e c h a n g e s in the p e r m i s s i o n s . It
w o u l d be nice if you could say
$ chmod
rw-rw-rw-
junk
rather than
$ chmod
666
junk
+x command
-w f i l e
t u r n s o f f w r i t e p e r m i s s i o n for e v e r y o n e , i n c l u d i n g t h e f i l e ' s o w n e r . E x c e p t f o r
t h e u s u a l d i s c l a i m e r a b o u t s u p e r - u s e r s , o n l y the o w n e r o f a file m a y c h a n g e t h e
p e r m i s s i o n s on a file, r e g a r d l e s s of t h e p e r m i s s i o n s t h e m s e l v e s . E v e n if s o m e b o d y else allows you to w r i t e a f i l e , t h e s y s t e m will not a l l o w you to c h a n g e its
T H E FILE SYSTEM
CHAPTER 2
57
p e r m i s s i o n bits.
$ ls -Id /usr/mary
drwxrwxrwx 5 mary
704 Sep 25 1 0 : 1 8 / u s r / m a r y
$ chmod 444 /usr/mary
chmod: c a n ' t c h a n g e / u s r / m a r y
$
If a d i r e c t o r y is w r i t a b l e , h o w e v e r , p e o p l e can r e m o v e files in it r e g a r d l e s s of
the p e r m i s s i o n s on t h e files t h e m s e l v e s . If you w a n t to m a k e s u r e that you or
y o u r f r i e n d s n e v e r d e l e t e files f r o m a d i r e c t o r y , r e m o v e w r i t e p e r m i s s i o n f r o m
it:
$ cd
$ date
>temp
$ chmod -w .
$ ls -Id
.
dr-xr-xr-x 3
$ rm temp
rm: temp n o t
$ chmod 775
$ l s -Id
.
drwxrwxr-x 3
$ rm temp
$
80 S e p 27 1 1 : 4 8
t e m p i s n o w g o n e . N o t i c e that c h a n g i n g t h e p e r m i s s i o n s o n t h e d i r e c t o r y
d i d n ' t c h a n g e its m o d i f i c a t i o n d a t e . T h e m o d i f i c a t i o n d a t e r e f l e c t s c h a n g e s t o
t h e f i l e ' s c o n t e n t s , not its m o d e s . T h e p e r m i s s i o n s a n d d a t e s a r e not s t o r e d i n
t h e file itself, but in a s y s t e m s t r u c t u r e called an i n d e x n o d e , or i-node, the
subject of t h e next section.
Exercise 2-5. Experiment with chmod. Try different simple modes, like 0 and 1. Be
careful not to damage your login directory!
2.5
Inodes
58
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
$ date
T u e S e p 27 1 2 : 0 7 : 2 4 EDT 1 9 8 3
$ d a t e >junk
$ ls -1 junk
- r w - r w - r w - 1 you
29 Sep 27 1 2 : 0 7
$ ls -1u j u n k
- r w - r w - r w - 1 you
29 Sep 27 0 6 : 1 1
$ ls -1c junk
- r w - r w - r w - 1 you
29 Sep 27 1 2 : 0 7
$
junk
junk
junk
29 Sep 27 0 6 : 1 1
junk
29 Sep 27 12:11
junk
64 Sep 27 12:11 r e c i p e s
29 Sep 27 0 6 : 1 1 j u n k
r e c i p e s is m o s t r e c e n t l y u s e d , b e c a u s e we j u s t l o o k e d at its c o n t e n t s .
It is i m p o r t a n t to u n d e r s t a n d i n o d e s , not o n l y to a p p r e c i a t e t h e o p t i o n s on
ls, but b e c a u s e in a s t r o n g sense t h e i n o d e s are t h e files. A l l t h e d i r e c t o r y
h i e r a r c h y d o e s i s p r o v i d e c o n v e n i e n t a m e s f o r files. T h e s y s t e m ' s i n t e r n a l
a m e f o r a file is its i-number: the n u m b e r of t h e i n o d e h o l d i n g the f i l e ' s i n f o r m a t i o n . l s - i r e p o r t s the i - n u m b e r i n d e c i m a l :
$ d a t e >x
$ l s -i
15768 j u n k
15274 r e c i p e s
15852 x
$
It is the i - n u m b e r that is s t o r e d in the first t w o b y t e s of a d i r e c t o r y , b e f o r e t h e
CHAPTER 2
59
0000020
273
0000040
252
0000060
230
0000100
354
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
\0
P
\0
\0
\0
\0
\0
0000120
$ od -d
0000000 1 5 1 5 6 0 0 0 4 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0000020
10427
11822
00000
00000
00000
00000
00000
00000
0000040
15274
25970
26979
25968
00115
00000
00000
00000
0000060
15768
30058
27502
00000
00000
00000
00000
00000
0000100
15852
00120
00000
00000
00000
00000
00000
00000
0000120
rm
od
-d
0000000
0000020
0000040
0000060
0000100
0000120
15156
10427
15274
15768
00000
00046
11822
25970
30058
00120
00000
00000
26979
27502
00000
00000
00000
25968
00000
00000
00000
00000
00115
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
00000
old-file new-file
60
CHAPTER 2
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
29 Sep 27 12:07 j u n k
29 Sep 27 1 2 : 0 7 l i n k t o j u n k
64 Sep 27 0 9 : 3 4 r e c i p e s
T h e i n t e g e r p r i n t e d b e t w e e n t h e p e r m i s s i o n s a n d t h e o w n e r i s the n u m b e r o f
links to t h e file. B e c a u s e e a c h link j u s t p o i n t s to t h e i n o d e , e a c h link is e q u a l l y
i m p o r t a n t t h e r e is no d i f f e r e n c e b e t w e e n the first link a n d s u b s e q u e n t o n e s .
( N o t i c e t h a t t h e total disc space c o m p u t e d by ls is w r o n g b e c a u s e of d o u b l e
counting.)
W h e n you c h a n g e a f i l e , access to t h e file by a n y of its a m e s will r e v e a l
t h e c h a n g e s , since all the links point to the s a m e file.
$ e c h o x >junk
$ ls -1
total 3
- r w - r w - r w - 2 you
- r w - r w - r w - 2 you
drwxrwxrwx 4 you
$ rm linktojunk
$ ls -1
total 2
- r w - r w - r w - 1 you
drwxrwxrwx 4 you
$
2 S e p 27 1 2 : 3 7 j u n k
2 Sep 27 12:37 l i n k t o j u n k
64 Sep 27 0 9 : 3 4 r e c i p e s
2 Sep 27 1 2 : 3 7 j u n k
64 Sep 27 0 9 : 3 4 r e c i p e s
T H E FILE SYSTEM
CHAPTER 2
links w o u l d r e f l e c t the c h a n g e .
$ cp
$ ls
total
15850
15768
15274
$
61
c p m a k e s copies o f files:
junk
copyofjunk
-li
3
- r w - r w - r w - 1 you
- r w - r w - r w - 1 you
drwxrwxrwx 4 you
S e p 27 13 1 3 c o p y o f j u n k
S e p 27 12 3 7 j u n k
64 Sep 27 0 9 : 3 4 r e c i p e s
T h e i-numbers o f j u n k and c o p y o f j u n k are different, because they are diff e r e n t f i l e s , even t h o u g h t h e y c u r r e n t l y h a v e the s a m e c o n t e n t s . It's o f t e n a
good idea to c h a n g e t h e p e r m i s s i o n s on a b a c k u p copy so it's h a r d e r to r e m o v e
it a c c i d e n t a l l y .
$ chmod -w copyofjunk
$ ls -li
total 3
15850 - r - - r - - r - - 1
15768 - r w - r w - r w - 1
15274 drwxrwxrwx 4
$ rm copyofjunk
r m : c o p y o f j u n k 444
$ d a t e >junk
$ ls -li
total 3
15850 - r - - r - - r - - 1
15768 - r w - r w - r w - 1
15274 drwxrwxrwx 4
$ rm copyofjunk
r m : c o p y o f j u n k 444
$ l s -li
total 2
15768 - r w - r w - r w - 1
15274 drwxrwxrwx 4
you
you
you
mode n
you
you
you
mode y
you
you
2 Sep 27 1 3 : 1 3 c o p y o f j u n k
2 Sep 27 1 2 : 3 7 j u n k
64 Sep 27 09:34 r e c i p e s
No! It's precious
2 Sep 27 1 3 : 1 3 c o p y o f j u n k
29 Sep 27 13:16 j u n k
64 Sep 27 0 9 : 3 4 r e c i p e s
Well, maybe not so precious
29 Sep 27 13:16 j u n k
64 Sep 27 0 9 : 3 4 r e c i p e s
62
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ mv
$ ls
total
15274
15768
$
junk
sameoldjunk
-li
2
drwxrwxrwx 4 you
- r w - r w - r w - 1 you
CHAPTER 2
64 Sep 27 0 9 : 3 4 r e c i p e s
29 Sep 27 13:16 s a m e o l d j u n k
sh
-Id
/usr/you
junkl
$ cp junk
$ rm junk
junkl
and
Hint: try
CHAPTER 2
63
Exercise 2-8. cp doesn't copy subdirectories, it just copies files at the first level of a
hierarchy. What does it do if one of the argument files is a directory? Is this kind or
even sensible? Discuss the relative merits of three possibilities: an option to cp to descend directories, a separate command r c p (recursive copy) to do the job, or just having
cp copy a directory recursively when it finds one. See Chapter 7 for help on providing
this facility. What other programs would profit from the ability to traverse the directory
tree?
2o6 T h e directory hierarchy
I n C h a p t e r 1 , w e l o o k e d a t t h e file s y s t e m h i e r a r c h y r a t h e r i n f o r m a l l y ,
starting f r o m / u s r / y o u . W e ' r e now going to investigate it in a more orderly
w a y , s t a r t i n g f r o m t h e t o p o f t h e t r e e , the r o o t .
T h e top directory is /.
$ ls
bin
boot
dev
etc
lib
tmp
unix
usr
$
64
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
CHAPTER 2
T H E FILE SYSTEM
65
T h e r e i s a p r o b l e m , o f c o u r s e , w h e n several p r o g r a m s c r e a t e files i n / t m p
a t o n c e : t h e y m i g h t i n t e r f e r e with each o t h e r ' s files. T h a t i s w h y e d ' s t e m p o r a r y file h a s a p e c u l i a r a m e : it is c o n s t r u c t e d in such a w a y as to g u a r a n t e e
t h a t n o o t h e r p r o g r a m will c h o o s e the s a m e a m e f o r its t e m p o r a r y file. I n
C h a p t e r s 5 a n d 6 we will see w a y s to do this.
/ u s r i s called t h e " u s e r file s y s t e m , " a l t h o u g h i t m a y h a v e little t o d o with
t h e a c t u a l u s e r s o f t h e s y s t e m . O n our m a c h i n e , o u r login d i r e c t o r i e s a r e
/ u s r / b w k a n d / u s r / r o b , but o n y o u r m a c h i n e t h e / u s r p a r t m i g h t b e d i f f e r e n t , as e x p l a i n e d in C h a p t e r 1. W h e t h e r or not y o u r p e r s o n a l files a r e in a
s u b d i r e c t o r y o f / u s r , t h e r e are a n u m b e r o f t h i n g s you a r e likely t o f i n d t h e r e
( a l t h o u g h local c u s t o m s v a r y i n this r e g a r d , t o o ) . Just a s i n / , t h e r e a r e d i r e c t o r i e s called / u s r / b i n , / u s r / l i b a n d / u s r / t m p . T h e s e d i r e c t o r i e s h a v e
f u n c t i o n s similar t o their n a m e s a k e s i n / , but c o n t a i n p r o g r a m s less critical t o
the system. For example, n r o f f i s usually i n / u s r / b i n rather than / b i n ,
a n d t h e F O R T R A N c o m p i l e r libraries live i n / u s r / l i b . O f c o u r s e , just w h a t
i s d e e m e d " c r i t i c a l " vares f r o m s y s t e m t o s y s t e m . S o m e s y s t e m s , such a s t h e
d i s t r i b u t e d 7th E d i t i o n , h a v e all the p r o g r a m s i n / b i n a n d d o a w a y with
/ u s r / b i n a l t o g e t h e r ; o t h e r s split / u s r / b i n i n t o t w o d i r e c t o r i e s a c c o r d i n g t o
frequency of use.
Other directories i n / u s r are / u s r / a d m , containing accounting information a n d / u s r / d i c t , w h i c h h o l d s a m o d e s t d i c t i o n a r y (see s p e l l ( l ) ) . T h e
on-line m a n u a l i s k e p t i n / u s r / m a n see / u s r / m a n / m a n 1 / s p e l l . 1 , for
e x a m p l e . If y o u r s y s t e m h a s s o u r c e c o d e o n - l i n e , you will p r o b a b l y f i n d it in
/usr/src.
I t i s w o r t h s p e n d i n g a little t i m e e x p l o r i n g t h e file s y s t e m , especially / u s r ,
to d e v e l o p a f e e l i n g f o r h o w t h e file s y s t e m is o r g a n i z e d a n d w h e r e you m i g h t
expect t o f i n d t h i n g s .
2.7
Devices
W e s k i p p e d o v e r / d e v i n o u r t o u r , b e c a u s e t h e files t h e r e p r o v i d e a nice
r e v i e w o f files i n g e n e r a l . A s you m i g h t g u e s s f r o m t h e a m e , / d e v c o n t a i n s
device files.
O n e of t h e prettiest i d e a s in t h e U N I X s y s t e m is t h e w a y it d e a l s with peripherals discs, t a p e d r i v e s , line p r i n t e r s , t e r m i n i s , e t c . R a t h e r t h a n h a v i n g
special s y s t e m r o u t i n e s t o , for e x a m p l e , r e a d m a g n e t i c t a p e , t h e r e is a file
called / d e v / m t O ( a g a i n , local c u s t o m s v a r y ) . I n s i d e t h e k e r n e l , r e f e r e n c e s t o
t h a t file a r e con v e r t e d i n t o h a r d w a r e c o m m a n d s to access t h e t a p e , so if a p r o g r a m r e a d s / d e v / m t O , the c o n t e n t s o f a t a p e m o u n t e d o n the d r i v e a r e
returned. For example,
$ cp /dev/mtO
junk
66
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
root
root
root
root
root
root
root
root
root
root
root
you
root
root
root
0,
3,
3,
1,
3,
4,
2,
2,
13,
13,
2,
1,
1,
1,
1,
0
1
0
64
2
64
0
1
0
1
0
0
1
2
3
Sep
Sep
May
Aug
Sep
Sep
Sep
Sep
Apr
Jul
Jul
Sep
Sep
Sep
Sep
27
27
6
24
28
9
8
27
12
28
5
28
27
27
27
23:09
14:37
1981
17:41
02:03
15:42
08:07
23:09
1983
1 5 : 18
08:04
02:38
23:09
17:33
18:48
consol
kmem
mem
mtO
nuil
rmtO
rpOO
rpO 1
rrpOO
rrpO 1
tty
ttyO
tty 1
tty2
tty3
CHAPTER 2
T H E FILE SYSTEM
67
$ /etc/mount
r p O 1 on / u s r
$
I n o u r c a s e , t h e r o o t s y s t e m occupies / d e v / r p O O ( a l t h o u g h this isn't r e p o r t e d
b y / e t c / m o u n t ) while the user file s y s t e m t h e files i n / u s r a n d its s u b directories reside on / d e v / r p O 1.
T h e r o o t file s y s t e m h a s t o b e p r e s e n t f o r t h e s y s t e m t o e x e c u t e . / b i n ,
/ d e v a n d / e t c are a l w a y s k e p t o n the r o o t s y s t e m , b e c a u s e w h e n t h e s y s t e m
s t a r t s only files in t h e r o o t s y s t e m are accessible, a n d s o m e files such as
/ b i n / s h are n e e d e d t o r u n a t all. D u r i n g the b o o t s t r a p o p e r a t i o n , all t h e file
s y s t e m s a r e c h e c k e d for self-consistency (see i c h e c k ( 8 ) o r f s c k ( 8 ) ) , a n d
a t t a c h e d t o t h e r o o t s y s t e m . T h i s a t t a c h m e n t o p e r a t i o n i s called m o u n t i n g , t h e
s o f t w a r e e q u i v a l e n t of m o u n t i n g a n e w disc pack in a d r i v e ; it can n o r m a l l y be
d o n e o n l y b y t h e s u p e r - u s e r . A f t e r / d e v / r p O 1 h a s been m o u n t e d a s / u s r ,
t h e files in t h e user file s y s t e m are accessible exactly as if t h e y w e r e p a r t of t h e
root system.
F o r t h e a v e r a g e u s e r , the d e t a i l s o f w h i c h file s u b s y s t e m i s m o u n t e d w h e r e
a r e of little i n t e r e s t , but t h e r e a r e a c o u p l e of r e l e v a n t p o i n t s . F i r s t , b e c a u s e
t h e s u b s y s t e m s m a y be m o u n t e d a n d d i s m o u n t e d , it is illegal to m a k e a link to
a file in a n o t h e r s u b s y s t e m . F o r e x a m p l e , it is impossible to link p r o g r a m s in
/ b i n to convenient a m e s in prvate b i n directories, because / u s r is in a diff e r e n t file s u b s y s t e m f r o m / b i n :
$ ln /bin/mail
/usr/you/bin/m
ln: Cross-device link
$
T h e r e w o u l d also be a p r o b l e m b e c a u s e i n o d e n u m b e r s are not u n i q u e in d i f f e r e n t file s y s t e m s .
S e c o n d , e a c h s u b s y s t e m h a s fixed u p p e r limits o n size ( n u m b e r o f b l o c k s
a v a i l a b l e f o r files) a n d i n o d e s . If a s u b s y s t e m filis u p , it will be i m p o s s i b l e to
e n l a r g e files i n t h a t s u b s y s t e m until s o m e space i s r e c l a i m e d . T h e d f (disc
f r e e space) c o m m a n d r e p o r t s t h e available space o n t h e m o u n t e d file subsystems:
$ df
/ d e v / r p O O 1989
/ d e v / r p O 1 21257
$
/ u s r h a s 21257 f r e e b l o c k s . W h e t h e r this i s a m p i e space o r a crisis d e p e n d s
o n h o w t h e s y s t e m i s u s e d ; s o m e i n s t a l l a t i o n s n e e d m o r e file space h e a d r o o m
t h a n o t h e r s . B y the w a y , o f all t h e c o m m a n d s , d f p r o b a b l y h a s t h e widest
v a r i a t i o n i n o u t p u t f o r m a t . Y o u r d f o u t p u t m a y look q u i t e d i f f e r e n t .
L e t ' s t u r n n o w t o s o m e m o r e g e n e r a l l y u s e f u l t h i n g s . W h e n you log in, you
get a t e r m i n a l line a n d t h e r e f o r e a file in / d e v t h r o u g h which t h e c h a r a c t e r s
68
CHAPTER 2
$ who am i
you
ttyO
Sep 28 0 1 : 0 2
$ tty
/dev/ttyO
$ ls -1 /dev/ttyO
crww--w- 1 you
1, 12 Sep 28 0 2 : 4 0 / d e v / t t y O
$ d a t e >/dev/tty0
Wed S e p 28 0 2 : 4 0 : 5 1 EDT 1983
$
N o t i c e t h a t you o w n the device, a n d t h a t only you are p e r m i t t e d t o r e a d it. I n
o t h e r w o r d s , n o o n e else c a n directly r e a d the c h a r a c t e r s you a r e t y p i n g . A n y o n e m a y w r i t e o n y o u r t e r m i n a l , h o w e v e r . T o p r e v e n t t h i s , you c o u l d c h m o d
the d e v i c e , t h e r e b y p r e v e n t i n g p e o p l e f r o m u s i n g w r i t e t o c o n t a c t y o u , o r you
could just use m e s g .
$ mesg n
$ ls -1 /dev/ttyO
crw
1 you
$ mesg y
12 Sep 28 0 2 : 4 1 / d e v / t t y O
Restore
I t i s o f t e n u s e f u l t o b e able t o r e f e r b y a m e t o t h e t e r m i n a l you a r e u s i n g ,
but it's i n c o n v e n i e n t to d e t e r m i n e which o n e it is. T h e device / d e v / t t y is a
s y n o n y m for y o u r login t e r m i n a l , w h a t e v e r t e r m i n a l you are actually u s i n g .
$ d a t e >/dev/tty
Wed S e p 28 0 2 : 4 2 : 2 3 EDT 1 9 8 3
$
/ d e v / t t y i s p a r t i c u l a r l y u s e f u l w h e n a p r o g r a m n e e d s t o i n t e r a c t with a u s e r
e v e n t h o u g h its s t a n d a r d input a n d o u t p u t a r e c o n n e c t e d t o files r a t h e r t h a n t h e
terminal,
c r y p t i s o n e p r o g r a m that u s e s / d e v / t t y .
The "clear text"
c o m e s f r o m t h e s t a n d a r d i n p u t , a n d t h e e n c r y p t e d d a t a g o e s t o the s t a n d a r d
o u t p u t , s o c r y p t r e a d s the e n c r y p t i o n k e y f r o m / d e v / t t y :
$ crypt
<cleartext
Enter key:
>cryptedtext
Type encryption key
T H E FILE SYSTEM
CHAPTER 2
69
>/dev/null
/usr/dict/words
-r--r~-r-- 1 bin
$ time
grep
real
user
sys
$ time
real
user
sys
196513 Jan 20
e /usr/dict/words
1979 /usr/dict/words
>/dev/null
13.0
9.0
2.7
egrep
e /usr/dict/words
>/dev/null
8.0
3.9
2.8
The n u m b e r s in the output of t i m e are elapsed clock time, CPU time spent in
the program and CPU time spent in the kernel while the program was r u n n i n g .
e g r e p is a high-powered variant of g r e p that we will discuss in Chapter 4; it's
about twice as fast as g r e p when searching through large files. If output f r o m
g r e p and e g r e p had not been sent to / d e v / n u l l or a real file, we would
have had to wait for h u n d r e d s of thousands of characters to appear on the terminal before finding out the timing information we were after.
Exercise 2-9. Find out about the other files in / d e v by reading Section 4 of the
manual. What is the difference between / d e v / m t O and / d e v / r m t O ? Comment on
the potential advantages of having subdirectories in / d e v for discs, tapes, etc.
Exercise 2-10. Tapes written on non-UNix systems often have different block sizes, such
as 800 bytes ten 80-character card images but the tape device / d e v / m t O expects
512-byte blocks. Look up the dd command (dd(l)) to see how to read such a tape.
Exercise 2-11. Why isn't / d e v / t t y just a link to your login terminal? What would
happen if it were mode r w - - w - - w - like your login terminal?
Exercise 2-12. How does w r i t e ( l ) work? Hint: see utmp(5).
Exercise 2-13. How can you tell if a user has been active at the terminal recently?
70
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 2
CHAPTER 3:
you
jpl
tty2
tty4
Sep 28 07:51
Sep 28 08:32
72
CHAPTER 3
$ date;
who
who
who
I wc
10
60
This might not be what you expected, because only the output of w h o goes to
wc. Connecting who and wc with a pipe forms a single c o m m a n d , called a
pipeline, that runs after d a t e . T h e precedence of ! is higher than that of
as the shell parses your command line.
Parentheses can be used to group c o m m a n d s :
$
(date;
who)
(date;
who)
I wc
16
89
T h e outputs of d a t e and who are concatenated into a single stream that can be
sent down a pipe.
Data flowing through a pipe can be tapped and placed in a file (but not
another pipe) with the t e e c o m m a n d , which is not part of the shell, but is
nonetheless handy for manipulating pipes. O n e use is to save intermedate output in a file:
USING T H E S H E L L
CHAPTER 3
$ (date;
who) ! tee save / wc
3
16
89
$ cat save
Wed Sep 28 09:13:22 EDT 1983
you
tty2
Sep 28 07:51
jpl
tty4
Sep 28 08:32
$ wc <save
3
16
89
73
Output from wc
&
Process-id of long-running-command
Prompt appears immediately
Given the ability to group c o m m a n d s , there are some more interesting uses of
background processes. The command s l e e p waits the specified number of
seconds b e f o r e exiting:
$ sleep
5
Five seconds pass before prompt
$ (sleep
5; date)
& date
5278
Wed Sep 28 09:18:20 EDT 1983
$ Wed Sep 28 09:18:25 EDT 1983
300;
echo
Tea is
ready)
&
74
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ pr
file
! lpr
CHAPTER 3
&
arranges to print the file on the line printer without making you wait for the
command to finish. Parenthesizing the pipeline has the same effect, but
requires more typing:
$
(pr
file
I lpr) &
Helio
>junk
tells the shell to run e c h o with the single argument H e l i o , and place the output in the file j u n k . The string > j u n k is not an argument to e c h o ; it is
interpreted by the shell and never seen by e c h o . In fact, it need not be the
last string in the command:
$ >junk
echo
Helio
(Over the years the redirection operator < has lost some ground to pipes; people seem to
find " c a t f i l e !" more natural than " < f i l e " . )
3.2 Metacharacters
The shell recognizes a number of other characters as special; the most commonly used is the asterisk * which tells the shell to search the directory for
filenames in which any string of characters occurs in the position of the *. For
example,
$ echo
US1NG T H E S H E L L
CHAPTER 3
75
do that!"
Don't do that!
$
76
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 3
<<str
*
?
[ ccc ]
9
&
x
... x
( . . . )
{...}
$1, $ 2 etc.
$var
${var}
\
' . . . '
IV
11
#
var= valu
P 1 && P2
Pi ' ' Pi
In this last example, because the quotes are discarded after they've done their
j o b , e c h o sees a single argument containing no quotes.
Q u o t e d strings can contain newlines:
$ echo
'helio
> worid'
helio
world
$
T h e string '> ' is a secondary prompt printed by the shell when it expects you
to type m o r e input to complete a c o m m a n d . In this example the quote on the
first line has to be balanced with another. T h e secondary promnt string is
stored in the shell variable P S 2 , and can be modified to taste.
In all of these examples, the quoting of a metacharacter prevents the shell
f r o m trying to interpret it. The command
USING T H E S H E L L
CHAPTER 3
$ echo
77
x*y
A backslash at the end of a line causes the line to be continued; this is the
way to present a very long line to the shell.
$ echo abc\
> def\
> ghi
abcdefghi
$
Notice that the newline is discarded when preceded by backslash, but is
retained when it appears in quotes.
T h e metacharacter # is almost universally used for shell comments; if a
shell word begins with #, the rest of the line is ignored:
$ echo helio
# there
helio
$ echo hello#there
hello#there
$
T h e # was not part of the original 7th Edition, but it has been adopted very
widely, and we will use it in the rest of the book.
Exercise 3-2. Explain the output produced by
$
ls
.*
A digressiott on e c h o
Even though it isn't explicitly asked f o r , a final newline is provided by
e c h o . A sensible and perhaps cleaner design for e c h o would be to print only
78
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 3
No trailing newline
but has the disadvantage that the most common case providing a newline
is not the default and takes extra typing:
$ pure-echo
>
'Helio!
'
Helio!
$
-n
'-n
System V versin
Although this mechanism avoids confusion about echoing a minus sign, it has
other problems. e c h o is often used as a diagnostic aid, and backslashes are
interpreted by so many p r o g r a m s that having e c h o look at them too just adds
to the confusion.
Still, both designs of e c h o have good and bad points. We shall use the 7th
Edition versin ( - n ) , so if your local e c h o obeys a different convention, a
couple of our programs will need minor revisin.
A n o t h e r question of philosophy is what e c h o should do if given no arguments specifically, should it print a blank line or nothing at all? All the
current e c h o implementations we know print a blank line, but past versions
d i d n ' t , and there weire once great debates on the subject. Doug Mcllroy
imparted the right feelings of mysticism in his discussion of the topic:
CHAPTER 3
USING T H E S H E L L
79
But they say that he died of a surfeit of notation before he ever heard
Exercise 3-3. Predict what each of the following g r e p commands will do, then verify
your understanding.
grep
grep
grep
grep
grep
\$
\\$
\\\$
'\$'
'\'$
grep
grep
grep
grep
grep
\\
\\\\
"\$"
"$"
A file containing these commands themselves makes a good test case if you want to
experiment.
Exercise 3-4. How do you tell g r e p to search for a pattern beginning with a ' - ' ? Why
doesn't quoting the argument help? Hint: investgate the -e option.
Exercise 3-5. Consider
$ echo
*/*
Does this produce all ames in all directories? In what order do the ames appear?
Exercise 3-6. (Trick question) How do you get a / into a filename (i.e., a / that
doesn't separate components of the path)?
Exercise 3-7. What happens with
80
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ cat
CHAPTER 3
x y >y
and with
$ c a t x >>x
Think before rushing off to try them.
Exercise 3-8. If you type
$ rm *
why can't rm warn you that you're about to delete all your files?
3 . 3 Creating new commands
It's now time to move on to something that we promised in C h a p t e r
how to create new c o m m a n d s out of od ones.
Given a sequence of c o m m a n d s that is to be repeated m o r e than a
times, it would be convenient to make it into a " n e w " c o m m a n d with its
a m e , so you can use it like a regular c o m m a n d . To be specific, suppose
intend to count users frequently with the pipeline
$ who
1
few
own
you
I wc -1
'who
I wc -1'
>nu
you
rhh
moh
ava
$ cat nu
who ! wc
$ sh <nu
4
tty2
tty4
tty5
tty6
Sep
Sep
Sep
Sep
28
28
28
28
07:: 51
10:: 02
09:: 38
10 : 17
-1
CHAPTER 3
81
+x nu
82
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 3
your environment to your own taste. Some that we have found convenient
include
e s , which echoes the proper sequence of mysterious characters to clear the
screen on your terminal (24 newlines is a fairly general implementation);
w h a t , which runs who and ps -a to tell who's logged on and what they are
doing;
w h e r e , which prints the identifying a m e of the UNIX system y o u ' r e using
it's handy if you use several regularly. (Setting PS 1 serves a similar
purpose.)
Exercise 3-9. Look in / b i n and / u s r / b i n to see how many commands are actually
shell files. Can you do it with one command? Hint: f i l e ( l ) . How accurate are
guesses based on file length?
3 . 4 Command arguments and parameters
Although nu is adequate as it stands, most shell p r o g r a m s interpret arguments, so that, for example, filenames and options can be specified when the
program is run.
Suppose we want to m a k e a program called ex to change the m o d e of a file
to executable, so
$ ex
nu
is a shorthand for
$ chmod
+x nu
chmod +x filename
T h e only new thing we need to know is how to tell ex what the a m e of the
file is, since it will be different each time ex is r u n .
W h e n the shell executes a file of c o m m a n d s , each occurrence of $1 is
replaced by the first a r g u m e n t , each $2 is replaced by the second a r g u m e n t ,
and so on through $ 9 . So if the file ex contains
chmod +x $1
when the c o m m a n d
$ ex nu
is r u n , the sub-shell replaces " $ 1 " by its first a r g u m e n t , " n u . "
Let's look at the whole sequence of operations:
USING T H E S H E L L
CHAPTER 3
$ echo
'chmod
+x $1' >cx
$ sh ex ex
$ echo echo Hi, there!
>hello
$ helio
helio: cannot execute
$ ex helio
$ helio
Hi, there!
$ mv ex /usr/you/bin
$ rm helio
83
Create ex originally
Make ex itself executable
Make a test program
Try it
Make it executable
Try again
It works
Install ex
Clean up
N o t i c e t h a t w e said
$ s h ex
ex
e x a c t l y a s t h e shell w o u l d h a v e a u t o m a t i c a l l y d o n e i f e x w e r e a l r e a d y e x e c u t able a n d w e t y p e d
$ ex
ex
W h a t i f you w a n t t o h a n d l e m o r e t h a n o n e a r g u m e n t , f o r e x a m p l e t o m a k e
a p r o g r a m like ex h a n d l e s e v e r a l files at o n c e ? A c r u d e first cut is to put n i n e
a r g u m e n t s i n t o t h e shell p r o g r a m , as in
chmod +x $1 $2 $3 $4 $5 $6 $7 $8 $9
(It o n l y w o r k s u p t o $ 9 , b e c a u s e t h e string $ 1 0 i s p a r s e d a s " f i r s t a r g u m e n t ,
$ 1 , f o l l o w e d by a 0 " ! ) If t h e user of this shell file p r o v i d e s f e w e r t h a n n i n e
a r g u m e n t s , the missing o n e s are nuil strings; the e f f e c t i s t h a t o n l y t h e a r g u m e n t s t h a t w e r e actually p r o v i d e d a r e p a s s e d t o c h m o d b y the s u b - s h e l l . S o
this i m p l e m e n t a t i o n w o r k s , but it's o b v i o u s l y u n c l e a n , a n d it fails if m o r e t h a n
nine a r g u m e n t s are provided.
A n t i c i p a t i n g this p r o b l e m , t h e shell p r o v i d e s a s h o r t h a n d $ * t h a t m e a n s " a l l
the a r g u m e n t s . " T h e p r o p e r w a y t o d e f i n e e x , t h e n , i s
chmod +x $*
which w o r k s regardless of how m a n y a r g u m e n t s are provided.
W i t h $ * a d d e d t o y o u r r e p e r t o i r e , you can m a k e s o m e c o n v e n i e n t shell
files, such a s l e o r m :
$ cd /usr/you/bin
$ cat le
# l e : c o u n t number o f l i n e s i n f i l e s
wc - 1 $*
$ cat m
# m : a c o n c i s e way t o t y p e m a i l
m a i l $*
$
I f t h e r e are n o a r g u m e n t s , $ *
84
CHAPTER 3
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ ls
With or
/usr/you/bin/*
1 /usr/you/bin/cx
2 /usr/you/bin/lc
2 /usr/you/bin/m
1 /usr/you/bin/nu
2 /usr/you/bin/what
1 /usr/you/bin/where
9 total
/usr/you/bin
I le
6
T h e s e c o m m a n d s a n d the o t h e r s in this c h a p t e r
p r o g r a m s , t h e sort o f t h i n g s you w r i t e f o r y o u r s e l f
a r e u n l i k e l y t o m a k e publicly available b e c a u s e t h e y
s o n a l t a s t e . In C h a p t e r 5 we will a d d r e s s t h e issues
are e x a m p l e s of personal
a n d put i n y o u r b i n , but
are too dependent on perof w r i t i n g shell p r o g r a m s
>411
Something i s wrong
T h e final e x a m p l e i s i n c l u d e d t o s h o w a p o t e n t i a l p r o b l e m : even t h o u g h d o w
j o n e s is p r e s e n t e d to 4 1 1 as a single a r g u m e n t , it c o n t a i n s a space a n d is no
USING T H E S H E L L
CHAPTER 3
85
/usr/you/lib/phone-book
212-976-4141
...
with - y , lower case letters in pattern will also match upper case letters in the
input. (This option is in 7th Edition g r e p , but is absent f r o m some other systems.)
T h e r e are fine points about command a r g u m e n t s that we are skipping over
until C h a p t e r 5, but one is worth noting here. The a r g u m e n t $0 is the a m e
of the program being executed in e x , $0 is " e x . " A novel use of $0 is in
the implementation of the p r o g r a m s 2, 3, 4, . . . , which print their output in
that many columns:
$ who I 2
drh
ttyO
dmr
tty6
you
tty9
Sep 28 21:23
Sep 28 22:10
Sep 28 23:00
cvw
sej
jlb
tty5
tty7
ttyb
Sep 28 21:09
Sep 28 22:11
Sep 28 19:58
The implementations of 2, 3, ... are identical; in fact they are links to the
same file:
$ ln 2 3; ln 2 4;
$ l s - 1 1 [ 1-9]
16722 -rwxrwxrwx
16722 -rwxrwxrwx
16722 -rwxrwxrwx
16722 -rwxrwxrwx
16722 -rwxrwxrwx
ln
5
5
5
5
5
2 5; ln
you
you
you
you
you
2 6
51
51
51
51
51
Sep
Sep
Sep
Sep
Sep
28
28
28
28
28
23:21
23:21
23:21
23:21
23:21
2
3
4
5
6
86
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ ls /usr/you/bin
2
6
what
$ cat 5
# 2 , 3,
pr -$0 -t -11
$
I 5
3
ex
where
CHAPTER 3
4
le
411
m
5
nu
print in n columns
$*
T h e -t option turns off the heading at the top of the page and the -1 n option
sets the page length to n lines. The ame of the p r o g r a m becomes the
number-of-columns argument to p r , so the output is printed a row at a time in
the n u m b e r of columns specified by $ 0 .
3.5 P r o g r a m output as arguments
Let us turn now f r o m c o m m a n d a r g u m e n t s within a shell file to the generation of a r g u m e n t s . Certainly filename expansin f r o m metacharacters like * is
the most common way to generate arguments (other than by providing t h e m
explicitly), but another good way is by running a p r o g r a m . The output of any
p r o g r a m can be placed in a command line by enclosing the invocation in backquotes \ . . x :
$ echo At the tone the time will
be 'date'.
At the tone the time will be Thu Sep 29 00:02:15 EDT 1983.
$
A small change illustrates that
'cat mailinglist'
<letter
This r u n s c a t to produce the list of user a m e s , and those become the arguments to m a i l . ( W h e n interpreting output in backquotes as a r g u m e n t s , the
shell treats newlines as word separators, not command-line terminators; this
subject is discussed fully in Chapter 5.) Backquotes are easy enough to use
that there's really no need for a separate mailing-list option to the m a i l command.
A slightly different approach is to convert the file m a i l i n g l i s t f r o m just
a list of a m e s into a program that prints the list of ames:
CHAPTER 3
USING T H E S H E L L
$ cat mailinglist
echo don whr ejs mb
$ ex mailinglist
$ mailinglist
don whr ejs mb
$
87
New versin
'mailinglist'
<letter
arguments ...
presents the arguments one at a time and waits after each for a response. T h e
output of p i c k is those a r g u m e n t s selected by y (for " y e s " ) responses; any
other response causes the argument to be discarded. For example,
$ pr ' p i c k #.c' I lpr
presents each filename that ends in . c ; those selected are printed with pr and
l p r . ( p i c k is not part of the 7th Edition, but it's so easy and useful that
we've included versions of it in Chapters 5 and 6.)
Suppose you have the second versin of m a i l i n g l i s t . Then
$ mail
don? y
whr?
ejs?
mb? y
$
*pick
\*mailinglist\*'
<letter
sends the letter to d o n and mb. Notice that there are nested backquotes; the
backslashes prevent the interpretation of the inner
during the parsing of
the outer one.
Exercise 3-10. If the backslashes are omitted in
$ echo 'echo \'date\''
what happens?
Exercise 3-11. Try
$ 'date'
and explain the result.
Exercise 3-12.
$ grep -1 pattern filenames
lists the filenames in which there was a match of pattern, but produces no other output.
Try some variations on
88
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ command
'grep
CHAPTER 3
-1 pallern filenames*
Restore it
Not all variables are special to the shell. You can create new variables by
assigning them vales; traditionally, variables with special m e a n i n g are spelled
in upper case, so ordinary ames are in lower case. O n e of the common uses
of variables is to r e m e m b e r long strings such as p a t h n a m e s :
$ pwd
/usr/you/bin
$ dir=xpwd'
$ cd /usr/mary/bin
$ ln $dir/cx .
$
...
$ cd $dir
$ pwd
/usr/you/bin
$
T h e shell built-in c o m m a n d s e t displays the vales of all your defined variables. To see just one or two variables, e c h o is more appropriate.
CHAPTER 3
USING T H E S H E L L
89
$ se t
HOME=/usr/you
IFS=
PATH=:/usr/you/bin:/bin:/usr/bin
PS1 = $
PS2 = >
dir=/usr/you/bin
$ echo $dir
/usr/you/bin
$
The valu of a variable is associated with the shell that creates it, and is not
automatically passed to the shell's children.
$ x=Hello
$ sh
$ echo $x
$ ctl-d
$
$ echo
Helio
$
Create x
New shell
$x
x still defined
This mear.s that a shell file cannot change the valu of a variable, because the
shell file is run by a sub-shell:
$ echo 'x="Good Bye"
> echo $x' >setx
$ cat setx
x="Good Bye"
echo $x
$ echo $x
Helio
$ sh setx
Good Bye
$ echo $x
Helio
$
There are times when using a shell file to change shell variables would be
useful, h o w e v e r . An obvious example is a file to add a new directory to your
PATH. T h e shell t h e r e f o r e provides a c o m m a n d
(dot) that executes the
commands in a file in the current shell, rather than in a sub-shell. This was
originally invented so people could conveniently re-execute their . p r o f i l e
files without having to log in again, but it has other uses:
90
T H E UNIX P R O G R A M M I N G E N V 1 R O N M E N T
CHAPTER 3
$ cat /usr/you/bin/games
PATH=$PATH:/usr/games
Append /usr/games to PATH
$ echo $PATH
:/usr/you/bin:/bin:/usr/bin
$ . games
$ echo $PATH
:/usr/you/bin:/bin:/usr/bin:/usr/games
$
T h e file for the
c o m m a n d is searched for with the PATH m e c h a n i s m , so it
can be placed in your b i n directory.
W h e n a file is executing with
it is only superficially like r u n n i n g a shell
file. T h e file is not " e x e c u t e d " in the usual sense of the w o r d . Instead, the
c o m m a n d s in it are interpreted exactly as if you had typed them interactively
the standard input of the shell is temporarily redirected to come f r o m the
file. Since the file is read but not executed, it need not have execute permissions. A n o t h e r difference is that the file does not receive c o m m a n d line arguments; instead, $ 1 , $2 and the rest are empty. It would be nice if a r g u m e n t s
were passed, but they are not.
T h e other way to set the valu of a variable in a sub-shell is to assign to it
explicitly on the c o m m a n d line befare the c o m m a n d itself:
$ echo 'echo $x'
$ ex echox
$ echo $x
Helio
$ echox
>echox
As before
x not set in sub-shell
$ x=Hi
Hi
echox
Valu of x passed to sub-shell
the
perAs
the
USING T H E S H E L L
CHAPTER 3
91
$ echo $PATH
:/usr/you/bin:/bin:/usr/bin
PATH unchanged
$ cat /usr/you/bin/games
PATH=$PATH:/usr/games
games command still there
$ . games
$ fortune
Premature optimization is the root of all evil - Knuth
$ echo $PATH
: /usr/you/bin: /bin: /usr/bin: /usr/games
PATH changed this time
$
It's possible to exploit both these mechanisms in a single shell file. A
slightly different games c o m m a n d can be used to run a single game without
changing PATH, or can set PATH permanently to include /usr/games:
$ cat /usr/you/bin/games
PATH=$PATH:/usr/games $*
Note the $*
$ ex /usr/you/bin/games
$ echo $PATH
: /usr/you/bin: /bin: /usr/bin
Doesn't have /usr/games
$ games fortune
I'd give my right arm to be ambidextrous.
$ echo $PATH
: /usr/you/bin: /bin: /usr/bin
Still doesn't
$ . games
$ echo $PATH
:/usr/you/bin:/bin:/usr/bin:/usr/games
Now it does
$ fortune
He who hesitates is sometimes saved.
$
The first cali to games ran the shell file in a sub-shell, where PATH was temporarily modified to include /usr/games. The second example instead interpreted the file in the current shell, with $* the empty string, so there was no
command on the line, and PATH was modified. Using games in these two
ways is tricky, but results in a facility that is convenient and natural to use.
When you want to make the valu of a variable accessible in sub-shells, the
shell's e x p o r t command should be used. (You might think about why there
is no way to export the valu of a variable f r o m a sub-shell to its parent.)
Here is one of our earlier examples, this time with the variable e x p o r t e d :
$ x=Hello
$ export x
$ sh
$ echo $x
Helio
New shell
x known in sub-shell
92
$ x='Good Bye
$ echo $x
Good Bye
$ ctl-d
CHAPTER 3
$ echo $x
Helio
$
x still Helio
Where
1.0
0.4
0.4
22691 ch3.1
CHAPTER 3
$ time
real
user
sys
USING T H E S H E L L
wc ch3.1
>wc.out
2.0
0.4
0.3
$ time wc ch3.
$ cat time.out
real
user
sys
93
1 >wc.out
2>time.out
1.0
0.4
0.3
The construction 2>filename (no spaces are allowed between the 2 and the >)
directs the standard error output into the file; it's syntactically graceless but it
does the j o b . ( T h e times produced by t i m e are not very accurate for such a
short test as this one, but for a sequence of longer tests the n u m b e r s are useful
and reasonably trustworthy, and you might well want to save them for f u r t h e r
analysis; see, for example, Table 8.1.)
It is also possible to merge the two output streams:
$ time
wc ch3.1
$ cat wc.out
931
4288
real
user
sys
>wc.out
2>&1
22691 ch3.1
1.0
0.4
0.3
The notation 2>&1 tells the shell to put the standard error on the same stream
as the standard output. T h e r e is not much m n e m o n i c valu to the a m p e r s a n d ;
it's simply an idiom to be learned. You can also use 1>&.2 to add the standard
output to the standard error:
echo ... 1>&2
prints on the standard e r r o r . In shell files, it prevents the messages f r o m vanishing accidentally down a pipe or into a file.
T h e shell provides a mechanism so you can put the standard input for a
c o m m a n d along with the c o m m a n d , rather than in a separate file, so the shell
file can be completely self-contained. Our directory information p r o g r a m 4 1 1
could be written
94
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 3
$ cat 411
grep "$*" <<End
dial-a-joke 212-976-3838
dial-a-prayer 212-246-4200
dial santa 212-976-3636
dow jones report 212-976-4141
End
$
T h e shell jargon for this construction is a here document; it m e a n s that the
input is right here instead of in a file s o m e w h e r e . The << signis the construction; the word that follows (End in our example) is used to delimit the input,
which is taken to be everything up to an occurrence of that word on a line by
itself. T h e shell substitutes for $, x . . . \ and \ in a here d o c u m e n t , unless
some part of the word is quoted with quotes or a backslash; in that case, the
whole document is taken literally.
We'll return to here documents at the end of the chapter, with a much m o r e
interesting example.
Table 3.2 lists the various input-output redirections that the shell u n d e r stands.
Exercise 3-14. Compare the here-document versin of 411 with the original. Which is
easier to maintain? Which is a better basis for a general service?
Table 3.2: Shell I/O Redirections
>file
> >file
<file
PvPi
/v
n>file
n>>file
n>SL/n
n<S,.m
<<s
<<\s
<<'s'
USING T H E S H E L L
CHAPTER 3
95
Looping over a set of filenames is very c o m m o n , and the shell's f o r statement is the only shell control-flow statement that you might c o m m o n l y type at
the terminal rather than putting in a file for later execution. T h e syntax is:
for var in list of words
do
commands
done
For example, a f o r statement to echo filenames one per line is just
$ for i in *
> do
>
echo $i
> done
The " i " can be any shell variable, although i is traditional. Note that the
variable's valu is accessed by $ i , but that the f o r loop refers to the variable
as i. We used * to pick up all the files in the current directory, but any other
list of a r g u m e n t s can be used. Normally you want to do something more
interesting than merely printing filenames. O n e thing we do frequently is to
compare a set of files with previous versions. For example, to c o m p a r e the od
versin of C h a p t e r 2 (kept in directory o d ) with the current one:
$ ls ch2.*
I 5
ch2.1
ch2.2
ch2.6
ch2.7
$ for i in ch2.*
> do
>
echo $i:
>
d i f f -b old/$i
>
echo
> done I pr -h " d i f f
3712
ch2.3
ch2.4
ch2.5
$i
x
pwd*/old
We piped the output into pr and l p r just to illustrate that it's possible: the
standard output of the p r o g r a m s within a f o r goes to the standard output of
the f o r itself. We put a fancy heading on the output with the -h option of
p r , using two e m b e d d e d calis of pwd. A n d we set the whole sequence r u n n i n g
asynchronously (&) so we wouldn't have to wait for it; the &. applies to the
entire loop and pipeline.
We prefer to format a f o r statement as shown, but you can compress it
somewhat. The main limitations are that do and d o n e are only recognized as
keywords when they appear right after a newline or semicolon. D e p e n d i n g on
the size of the f o r , it's sometimes better to write it all on one line:
for i in list; do commands; done
You should use the f o r loop for mltiple c o m m a n d s , or where the built-in
96
CHAPTER 3
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
in
'cat .. . '
in
3 4 5 6;
do
ln
2 $i;
done
CHAPTER 3
97
$ for
i in *pick
ch2.* *
> do
>
echo $i:
>
d i f f old/$i
$i
> done
I pr ! lpr
ch2.1? y
ch2.2?
ch2.3?
ch2.4? y
ch2.5? y
ch2.6?
ch2.7?
$
It's obvious that this loop should be placed in a shell file to save typing next
time: if you've done something twice, you're likely to do it again.
Exercise 3-15. If the d i f f loop were placed in a shell file, would you put the p i c k in
the shell file? Why or why not?
Exercise 3-16. What happens if the last line of the loop above is
> done
I pr
i lpr
&
that is, ends with an ampersand? See if you can figure it out, then try it.
3.9 b u n d l e : putting it all together
To give something of the flavor of how shell files develop, let's work
through a larger example. Pretend you have received mail from a friend on
another machine, say s o m e w h e r e ! bob,+ who would like copies of the shell
files in your b i n . The simplest way to send them is by return mail, so you
might start by typing
$
$
>
>
>
>
cd /usr/you/bin
for
i in ypick
*"
do
echo
============ This
cat $i
done
I mail
somewhere!bob
is
file
$i
============
But look at it from s o m e w h e r e ! b o b ' s viewpoint: he's going to get a mail message with all the files clearly demarcated, but he'll need to use an editor to
break them into their component files. The flash of insight is that a properlyconstructed mail message could automatically unpack itself so the recipient
needn't do any work. That implies it should be a shell file containing both the
t T h e r e a r e several n o t a t i o n s for r e m o t e m a c h i n e a d d r e s s e s .
common.
Seemail(l).
T h e f o r m machine \person
is most
98
CHAPTER 3
CHAPTER 3
USING T H E S H E L L
$ cat CX
chmod +x $*
$ cat le
# le: count number of lines in files
wc -1 $*
$ cd . .
$ rm junk
$ pwd
test/*;
rmdir
test
99
Looks good
Clean up
/usr/you/bin
$ bundle
pick
*'
I mail
somewhere!bob
100
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 3
CHAPTER 4:
FILTERS
There is a large family of UNIX programs that read some input, perform a
simple transformation on it, and write some output. Examples include g r e p
and t a i l to select part of the input, s o r t to sort it, wc to count it, and so on.
Such programs are called filters.
This chapter discusses the most frequently used filters. We begin with
g r e p , concentrating on patterns more complicated than those illustrated in
Chapter 1. We will also present two other members of the g r e p family,
e g r e p and f g r e p .
The next section briefly describes a few other useful filters, including tr
for character transliteration, dd for dealing with data from other systems, and
u n i q for detecting repeated text lines. s o r t is also presented in more detail
than in Chapter 1.
The remainder of the chapter is devoted to two general purpose " d a t a
t r a n s f o r m e r s " or "programmable filters." They are called programmable
because the particular transformation is expressed as a program in a simple
programming language.
Different programs can produce very different
transformations.
The programs are s e d , which stands for stream editor, and awk, named
after its authors. Both are derived f r o m a generalization of g r e p :
$ program
pattern-action
filenames
...
scans the files in sequence, looking for lines that match a pattern; when one is
found a corresponding action is performed. For g r e p , the pattern is a regular
expression as in e d , and the default action is to print each line that matches
the pattern.
s e d and awk generalize both the patterns and the actions. s e d is a derivative of ed that takes a " p r o g r a m " of editor commands and streams data from
the files past them, doing the commands of the program on every line. awk is
not as convenient for text substitution as s e d is, but it includes arithmetic,
variables, built-in functions, and a programming language that looks quite a bit
like C. This chapter doen't have the complete story on either program;
Volume 2B of the UNIX Programmer's Manual has tutorials on both.
101
102
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 4
4 . 1 T h e g r e p family
We mentioned g r e p briefly in C h a p t e r 1, and have used it in examples
since t h e n .
$ g r e p pattern filenames...
searches the named files or the standard input and prints each line that contains an instance of the pattern.
g r e p is invaluable for finding occurrences of
variables in p r o g r a m s or words in d o c u m e n t s , or for selecting parts of the output of a p r o g r a m :
$
$
$
$
$
$
grep -n variable
*.[ch]
grep From $MAIL
grep From $MAIL I grep -v mary
grep -y mary $HOME/lib/phone-book
who I grep mary
ls I grep -v temp
From $MAIL
'"From'
prints lines that begin with F r o m , which are m o r e likely to be message header
lines. Regular expression metacharacters overlap with shell metacharacters, so
it's always a good idea to e n d o s e g r e p patterns in single quotes.
g r e p supports character classes much like those in the shell, so [ a - z ]
matches any lower case letter. But there are differences; if a g r e p character
class begins with a circumflex A , the pattern matches any character except
CHAPTER 4
FILTERS
103
-1
-1
I grep
! grep
' "d'
rw'
The
and seven periods match any seven characters at the beginning of the
line, which when applied the output o f l s - 1 means any permission string.
T h e closure operator * applies to the previous character or metacharacter
(including a character class) in the expression, and collectively they match any
number of successive matches of the character or metacharacter. For example,
x* matches a sequence of x ' s as long as possible, [a-zA-Z]* matches an
alphabetic string, .* matches anything up to a newline, and . *x matches anything up to and including the last x on the line.
T h e r e are a couple of important things to note about closures. First, closure applies to only one character, so x y * matches an x followed by y ' s , not a
sequence like x y x y x y . Second, "any n u m b e r " includes zero, so if you want at
least one character to be matched, you must duplcate it. For example, to
match a string of letters the correct expression is [ a - z A - Z ] [ a - z A - Z ] * (a
letter followed by zero or more letters). T h e shell's * filename matching character is similar to the regular expression . *.
No g r e p regular expression matches a newline; the expressions are applied
to each line individually.
With regular expressions, g r e p is a simple p r o g r a m m i n g language. For
example, recall that the second field of the password file is the encrypted password. This c o m m a n d searches for users without passwords:
$ grep
' /etc/passwd
104
CHAPTER 4
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ fgrep
-f
common-errors
document
CHAPTER 4
FILTERS
105
106
CHAPTER 4
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
I sort
-f
-s I sort
-s ! sort
-n
-nr
order
s o r t normally sorts on the entire line, but it can be told to direct its attention only to specific fields. The notation +m means that the comparison skips
the first m fields; +0 is the beginning of the line. So, for example,
$ ls -1 ! sort
+3nr
$ who I sort
+4n
+0f
+0 -u filenames
+ 0f sorts the line, folding upper and lower case together, but lines that are
identical may not be adjacent. So +0 is a secondary key that sorts the equal
lines from the first sort into normal ASCII order. Finally, -u discards any
adjacent duplicates. Therefore, given a list of words, one per line, the command prints the unique words. The index for this book was prepared with a
similar s o r t command, using even more o f s o r t ' s capabilities. See s o r t ( l ) .
The command u n i q is the inspiration for the -u flag of s o r t : it discards
all but one of each group of adjacent duplcate lines. Having a separate program for this function allows it to do tasks unrelated to sorting. For example,
u n i q will remove mltiple blank lines whether its input is sorted or not.
CHAPTER 4
FILTERS
107
f1
f2
prints the lines that are in the first file but not in the second. This is useful for
comparing directories and for comparing a word list with a dictionary.
T h e tr command transliterates the characters in its input. By far the most
common use of tr is case conversin:
$ tr
$ tr
a-z
A-Z
A-Z
a-z
-se A-Za-z
sort
u n i q -c
s o r t -n
tail !
5
'\012'
Compress
runs of non-letters
into newline
!
!
c a t collects the files, since t r only reads its standard input. T h e t r command is f r o m the manual: it compresses adjacent non-letters into newlines, thus
converting the input into one word per line. T h e words are then sorted and
u n i q -c compresses each group of identical words into one line prefixed by a
count, which becomes the sort field for s o r t - n . (This combination of two
s o r t s around a u n i q occurs often enough to be called an idiom.) The result
is the unique words in the document, sorted in increasing frequeney. t a i l
108
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 4
selects the 10 most common words (the end of the sorted list) and 5 prints
them in five columns.
By the way, notice that ending a line with ! is a valid way to continu it.
E x e r c i s e 4 - 3 . Use the tools in this section to write a simple spelling c h e c k e r , using
/ u s r / d i c t / w o r d s . W h a t a r e its s h o r t c o m i n g s , a n d h o w would you a d d r e s s t h e m ?
E x e r c i s e 4-4. W r i t e a w o r d - c o u n t i n g p r o g r a m in y o u r f a v o r i t e p r o g r a m m i n g l a n g u a g e
a n d c o m p a r e its size, speed a n d maintainability with the w o r d - c o u n t i n g p i p e l i n e . H o w
easily can you convert it into a spelling c h e c k e r ?
filenames ...
reads lines one at a time f r o m the input files; it applies the c o m m a n d s f r o m the
list, in o r d e r , to each line and writes its edited form on the standard o u t p u t .
So, for instance, you can change UNIX to UNIX(TM) everywhere it occurs in a
set of files with
$ sed 's/UNIX/UNIX(TM)/g' filenames ... >output
Do not misinterpret what happens here. s e d does not alter the contents of
its input files. It writes on the standard o u t p u t , so the original files are not
changed. By now you have enough shell experience to realize that
$ sed
file >file
is a bad idea: to replace the contents of files, you must use a t e m p o r a r y file, or
another p r o g r a m . ( W e will talk later about a program to encapsulate the idea
of overwriting an existing file; look at o v e r w r i t e in Chapter 5.)
s e d outputs each line automatically, so no p was needed after the substitution c o m m a n d above; indeed, if there had been o n e , each modified line would
have been printed twice. Quotes are almost always necessary, however, since
so many s e d metacharacters mean something to the shell as well. For example, consider using du -a to generate a list of filenames. Normally, du prints
the size and the filename:
$ du -a ch4.*
18
ch4. 1
13
ch4.2
14
ch4. 3
17
ch4.4
2
ch4.9
$
You can use s e d to discard the size part, but the editing c o m m a n d needs
FILTERS
CHAPTER 4
109
tty1
tty3
tty4
tty5
Sep
Sep
Sep
Sep
29
29
29
29
07:14
10:31
08:36
08:47
/ '
Ir 07:14
ron 10:31
you 08:36
td 08:47
$
sed
' s/ .*//'
$ getname
you
$
s/V-/'
$*
Versin 1 of i n d
This versin even puts a tab on each empty line, which seems unnecessary. A
better versin uses s e d ' s ability to select the lines to be m o d i f i e d . If you prefix a pattern to the c o m m a n d , only the lines that match the pattern will be
affected:
110
$*
CHAPTER 4
Versin 2 of ind
The pattern /. / matches any line that has at least one character on it other
than a newline; the s command is done for those lines but not for empty lines.
Remember that s e d outputs all lines regardless of whether they were changed,
so the empty lines are still produced as they should be.
There's yet another way that i n d could be written. It is possible to do the
commands only on lines that don't match the selection pattern, by preceding
the command with an exclamation mark
In
sed ' / * $ / ! s/V-/'
$*
Versin 3 of ind
the pattern / $ / matches empty lines (the end of the line immediately follows
the beginning), so / " " $ / ! says, "don't do the command on empty lines."
As we said above, s e d prints each line automatically, regardless of what
was done to it (unless it was deleted). Furthermore, most ed commands can
be used. So it's easy to write a s e d program that will print the first three
(say) lines of its input, then quit:
sed 3q
3q'
Notice where the quotes and the newline are: the commands have to be on
separate lines, but s e d ignores leading blanks and tabs.
With these ideas, it might seem sensible to write a program, called h e a d ,
to print the first few lines of each filename argument. But s e d 3q (or 10q) is
so easy to type that we've never felt the need. We do, however, have an i n d ,
since its equivalent s e d command is harder to type. (In the process of writing
this book we replaced the existing 30-line C program by versin 2 of the oneline implementations shown earlier). There is no clear criterion for when it's
worth making a separate command from a complicated command line; the best
rule we've found is to put it in your b i n and see if you actually use it.
It's also possible to put s e d commands in a file and execute them from
there, with
$ sed
-f cmdfile
. . .
FILTERS
CHAPTER 4
$ sed
'/pattern/q'
prints its input up to and including the first line matching pattern,
$ sed
111
'/pattern/d
and
'
deletes every line that contains pattern; the deletion happens before the line is
automatically printed, so deleted lines are discarded.
Although automatic printing is usually convenient, sometimes it gets in the
way. It can be turned off by the -n option; in that case, only lines explicitly
printed with a p command appear in the output. For example,
$ sed
-n
' /pattern/p'
does what g r e p does. Since the matching condition can be inverted by following it with !,
$ sed
-n
'/pattern/!p'
is g r e p - v . (So is s e d '/pattern/d'.)
Why do we have both s e d and g r e p ? After all, g r e p is just a simple special case of s e d . Part of the reason is history g r e p carne well before s e d .
But g r e p survives, and indeed thrives, because for the particular job that they
both do, it is significantly easier to use than s e d is: it does the common case
about as succinctly as possible. (It also does a few things that s e d won't; look
at the -b option, for instance.) Programs do die, however. There was once a
program called g r e s that did simple substitution, but it expired almost
immediately when s e d was born.
Newlines can be inserted with s e d , using the same syntax as in e d :
$ sed
>
's/$/\
/ '
adds a newline to the end of each line, thus double-spacing its input, and
$ sed 's/[
-*][
> /g'
replaces each string of blanks or tabs with a newline and thus splits its input
into one word per line. (The regular expression '[ -]' matches a blank or
tab; '[ - ] * ' matches zero or more of these, so the whole pattern matches one
or more blanks and/or tabs.)
You can also use pairs of regular expressions or line numbers to select a
range of lines over which any one of the commands will operate.
112
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$
$
$
$
s e d -n '20, 30p'
s e d ' 1, 10d'
s e d ' 1, /~$/d '
s e d -n '/"$/,/~end/p'
$ sed
'$d'
CHAPTER 4
Once a line is read, the previous line is gone forever: there is no way to identify the next-to-last line, which is what this command requires. (In fairness,
there is a way to handle this with s e d , but it is pretty advanced. Look up the
" h o l d " c o m m a n d in the manual.) T h e r e is also no way to do relative addressing f o r w a r d :
$ sed
'/thing/+ld'
'/pat/w
/pat/lw
filel
file2'
filenames ...
Or,
$ c a t newer
# newer f :
l i s t f i l e s newer t h a n f
l s - t s e d '/*'$1'$/q'
T h e quotes protect the various special characters aimed at s e d , while leaving
the $1 exposed so the shell will replace it by the filename. An alternate way
to write the a r g u m e n t is
CHAPTER 4
FILTERS
113
! cmd
: label
{
"/*$1\$/q"
since the $1 will be replaced by the argument while the \$ becomes just $.
In the s a m e way, we can write o l d e r , which lists all the files older than
the named one:
$ cat older
# older f:
l i s t f i l e s older than f
ls - t r ! sed ' / ~ ' $ 1 ' $ / q '
$
114
CHAPTER 4
another), it only makes one pass over the data, it's not possible to go backwards, there's no way to do forward references like / . . . / + 1 , and it provides
no facilities for manipulating numbers it is purely a text editor.
Exercise 4-5. Modify o l d e r and n e w e r so they don't include the argument file in
their output. Change them so the files are listed in the opposite order.
Exercise 4-6. Use s e d to make b u n d l e robust. Hint: in here documents, the endmarking word is recognized only when it matches the line exactly.
'program'
fleames ...
is different:
{ action
{ action
}
}
awk reads the input in the file ames one line at a time. Each line is compared
with each pattern in order; for each pattern that matches the line, the
corresponding action is performed. Like s e d , awk does not alter its input
files.
T h e patterns can be regular expressions exactly as in e g r e p , or they can be
more complicated conditions reminiscent of C. As a simple example, though,
$ awk
'/regular
expression/
}'
filenames
...
does what e g r e p does: it prints every line that matches the regular expression.
Either the pattern or the action is optional. If the action is omitted, the
default action is to print matched lines, so
$ awk
'/regular
expression/'
filenames
...
does the same job as the previous example. Conversely, if the pattern is omitted, then the action part is done for every input line. So
$ awk
'{
}'
filenames
...
-f
cmdfile filenames
...
FILTERS
CHAPTER 4
115
Fields
awk splits each input line automatically into fields, that is, strings of nonblank characters separated by blanks or tabs. By this definition, the output of
who has five fields:
$ who
you
jim
tty2
tty4
Sep 29 11:53
Sep 29 11:27
a w k calis the fields $ 1 , $ 2 , ..., $NF, where NF is a variable whose valu is set
to the n u m b e r of fields. In this case, NF is 5 for both lines. (Note the difference between NF, the number of fields, and $NF, the last field on the line. In
a w k , unlike the shell, only fields begin with a $; variables are u n a d o r n e d . )
For example, to discard the file sizes produced by du - a ,
$ du -a
and to print the ames of the people logged in and the time of login, one per
line:
$ who I awk '{ print $1, $5 }'
you 1 1 : 5 3
jim 11:27
$
To print the a m e and time of login sorted by time:
$ who I awk '{ print $5, $1 }' I sort
11:27 jim
1 1 : 5 3 you
$
These are alternatives to the s e d versions shown earlier in this chapter.
Although a w k is easier to use than s e d for operations like these, it is usually
slower, both getting started and in execution when there's a lot of input.
a w k normally assumes that white space (any number of blanks and tabs)
separates fields, but the separator can be changed to any single character. O n e
way is with the -F (upper case) command-line option. For example, the fields
in the password file / e t c / p a s s w d are separated by colons:
$ sed 3q /etc/passwd
root:3D.fHR5KoB.3s:0:1:S.User:/:
ken:y.68wd1.i jayz:6:1:K.Thompson:/usr/ken:
dmr:z4u3dJWbg7wCk:7:1:D.M.Ritchie:/usr/dmr:
$
116
T H E UNIX P R O G R A M M I N G E N V 1 R O N M E N T
$ sed 3q /etc/passwd
CHAPTER 4
root
ken
dmr
$
'{
printf
"\t%s\n",
$0 }'
$*
/etc/passwd
T h e pattern asks if the second field is an empty string ( ' = = ' is the equality test
FILTERS
CHAPTER 4
operator).
117
$2
==
$2
$2
!-
/ ~ $ /
/ . /
length($2)
== 0
==
"")
The ' ! ' operator is like that in C, but opposite to s e d , where the ! follov/s the
pattern.
O n e common use of patterns in awk is for simple data validation tasks.
Many of these amount to little m o r e than looking for lines that fail to meet
some criterion; if there is no output, the data is acceptable ( " n o news is good
n e w s " ) . For example, the following pattern makes sure that every input
record has an even n u m b e r of fields, using the operator % to compute the
remainder:
NF % 2 != 0
if
odd number of
fields
> 72 # p r i n t
if
too long
awk uses the same comment convention as the shell does: a # m a r k s the beginning of a c o m m e n t .
You can m a k e the output somewhat m o r e informative by printing a warning
and part of the too-long line, using another built-in f u n c t i o n , s u b s t r :
length($0)
> 72 { p r i n t
"Line",
NR,
"too long:",
substr($0,1,60)
1, 5) }'
Exercise 4-7. How many awk programs can you write that copy input to output as c a t
does? Which is the shortest?
118
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 4
END actions are done after the last line of input has been processed:
$ awk 'END { print NR } ' ...
prints the n u m b e r of lines of input.
Arihmetic and variables
T h e examples so far have in volved only simple text manipulation. a w k ' s
real strength lies in its ability to do calculations on the input data as well; it is
easy to count things, compute sums and averages, and the like. A c o m m o n use
of a w k is to sum columns of numbers. For example, to add up all the n u m b e r s
in the first column:
END
{ s = s + $1 }
{ print s }
Since the number of vales is available in the variable NR, changing the last
line to
END
s,
s/NR
{ s += $1 }
{ print s }
END
{ nc += l e n g t h ( $ 0 )
nw += NF
}
{ p r i n t NR, nw, nc
+ 1
# number of
# number of
chars,
words
1 for
\n
T h i s counts the lines, words and characters in its input, so it does the same job
as wc (although it doesn't break the totals down by file).
As another example of arithmetic, this program computes the n u m b e r of
FILTERS
119
This
CHAPTER 4
$ c a t prpages
# prpages:
c o m p u t e number o f p a g e s t h a t
wc $* !
awk ' ! / t o t a l $ / { n += i n t ( ( $ 1 + 5 5 ) / 5 6 )
END
{ p r i n t n }'
pr w i l l
3090
2421
2462
2986
213
11172
18129
13242
13455
16904
1117
62847
ch4. 1
ch4.2
ch4. 3
ch4.4
ch4.9
total
$ prpages ch.4. *
53
$
120
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 4
*
ii
\
ii
ii
+
ii
i
ii
!!
V
V
II
A
A
II
II
II
nothing
+ * /
++ --
= ~ !~
CHAPTER 4
FILTERS
121
$ c a t double
awk '
FILENAME != p r e v f i l e {
# new f i l e
NR = 1
# r e s e t l i n e number
p r e v f i l e = FILENAME
}
NF > O {
if ($1 == l a s t w o r d )
p r i n t f " d o u b l e %s, f i l e %s, l i n e % d \ n " , $ 1,FILENAME,NR
f o r ( i = 2 ; i <= NF; i + + )
if ( $ i == $(i1))
p r i n t f " d o u b l e %s, f i l e %s, l i n e %d\n",$i,FILENAME,NR
i f (NF > 0 )
l a s t w o r d = $NF
}'
$*
(condition)
statement]
else
statement2
(expression] ; condition;
statement
expression2)
For example,
for
(i
= 2;
<= NF; i + + )
runs the loop with i set in turn to 2, 3, ..., up to the n u m b e r of fields, NF.
T h e b r e a k statement causes a n immediate exit f r o m the enclosing w h i l e
122
CHAPTER 4
or f o r ; the c o n t i n u statement causes the next iteration to begin (at condition i n the w h i l e and expression2 i n the f o r ) . T h e n e x t statement causes
the next input line to be read and pattern matching to r e s u m e at the beginning
o f the awk p r o g r a m . T h e e x i t statement causes a n immediate t r a n s f e r t o the
END pattern.
Arrays
awk provides arrays, as do most p r o g r a m m i n g languages. As a trivial
example, this awk p r o g r a m collects each line of input in a separate array elem e n t , indexed by line n u m b e r , then prints t h e m out in reverse order:
$ c a t backwards
# backwards:
p r i n t i n p u t in backward l i n e o r d e r
awk '
{ l i n e [ N R ] = $0 }
END
{ f o r (i = NR; i > 0; i - - ) p r i n t l i n e [ i ]
} ' $*
Notice that, like variables, arrays don't have to be declared; the size of an
array is limited only by the m e m o r y available on your machine. Of course if a
very large file is being read into an array, it m a y eventually run out of
m e m o r y . To print the end of a large file in reverse order requires cooperation
with t a i l :
$ tail -5 /usr/dict/web2
I backwards
zymurgy
zymotically
zymotic
zymosthenic
zymosis
$
arr,
sep)
splits the string s into fields that are stored in elements 1 through n of the
array arr. If a separator character sep is provided, it is used; otherwise the
current valu of FS is used. For example, s p l i t ( $0 , a, " : " ) splits the input
line on colons, which is suitable for processing / e t c / p a s s w d , and
s p l i t ( " 9 / 2 9 / 8 3 " , d a t e , " / " ) splits a date o n slashes.
CHAPTER 4
FILTERS
123
cosine of expr
exponential of expr: eexpr
reads next input line; returns 0 if end of file, 1 if not
position of string s2 in sl\ returns 0 if not present
integer part of expr:; truncates toward 0
length of string s
natural logarithm of expr
sine of expr
split s into a[
on character c; return n
format ... according to specification fmt
n-character substring of s beginning at position m
Associative arrays
A standard problem in data processing is to accumulate vales for a set of
name-value pairs. That is, f r o m input like
Susie
J ohn
Mary
Mary
John
Susie
Mary
400
100
20 0
30 0
100
100
100
200
600
500
awk provides a neat way to do this, the associative array. Although one normally thinks of array subscripts as integers, in awk any valu can be used as a
subscript. So
END
{ sum[$ 1] += $2 }
{ f o r (ame in sum) p r i n t ame, sum[name]
is the complete program for adding up and printing the sums for the a m e -
124
CHAPTER 4
valu pairs like those above, whether or not they are sorted. Each a m e ( $ 1 )
is used as a subscript in sum; at the end, a special f o r m of the f o r statement is
used to cycle through all the elements of sum, printing them out. Syntactically, this variant of the f o r statement is
for
(var i n array)
statement
A l t h o u g h it might look superficially like the f o r loop in the shell, it's unrelated. It loops over the subscripts of array, not the elements, setting var to
each subscript in turn. T h e subscripts are produced in an unpredictable o r d e r ,
h o w e v e r , so it m a y be necessary to sort t h e m . In the example above, the output can be piped into s o r t to list the people with the largest vales at the top.
$ awk '. . . ' I sort + 1nr
T h e implementation of associative m e m o r y uses a hashing scheme to ensure
that access to any element takes about the same time as to any other, and that
(at least for m o d e r a t e array sizes) the time doesn't depend on h o w m a n y elements are in the a r r a y .
T h e associative m e m o r y is effective for tasks like counting all the words in
the input:
$ c a t wordfreq
awk '
END
'
{ for
{ for
(i = 1; i <= NF; i + + ) n u m [ $ i ] + + }
( w o r d in num) p r i n t w o r d , n u m [ w o r d ]
$ *
372
175
94
87
63
.CW 345
a 167
.P2 94
sed 83
are 61
o f 220
i n 109
.PP 9 0
t h a t 76
l i n e 55
i s 185
and 100
$ 87
f o r 75
p r i n t 52
The first f o r loop looks at each word in the input line, incrementing the element of a r r a y num subscripted by the word. ( D o n ' t confuse a w k ' s $ i , the i ' t h
field of the input line, with any shell variables.) A f t e r the files'ha^been r e a d ,
the second f o r loop prints, in arbitrary o r d e r , the words and their counts.
Exercise 4-9. The output from w o r d f r e q includes text formatting commands like .CW,
which is used to print words in t h i s f o n t . How would you get rid of such nonwords? How would you use tr to make w o r d f r e q work properly regardless of the
case of its input? Compare the implementation and performance of w o r d f r e q to the
pipeline from Section 4.2 and to this one:
sed ' s / [
-][ - ] * / \
FILTERS
CHAPTER 4
125
Strings
Although both s e d and awk are used for tiny jobs like selecting a single
field, only awk is used to any extent for tasks that really require programming.
One example is a program that folds long lines to 80 columns. Any line that
exceeds 80 characters is broken after the 80th; a \ is appended as a warning,
and the residue is processed. The final section of a folded line is rightjustified, not left-justified, since this produces more convenient output for program listings, which is what we most often use f o l d for. As an example,
using 20-character lines instead of 80,
$ cat t e s t
A short line.
A somewhat l o n g e r l i n e .
This l i n e is quite a b i t
$ fold
longer
than the
last
one.
test
A short line.
A somewhat l o n g e r
This
bit
li\
ne.
line is quite a\
longer than t h e \
l a s t one.
In
awk
there
is
no
explicit
string
concatenation
operator;
strings
are
126
CHAPTER 4
((n = length($0))
<= N) . . .
assigns the length of the input line to n before testing the valu.
parentheses.
Notice the
Exercise 4-10. Modify f o l d so that it will fold lines at blanks or tabs rather than splitting a word. Make it robust for long words.
$ ' $ 1'
}'
T h e $1 is exposed (it's not inside any quotes) and thus becomes the field
n u m b e r seen by awk. Another approach uses double quotes:
awk "{ p r i n t
\$$1
}"
CHAPTER 4
FILTERS
127
awk '
BEGIN { n = ' $ 1 ' }
{
f o r ( i = 1; i <= n; i + + )
s u m [ i ] += $i
}
END {
f o r ( i = 1; i <= n; i + + ) {
p r i n t f "%6g
sum[i]
t o t a l += sum[i]
}
printf
}
"; t o t a l
= %6g\n",
total
'
We use a BEGIN to insert the valu of n into a variable, rather than cluttering
up the rest of the program with quotes.
T h e main problem with all these examples is not keeping track of whether
one is inside or outside of the quotes (though that is a b o t h e r ) , but that as
currently written, such programs can read only their standard input; there is no
way to pass t h e m both the parameter n and an arbitrarily long list of
filenames. This requires some shell p r o g r a m m i n g that we'll address in the next
chapter.
A calendar service based on awk
O u r final example uses associative arrays; it is also an illustration of h o w to
interact with the shell, and demonstrates a bit about p r o g r a m evolution.
T h e task is to have the system send you mail every morning that contains a
reminder of upcoming events. (There may already be such a calendar service;
see c a l e n d a r ( l ) . This section shows an alternate approach.) T h e basic service should tell you of events happening today; the second step is to give a day
of warning events of t o m o r r o w as well as today. The proper handling of
w e e k e n d s and holidays is left as an exercise.
T h e first requirement is a place to keep the calendar. For that, a file called
c a l e n d a r i n / u s r / y o u seems easiest.
$ c a t calendar
Sep 30
Oct 1
Oct 1
$
mother's birthday
l u n c h w i t h j o e , noon
m e e t i n g 4pm
Second, you need a way to sean the calendar for a date. T h e r e are many
choices here; we will use awk because it is best at doing the arithmetic necessary to get f r o m " t o d a y " to " t o m o r r o w , " but other p r o g r a m s like s e d or
e g r e p can also serve. The lines selected f r o m the calendar are shipped off by
m a i l , o f course.
T h i r d , you need a way to have c a l e n d a r scanned reliably and automatically every day, probably early in the morning. This can be done with a t ,
which we mentioned briefly in Chapter 1.
128
CHAPTER 4
$ c a t bin/calendar
# calendar:
v e r s i n 1 -- today o n l y
awk <$HOME/calendar '
BEGIN { s p l i t (" " " d a t e x
, date)
$1 == d a t e [ 2 ] && $2 == d a t e [ 3 ]
' ! m a i l $NAME
$
T h e BEGIN block splits the date produced by d a t e into an array; the second
and third elements of the array are the month and the day. We are assuming
that the shell variable AME contains your login a m e .
T h e r e m a r k a b l e sequence of quote characters is required to capture the date
in a string in the middle of the awk p r o g r a m . An alternative that is easier to
u n d e r s t a n d is to pass the date in as the first line of input:
$ c a t bin/calendar
# calendar:
v e r s i n 2 -- today o n l y , no quotes
( d a t e ; c a t $HOME/calendar)
awk '
NR == 1
{ mon = $ 2 ; d a y = $3 } # s e t t h e d a t e
NR > 1 &.&. $1 == mon &.&. $2 == d a y # p r i n t c a l e n d a r
' m a i l $NAME
$
lines
= 31; nextmon["Jan"]
= 28; nextmon["Feb"]
= "Feb"
= "Mar"
we will use s p l i t to convert a convenient data structure into the one really
needed:
CHAPTER 4
FILTERS
129
$ c a t calendar
# calendar:
v e r s i n 3 - - t o d a y and t o m o r r o w
awk <$HOME/calendar '
BEGIN {
x = "Jan 31 F e b 28 Mar 31 Apr 30 May 31 J u n 30 " \
" J u l 31 Aug 31 S e p 30 Oct 31 Nov 30 Dec 31 J a n 31"
s p l i t ( x , data)
f o r ( i = 1; i < 2 4 ; i += 2 ) {
days[data[i]] = data[i+1]
n e x t m o n [ d a t a [ i ] ] = d a t a [ i + 2]
I
s p l i t ( " ' d a t e *"'", date)
moni = d a t e [ 2 ] ; d a y 1 = d a t e [ 3 ]
mon2 = m o n i ; d a y 2 = d a y 1 + 1
if (day1 >= d a y s [ m o n 1 ] ) {
day2 = 1
mon2 = n e x t m o n [ m o n 1 ]
}
}
$1 == moni && $2 == d a y 1
' ! m a i l $NAME
$
!!
$1 == mon2 && $2 == d a y 2
Notice that J a n appears twice in the data; a " s e n t i n e l " d a t a valu like this simplifies processing for December.
T h e final stage is to a r r a n g e for the calendar p r o g r a m to be run every day.
What you want is for someone to wake up every morning at around 5 AM and
run c a l e n d a r . You can do this yourself by r e m e m b e r i n g to say (every day!)
$ at 5am
calendar
ctl-d
$
but that's not exactly automatic or reliable. T h e trick is to tell at not only to
run the calendar, but also to schedule the next run as well.
$ c a t early.morning
calendar
e c h o e a r l y . m o r n i n g ! at
$
5am
130
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 4
Exercise 4-12. Should c a l e n d a r know about dates inside a line, not just at the beginning? How about dates expressed in other formats, like 1 0 / 1 / 8 3 ?
Exercise 4-13. Why doesn't c a l e n d a r use g e t n a m e instead of $NAME?
Exercise 4-14. Write a personal versin of rm that moves files to a temporary directory
rather than deleting them, with an at command to clean out the directory while you are
sleeping.
Loose ends
awk is an ungainly language, and it's impossible to show all its capabilities
in a chapter of reasonable size. Here are some other things to look at in the
manual:
Redirecting the output of p r i n t into files and pipes: any p r i n t or
p r i n t f statement can be followed by > and a filename (as a quoted string
or in a variable); the output will be sent to that file. As with the shell, >>
appends instead of overwriting. Printing into a pipe uses 1 instead of >.
Multi-line records: if the record separator RS is set to newline, then input
records will be separated by an empty line. In this way, several input lines
can be treated as a single record.
"Pattern, p a t t e r n " as a selector: as in ed and s e d , a range of lines can be
specified by a pair of patterns. This matches lines from an occurrence of
the first pattern until the next occurrence of the second. A simple example
is
NR == 1 0 ,
NR == 20
CHAPTER 4
FILTERS
131
Filters share a common design. Each writes on its standard output the
result of processing the argument files, or the standard input if no arguments
are given. The arguments specify input, never o u t p u t , t so the output of a
command can always be fed to a pipeline. Optional arguments (or nonfilename arguments such as the g r e p pattern) precede any filenames. Finally,
error messages are written on the standard error, so they will not vanish down
a pipe.
These conventions have little effect on the individual commands, but when
uniformly applied to all programs result in a simplicity of interconnection,
illustrated by many examples throughout this book, but perhaps most spectacularly by the word-counting example at the end of Section 4.2. If any of the
programs demanded a named input or output file, required interaction to
specify parameters, or generated headers and trailers, the pipeline wouldn't
work. And of course, if the UNIX system didn't provide pipes, someone would
have to write a conventional program to do the job. But there are pipes, and
the pipeline works, and is even easy to write if you are familiar with the tools.
Exercise 4-15. ps prints an explanatory header, and ls
of blocks in the files. Comment.
CHAPTER 5:
SHELL PROGRAMMiNG
Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a
command. Because it must satisfy both the interactive and programming
aspects of command execution, it is a strange language, shaped as much by history as by design. The range of its application leads to an unsettling quantity
of detail in the language, but you don't need to understand every nuance to use
it effectively. This chapter explains the basics of shell programming by showing the evolution of some useful shell programs. It is not a manual for the
shell. That is in the manual page s h ( l ) of the Unix Programmer's Manual,
which you should have handy while you are reading.
With the shell, as with most commands, the details of behavior can often be
most quickly discovered by experimentation. The manual can be cryptic, and
there is nothing better than a good example to clear things up. For that reason, this chapter is organized around examples rather than shell features; it is a
guide to using the shell for programming, rather than an encyclopedia of its
capabilities. We will talk not only about what the shell can do, but also about
developing and writing shell programs, with an emphasis on testing ideas
inter actively.
When you've written a program, in the shell or any other language, it may
be helpful enough that other people on your system would like to use it. But
the standards other people expect of a program are usually more rigorous than
those you apply for yourself. A major theme in shell programming is therefore
making programs robust so they can handle improper input and give helpful
information when things go wrong.
5.1 Customizing the c a l command
One common use of a shell program is to enhance or to modify the user
interface to a program. As an example of a program that could stand enhancement, consider the c a l ( l ) command:
133
134
CHAPTER 5
$ cal
usage:
cal
[month] y e a r
Good so far
Not so good
S
1
2
9
16
23
30
$
3 4
5 6 7 8
10 11 12 13 14 15
17 18 19 20 21 22
24 25 26 27 28 29
31
;;
;;
esac
SHELL P R O G R A M M I N G
CHAPTER 5
135
0)
1)
*)
interface
to
/usr/bin/cal
$# in
d a t e x ; m=$2; y = $ 6
set
d a t e x ; y=$6
m=$1; s e t
m=$1; y = $ 2
9 9
9 *
# no a r g s : use t o d a y
# 1 arg: use t h i s year
# 2 a r g s : m o n t h and y e a r
esac
c a s e $m i n
jan* Jan*)
f e b * Feb* )
mar* Mar* )
a p r * Apr* )
may* May* )
jun* Jun*)
jul* Jul*)
a u g * Aug* )
sep* Sep*)
o c t * Oct* )
n o v * Nov* )
d e c * Dec* )
t 1 - 9 ] ! 1 0 ! 1 1 ! 12)
*)
m= 1
m=2
m=3
m=4
m=5
m=6
m=7
m=8
m=9
m= 10
9
m= 11
9
m= 12
9
i i
y=$m; m=
# n u m e r i c month
# plain year
esac
/usr/bin/cal
$m $ y
# run t h e r e a l
one
The first c a s e checks the number of arguments, $#, and chooses the appropriate action. The final * pattern in the first c a s e is a catch-all: if the number of
arguments is neither 0 or 1, the last case will be executed. (Since patterns are
scanned in order, the catch-all must be last.) This sets m and y to the month
and year given two arguments, our c a l is going to act the same as the original.
The first c a s e statement has a couple of tricky lines containing
set
'date*
Although not obvious from appearance, it is easy to see what this statement
does by trying it:
136
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
TabSe 5.1:
$#
$*
$(s>
$$?
$$
$!
$HOME
$IFS
$MAIL
$PATH
$PS 1
$PS2
CHAPTER 5
the n u m b e r of a r g u m e n t s
all a r g u m e n t s to shell
similar to $ * ; see Section 5.7
options supplied to the shell
return valu of the last command executed
process-id of the shell
process-id of the last c o m m a n d started with &.
default a r g u m e n t for cd c o m m a n d
list of characters that separate words in a r g u m e n t s
file that, when changed, triggers "you have m a i l " message
list of directories to search for c o m m a n d s
prompt string, default '$ '
prompt string for continued c o m m a n d line, default '> '
$ date
S a t Oct
1 06:05:18
$ set 'date'
EDT 1 9 8 3
$ echo $ 1
Sat
$ echo $4
06:05:20
$
s e t is a shell built-in c o m m a n d that does too m a n y things. With no argum e n t s , it shows the vales of variables in the e n v i r o n m e n t , as we saw in
C h a p t e r 3. O r d i n a r y a r g u m e n t s reset the vales of $ 1 , $ 2 , and so o n . So
s e t * d a t e x sets $1 to the day of the w e e k , $2 to the a m e of the m o n t h ,
and so on. T h e first c a s e in c a l , t h e r e f o r e , sets the m o n t h and year f r o m
the current date if there are no arguments; if t h e r e ' s one a r g u m e n t , it's used as
the month and the year is taken f r o m the current date.
s e t also recognizes several options, o f which the most often used are - v
and - x ; they turn on echoing of c o m m a n d s as they are being processed by the
shell. T h e s e are indispensable for debugging complicated shell p r o g r a m s .
T h e remaining problem is to convert the m o n t h , if it is in textual f o r m , into
a n u m b e r . This is done by the second c a s e s t a t e m e n t , which should be
largely self-explanatory. T h e only twist is that the ! character in c a s e statement patterns, a s i n e g r e p , indicates a n alternative: b i g i s m a l l matches
either b i g or s m a l l .
Of course, these cases could also be written as
[ j j ] a n * and so on. The program accepts month ames either in all lower
case, because most c o m m a n d s accept lower case input, or with first letter capitalized, because that is the format printed by d a t e . The rules for shell pattern
matching are given in Table 5.2.
SHELL P R O G R A M M I N G
CHAPTER 5
Table 5.2:
?
[ccc]
II
137
II
\c
a! b
/
T h e last two cases in the second c a s e statement deal with a single argument that could be a year; recall that the first c a s e statement assumed it was
a m o n t h . If it is a n u m b e r that could be a m o n t h , it is left alone. O t h e r w i s e ,
it is assumed to be a year.
Finally, the last line calis / u s r / b i n / c a l (the real c a l ) with the converted a r g u m e n t s . Our versin of c a l works as a newcomer might expect:
$ date
Sat Oct
1 06:09:55
EDT 1 9 8 3
$ cal
S
O c t o b e r 1983
M Tu W Th F
2
3 4
5
9 10 1 1 12
16 17 18 19
2 3 24 2 5 26
30 31
$ cal dec
Decemb e r
s
M Tu W
4
5
6
7
1 1 12 13 14
18 19 20 21
2 5 26 27 2 8
6
7
13 14
20 21
27 2 8
S
1
8
15
22
29
1983
Th F
1 2
8
9
15 16
22 23
2 9 30
S
3
10
17
24
31
138
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 5
"?*.c$
Doesrt
instead of
$
ls *.c
If it's now December, and you ask for c a l j a n , should you get this year's January or
next year's? When should you have stopped adding features to c a l ?
5.2 Which command is w h i c h ?
There are problems with making prvate versions of commands such as
c a l . The most obvious is that if you are working with Mary and ty_pe c a l
while logged in as m a r y , you will get the standard c a l instead of the new one,
unless of course Mary has linked the new c a l into her b i n directory. This
can be confusing recall that the error messages from the original c a l are
not very helpful but is just an example of a general problem. Since the shell
searches for commands in a set of directories specified by PATH, it is always
possible to get a versin of a command other than the one you expect. For
instance, if you type a command, say e c h o , the pathname of the file that is
actually run could be . / e c h o or / b i n / e c h o or / u s r / b i n / e c h o or
CHAPTER 5
SHELL P R O G R A M M I N G
139
something else, depending on the components of your PATH and where the
files are. It can be very confusing if there happens to be an executable file
with the right a m e but the wrong behavior earlier in your search path than
you expect. Perhaps the most common is the t e s t c o m m a n d , which we will
discuss later: its a m e is such an obvious one for a temporary versin of a program that the wrong t e s t program gets called annoyingly o f t e n . t A c o m m a n d
that reports which versin of a program will be executed would provide a useful service.
O n e implementation is to loop over the directories n a m e d in PATH, searching each for an executable file of the given a m e . In C h a p t e r 3, we used the
f o r to loop over filenames and arguments. H e r e , we want a loop that says
f o r i in each component of PATH
do
if given ame is in directory i
print its full pathname
done
Because we can run any c o m m a n d inside backquotes x . . . \ the obvious solution is to run s e d over $PATH, converting colons into spaces. We can test it
out with our od friend e c h o :
$ echo $PATH
:/usr/you/bin:/bin:/usr/bin
$ e c h o $PATH I sed 's/;/ /g'
/usr/you/bin /bin /usr/bin
$ echo ' e c h o $PATH I sed 's/:/ /g''
/usr/you/bin /bin /usr/bin
$
4 components
Only 3 printed!
Still only 3
' s/~
s/::/:.:/g
s/:$/:./
s/:/ /g'
/usr/bin
140
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 5
CHAPTER 5
SHELL P R O G R A M M I N G
141
c a s e statement does pattern matching directly in the shell. In some UNIX versions, including System V, t e s t is a shell built-in function so an if and a
t e s t will run a s fast a s a c a s e . I f t e s t isn't built in, c a s e statements are
more efficient than if statements, and should be used for any pattern matchc a s e "$1" i n
helio)
command
esac
"$1"
= helio
command
fi
That is one reason why we sometimes use c a s e statements in the shell for
testing things that would be done with an if statement in most p r o g r a m m i n g
languages. A c a s e statement, on the other h a n d , can't easily d e t e r m i n e
whether a file has read permissions; that is better done with a t e s t and an
if.
So now the pieces are in place for the first versin of the c o m m a n d w h i c h ,
to report which file corresponds to a c o m m a n d :
$ c a t which
# w h i c h cmd:
w h i c h cmd in PATH is
executed,
versin
case $# in
0)
e c h o ' U s a g e : w h i c h command' 1>&2; e x i t 2
esac
f o r i i n x e c h o $PATH s e d ' s / * : / . : /
s/::/:.:/g
s/:$/: ./
s / : / /q' *
do
if test -f $/$1
# u s e t e s t -x if you can
then
echo $ i / $ 1
exit 0
# found it
fi
done
exit 1
# not found
$
142
$ ex which
$ which which
./which
$ which ed
/bin/ed
$ mv which /usr/you/bin
$ which which
/usr/you/bin/which
$
CHAPTER 5
Make it executable
>test
Make a fake t e s t
Make it executable
Try w h i c h now
Fails!
CHAPTER 5
SHELL P R O G R A M M I N G
$ c a t which
# w h i c h cmd:
w h i c h cmd i n PATH i s
executed,
143
final versin
opath=$PATH
PATH=/bin:/usr/bin
case $# in
0)
e c h o ' b s a g e : w h i c h command' 1>&2; e x i t 2
esac
f o r i in 'echo $opath ! sed ' s / A : / . : /
s/::/:.:/g
s/:$/:./
s/:/ /g''
do
if test -f $i/$1
# this is /bin/test
then
# or / u s r / b i n / t e s t only
echo $ i / $ 1
exit 0
# found it
fi
done
exit 1
# not found
$
w h i c h now works even if there is a spurious t e s t
the s e a r c h p a t h .
$ ls -1 t e s t
-rwxrwxrwx 1 you
$ which which
/usr/you/bin/which
$ which test
./test
$ rm test
$ which test
/bin/test
$
11 O c t
(or s e d o r e c h o )
1 06:55 t e s t
along
Still there
T h e shell p r o v i d e s t w o o t h e r o p e r a t o r s f o r c o m b i n i n g c o m m a n d s , a n d
t h a t a r e o f t e n m o r e c o m p a c t a n d c o n v e n i e n t t h a n the i f s t a t e m e n t . F o r
e x a m p l e , ! ! can r e p l a c e s o m e i f s t a t e m e n t s :
test
is e q u i v a l e n t to
if t e s t
then
! -f
filename
! !, d e s p i t e a p p e a r a n c e s , h a s n o t h i n g to do w i t h p i p e s it is a
144
CHAPTER 5
in
list of words
loop body, $i set to successive elements of list
done
for
do
done
$*)
SHELL P R O G R A M M I N G
CHAPTER 5
while
do
145
command
loop body executed as long as command returns true
done
until
do
command
loop body executed as long as command returns false
done
The second form of the f o r , in which an empty list implies $*, is a convenient
shorthand for the most common usage.
T h e conditional command that controls a w h i l e or u n t i l can be any command. As a trivial example, here is a w h i l e loop to watch for someone (say
Mary) to log in:
while
do
sleep
who
60
g r e p mary
done
The s l e e p , which pauses for 60 seconds, will always execute normally (unless
interrupted) and therefore return "success," so the loop will check once a
minute to see if Mary has logged in.
This versin has the disadvantage that if Mary is already logged in, you
must wait 60 seconds to find out. Also, if Mary stays logged in, you will be
told about her once a minute. The loop can be turned inside out and written
with an u n t i l , to provide the information once, without delay, if Mary is on
now:
until
do
who
! g r e p mary
s l e e p 60
done
146
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 5
$ cat watchfor
# watchfor:
watch f o r someone t o l o g i n
PATH=/bin:/usr/bin
case $# in
0)
echo 'Usage: watchfor person'
esac
u n t i l who ! e g r e p "$1"
do
s l e e p 60
done
$ ex watchfor
$ watchfor you
you
ttyO
Oct
1 08:01
$ mv watchfor /usr/you/bin
1>&2; e x i t
It works
nstall it
CHAPTER 5
SHELL P R O G R A M M I N G
147
$ c a t watchwho
# watchwho:
w a t c h who l o g s
i n and o u t
PATH=/bin:/usr/bin
new=/tmp/wwho1.$$
old=/tmp/wwho2.$$
>$old
# c r e a t e a n empty f i l e
while
do
done
# loop forever
who >$new
d i f f $ o l d $new
mv $new $ o l d
s l e e p 60
! awk ' / > / { $1 = " i n :
/ < / { $1 = "out:
print
print
}
}'
148
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 5
$ cat checkmail
# checkmail:
w a t c h m a i l b o x f o r growth
PATH=/bin:/usr/bin
MAIL=/usr/spool/mail/*getname*
# system dependent
t=${1-60}
x = M , l s -1 $MAIL*"
while :
do
y = " * l s - 1 $MAIL'"
e c h o $x $y
x="$y"
sleep $t
done ! awk ' $ 4 < $12 { p r i n t "You have m a i l "
}'
We have used a w k again, this time to ensure that the message is printed only
when the mailbox grows, not merely when it changes. O t h e r w i s e , you'll get a
message right after you delete mail. (The shell's built-in versin s u f f e r s f r o m
this d r a w b a c k . )
T h e time interval is normally set to 60 seconds, but if there is a p a r a m e t e r
on the c o m m a n d line, as in
$ checkmail 30
that is used instead. The shell variable t is set to the time if one is supplied,
and to 60 if no valu was given, by the line
t = ${ 1 - 6 0 }
T h i s introduces another f e a t u r e of the shell.
$ { v a r } is equivalent to $ v a r , and can be used to avoid problems with
variables inside strings containing letters or numbers:
$ var=hello
$ varx=goodbye
$ e c h o $var
helio
$ echo $varx
goodbye
$ echo ${var}x
hellox
$
Certain characters inside the braces specify special processing of the variable.
If the variable is u n d e f i n e d , and the ame is followed by a question m a r k , then
the string after the ? is printed and the shell exits (unless it's interactive). If
the message is not provided, a standard one is printed:
CHAPTER 5
$ echo
SHELL P R O G R A M M I N G
149
${var?}
helio
$ echo
${junk?}
junk: parameter not set
$ echo
${junk?error!}
junk: error !
$
Default
message
Message provided
Note that the message generated by the shell always contains the a m e of the
u n d e f i n e d variable.
A n o t h e r f o r m is $ { v a r - t h i n g } which evaluates to $ v a r if it is d e f i n e d ,
and t h i n g if it is not. $ { v a r = t h i n g } is similar, but also sets $ v a r to
thing:
$ echo
${junk-'Hi
there'}
Hi there
$ echo
${junk?}
junk: parameter not set
$ echo
${junk='Hi
there'}
junk unaffected
Hi there
$ echo
${junk?}
Hi there
$
${var+thing}
valu o f v a r ; nothing i f v a r u n d e f i n e d
same; useful if alphanumerics follow variable a m e
valu o f v a r i f defined; otherwise t h i n g .
$ v a r unchanged.
valu o f v a r i f defined; otherwise t h i n g .
I f u n d e f i n e d , $ v a r set t o t h i n g
i f d e f i n e d , $ v a r . O t h e r w i s e , print m e s s a g e
and exit shell. If m e s s a g e e m p t y , print:
var: parameter not set
t h i n g i f $ v a r d e f i n e d , otherwise nothing
150
CHAPTER 5
5 . 4 T r a p s : catching i n t e r r u p t s
If you hit DEL or hang up the phone while w a t c h w h o is r u n n i n g , one or
two t e m p o r a r y files are left in / t m p . w a t c h w h o should r e m o v e the t e m p o r a r y
files before it exits. We need a way to detect when such events h a p p e n , and a
way to recover.
W h e n you type DEL, an interrupt signal is sent to all the processes that you
are r u n n i n g on that terminal. Similarly, when you hang up, a hangup signal is
sent. T h e r e are other signis as well. Unless a p r o g r a m has taken explicit
action to deal with signis, the signal will termnate it. T h e shell protects programs run with &. f r o m interrupts but not f r o m hangups.
C h a p t e r 7 discusses signis in detail, but you needn't know much to be able
to handle them in the shell. The shell built-in c o m m a n d t r a p sets up a
sequence of c o m m a n d s to be executed when a signal occurs:
trap sequence-of-commands
T h e sequence-of-commands
is a single a r g u m e n t , so it mus almost always be
q u o t e d . T h e signal numbers are small integers that identify the signal. For
example, 2 is the signal generated by pressing the DEL key, and 1 is generated
by hanging up the phone. The signal n u m b e r s most often useful to shell prog r a m m e r s are listed in Table 5.4.
T a b l e 5.4:
0
1
2
3
9
15
Shell Signal N u m b e r s
CHAPTER 5
SHELL P R O G R A M M I N G
151
(trap
"
1;
long-running-command)
&
2134
$
The nuil c o m m a n d sequence means " i g n o r e i n t e r r u p t s " in this process and its
children. T h e parentheses cause the t r a p and c o m m a n d to be run together in
a background sub-shell; without t h e m , the t r a p would apply to the login shell
as well as to l o n g - r u n n i n g - c o m m a n d .
T h e n o h u p ( l ) c o m m a n d is a short shell p r o g r a m to provide this service.
Here is the 7th Edition versin, in its entirety:
$ cat
' w h i c h nohup*
trap "" 1 15
if test -t 2>&.1
then
echo "Sending output to 'nohup.out'"
exec nice -5 $* >>nohup.out 2>&1
else
exec nice -5 $* 2>&1
fi
$
test -t tests whether the standard output is a terminal, to see if the output
should be saved. The background program is run with nice to give it a lower
priority than interactive p r o g r a m s . (Notice that nohup doesn't set PATH.
Should it?)
The exec is just for efficiency; the c o m m a n d would run just as well
without it. exec is a shell built-in that replaces the process r u n n i n g this shell
152
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 5
by the named program, thereby saving one process the shell that would normally wait for the program to complete. We could have used e x e c in several
other places, such as at the end of the enhanced c a l program when it invokes
/usr/bin/cal.
By way, the signal 9 is one that can't be caught or ignored: it always kills.
From the shell, it is sent as
$ kill
-9 process
id ...
k i l l -9 is not the default because a process killed that way is given no chance
to put its affairs in order before dying.
Exercise 5-14. T h e versin of n o h u p above combines the s t a n d a r d e r r o r of the comm a n d with the standard o u t p u t . Is this a good design? If not, how would you separate
them cleanly?
Exercise 5-15. Look up the t i m e s shell built-in, and add a line to your . p r o f i l e so
that when you log off the shell prints out how much C P U time you have used.
Exercise 5-16. W r i t e a p r o g r a m that will find the next available user-id in
/ e t c / p a s s w d . If you are enthusiastic (and have permission), m a k e it into a c o m m a n d
that will add a n e w user to the system. W h a t permissions d o e s it n e e d ? H o w should it
h a n d l e interrupts?
filel
-o
file2
filel
>file2
is equivalent to
$ sort
If f i l e l and f i l e 2 are the same file, redirection with > will trncate the
input file before it is sorted. The -o option, however, works correctly,
because the input is sorted and saved in a temporary file before the output file
is created.
Many other commands could also use a -o option. For example, s e d could
edit a file in place:
$ sed
's/UNIX/UNIX(TM)Zg'
ch2
-o
ch2
Doesrit
It would be impractical to modify all such commands to add the option. Furthermore, it would be bad design: it is better to centralize functions, as the- shell
does with the > operator. We will provide a program o v e r w r i t e to do the
job. The first design is like this:
$ sed
's/UNIX/UNIX(TM)/g'
ch2
! overwrite
ch2
SHELL P R O G R A M M I N G
CHAPTER 5
# overwrite:
# versin 1.
153
PATH=/bin:/usr/bin
case $# in
D
;;
*)
echo 'Usage: overwrite file' 1>&2; exit 2
esac
new=/tmp/overwr.$$
trap 'rm -f $new; exit 1' 1 2 15
cat >$new
cp $new $1
rm -f $new
cp is used instead of mv so the permissions and owner of the output file aren't
changed if it already exists.
Appealingly simple as this versin is, it has a fatal flaw: if the user types
DEL during the c p , the original input file will be r u i n e d . We must prevent an
interrupt from stopping the overwriting of the input file:
# overwrite:
# versin 2.
PATH=/bin:/usr/bin
case $# in
1)
;;
*)
echo 'Usage: overwrite file' 1>&2; exit 2
esac
new=/tmp/overwr1.$$
old=/tmp/overwr2.$$
trap 'rm -f $new $old; exit 1' 1 2 15
cat >$new
cp $1 $old
trap " 1 2 15
cp $new $1
rm -f $new $old
If a DEL happens before the original file is touched, then the temporary files
are removed and the file is left alone. A f t e r the backup is m a d e , signis are
ignored so the last cp won't be interrupted once the cp starts, o v e r w r i t e
is committed to changing the original file.
154
CHAPTER 5
I overwrite
precious
1 09:02 precious
CHAPTER 5
SHELL PROGRAMMING
155
The shell built-in command s h i f t moves the entire a r g u m e n t list one position to the left: $2 becomes $ 1 , $3 becomes $ 2 , etc. "$@" provides all the
a r g u m e n t s ( a f t e r the s h i f t ) , like $ * , but uninterpreted; we'll come back to it
in Section 5.7.
Notice that PATH is restored to run the user's c o m m a n d ; if it w e r e n ' t , comm a n d s that were not i n / b i n o r / u s r / b i n would b e inaccessible t o
overwrite.
o v e r w r i t e now works (if somewhat clumsily):
$ cat notice
UNIX is a Trademark of Bell Laboratories
$ overwrite
notice
sed 's/UNIXUNIX(TM)/g'
notice
command garbled: s/UNIXUNIX(TM)/g
overwrite: sed failed, notice unchanged
$ cat notice
UNIX is a Trademark of Bell Laboratories
Unchanged
$ overwrite
notice
sed 's/UNIX/UNIX(TM)/g'
notice
$ cat notice
UNIX(TM) is a Trademark of Bell Laboratories
$
Using s e d to replace all occurrences of one word with another is a common
thing to do. With o v e r w r i t e in h a n d , a shell file to automate the task is
easy:
$ cat replace
# replace:
PATH=/bin:/usr/bin
case $# in
O 1 ! 2) echo 'Usage: replace str1 str2 files' 1>&.2; exit 1
esac
left="$1"; right="$2"; shift; shift
for i
do
overwrite $i sed "s@$left($right@g" $i
done
$ cat footnote
UNIX is not an acronym
$ replace
UNIX Unix footnote
$ cat footnote
Unix is not an acronym
$
(Recall that if the list on a f o r statement is e m p t y , it defaults to $*.) We
used @ instead of / to delimit the substitute c o m m a n d , since @ is somewhat
less likely to conflict with an input string.
156
CHAPTER 5
E x e r c i s e 5 - 2 0 . C a n r e p l a c e b e used t o c h a n g e the v a r i a b l e i t o i n d e x e v e r y w h e r e i n
a p r o g r a m ? H o w could you c h a n g e t h i n g s to m a k e this w o r k ?
E x e r c i s e 5 - 2 1 . I s r e p l a c e convenient and p o w e r f u l e n o u g h t o b e l o n g i n / u s r / b i n ?
I s i t p r e f e r a b l e t o simply typing the correct s e d c o m m a n d s w h e n n e e d e d ? W h y o r why
not?
Exercise 5-22.
(Hard)
$ overwrite
doesn't work.
H i n t : see e v a l i n s h ( l ) .
5.6 z a p :
H o w does your
CHAPTER 5
SHELL P R O G R A M M I N G
$ cat zap
# zap pattern:
157
1000 &
22126
$ ps -ag
PID TTY TIME CMD
22126 0
$ zap sleep
22126?
0? q
T h e problem is that the output of ps is being broken into words, which are
seen by p i c k as individual a r g u m e n t s rather than being processed a line at a
time. T h e shell's normal behavior is to break strings into a r g u m e n t s at
blank/non-blank boundaries, as in
for i in 1 2 3 4 5
In this p r o g r a m we must control the shell's divisin of strings into a r g u m e n t s ,
so that only newlines separate adjacent " w o r d s . "
T h e shell variable IFS (internal field separator) is a string of characters
that separate words in argument lists such as backquotes and f o r statements.
Normally, IFS contains a blank, a tab and a newline, but we can change it to
anything useful, such as just a newline:
158
CHAPTER 5
>nargs
Oct
Oct
1 05:59
1 11:26
Ten blank and newline-separated fields
10
$ IFS='
$ nargs
whox
Just a newline
Two lines, two fields
2
$
$ zap sleep
PID TTY TIME CMD
22126 0
0:00 sleep 1000? y
23104 0
0:02 egrep sleep? n
$
SHELL P R O G R A M M I N G
CHAPTER 5
159
</etc/passwd
Must type a valu anyway
Now shell reports error
g r e e t i n g has typed valu, not one from file
This might be described as a bug in the shell, but it is a fact of life. Fortunately, it can usually be circumvented by redirecting the loop surrounding the
r e a d . This is the key to our implementation of the p i c k command:
160
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
# pick:
CHAPTER 5
select arguments
PATH=/bin:/usr/bin
for i
do
'1 2'
If you want to see how p i c k is reading its a r g u m e n t s , run it and just press
RETURN after each p r o m p t . It's working fine as it stands: f o r i handles the
a r g u m e n t s properly. We could have written the loop other ways:
$ grep for pick
for i in $*
$ pick
'12'
3
1?
2?
3?
$
This f o r m doesn't work, because the o p e r a n d s of the loop are r e s c a n n e d , and
the blanks in the first argument cause it to become two a r g u m e n t s . Try quoting the $*:
$ grep for pick
for i in "$*"
$ pick
'12'
3
1 2 3?
$
CHAPTER 5
SHELL PROGRAMMING
161
This doesn't work either, because " $ * " is a single word f o r m e d f r o m all the
a r g u m e n t s joined together, separated by blanks.
Of course there is a solution, but it is almost black magic: the string
is treated specially by the shell, and converted into exactly the a r g u m e n t s to
the shell file:
$ grep
for
pick
for i in
$ pick
1 2?
'7 2'
3?
$
<mailinglist
instead of
$ pick
'cat mailinglist'
But we won't investgate this versin of p i c k : it involves some ugly complications and is significantly harder than the same program written in C, which we
will present in the next chapter.
T h e first two of the following exercises are difficult, but educational to the
advanced shell p r o g r a m m e r .
Exercise 5-24. T r y writing a p i c k that reads its a r g u m e n t s f r o m t h e s t a n d a r d input if
none a r e supplied on the c o m m a n d line. It should handle blanks properly. D o e s a q
response w o r k ? If not, try the next exercise.
Exercise 5-25. A l t h o u g h shell built-ins like r e a d and s e t cannot b e redirected, the
shell itself can be temporarily redirected. R e a d the section of s h ( l ) that describes e x e c
and work out how t o r e a d f r o m / d e v / t t y without calling a sub-shell. (It might help
to read C h a p t e r 7 first.)
Exercise 5-26. ( M u c h easier) Use r e a d i n your
whatever else depends on it, such as tab stops.
.profile
162
CHAPTER 5
# news:
HOME=.
# debugging only
cd .
# place holder for /usr/news
for i in 'ls -t * $HOME/.news _timex
do
case $i in
*/.news_time)
break ;;
*)
echo news: $i
esac
done
touch $HOME/.news_time
$
$
$
$
touch
touch
touch
news
.news_time
x
y
news: y
news: x
$
t o u c h changes the last-modified time of its a r g u m e n t file to the present
t i m e , without actually modifying the file. For debugging, we just echo the
a m e s of the news files, rather than printing t h e m . T h e loop terminates when
it discovers . n e w s _ t i m e , thereby listing only those files that are n e w e r . Note
that the * in c a s e statements can match a /, which it cannot in f i l e n a m e patterns.
W h a t happens if . n e w s _ t i m e doesn't exist?
SHELL P R O G R A M M I N G
CHAPTER 5
163
$ rm .news_time
$ news
$
This silence is unexpected, and wrong. It happens because if ls can't find a
file, it reports the problem on its standard output, before printing any i n f o r m a tion about existing files. This is undeniably a bug the diagnostic should be
printed on the standard error but we can get around it by recognizing the
problem in the loop and redirecting standard error to standard output so all
versions work the same. (This problem has been fixed in newer versions of
the system, but we've left it as is to illustrate how you can often cope with
minor botches.)
$ cat news
# news: print news files, versin 2
HOME =
cd .
IFS='
'
for i in
do
# debugging only
# place holder for /usr/news
# just a newline
'ls -t * $HOME/.news.time 2>&1
case $i in
*' not found')
*/.news.time)
*)
esac
break ;;
echo news: $i ;;
done
touch $HOME/.news_time
$ rm .news_time
$ news
news: news
news: y
news: x
$
We must set IFS to newline so the message
./.news_time not found
is not parsed as three words.
news must next print the news files, rather than echoing their a m e s . It's
useful to know who posted a message and when, so we use the set c o m m a n d
and ls -1 to print a header before the message itself:
164
$ ls -1 news
-rwxrwxrwx 1 you
208 Oct
$ set xls -1 news'
-rwxrwxrwx: bad option(s)
$
CHAPTER 5
1 12:05 news
Something is wrong!
PATH=/bin:/usr/bin
IFS='
# just a newline
cd /usr/news
for i in 'ls -t * $HOME/.news_time 2>&1x
do
IFS=' '
case $i in
*' not found') ;;
*/.news_time)
break ;;
*)
set X^ls -1 $s
echo "
$i: ($3) $5 $6 $7
II
cat $i
esac
done
touch $HOME/.news_time
T h e extra newlines in the header separate the news items as they are printed.
T h e first valu of IFS is just a newline, so the n o t f o u n d message (if any)
f r o m the first ls is treated as a single a r g u m e n t . T h e second assignment to
IFS resets it to a blank, so the output of the second ls is split into mltiple
arguments.
Exercise 5-27. Add an option -n (notify) to news to report but not print the news
items, and not touch .news_time. This might be placed in your .profile.
SHELL P R O G R A M M I N G
CHAPTER 5
165
Exercise 5-28. C o m p a r e our design and implementation of n e w s to the similar command on y o u r system.
5.9 g e t and p u t :
In this section, the last of a long chapter, we will show a larger, more complicated example that illustrates cooperation of the shell with awk and s e d .
A program evolves as bugs are fixed and features are added. It is sometimes convenient to keep track of these versions, especially if people take the
program to other machines they will come back and ask "What has changed
since we got our versin?" or " H o w did you fix the such-and-such b u g ? "
Also, always maintaining backup copies makes it safer to try out ideas: if
something doesn't work out, it's painless to revert to the original program.
O n e solution is to keep copies of all the versions around, but that is difficult to organize and expensive in disc space. Instead, we will capitalize on the
likelihood that successive versions have large portions in common, which need
t o b e stored only once. The d i f f - e command
$ d i f f -e
od
new
generates a list of ed commands that will convert o d into new. It is therefore possible to keep all the versions of a file in a single (different) file by
maintaining one complete versin and the set of editing commands to convert it
into any other versin.
There are two obvious organizations: keep the newest versin intact and
have editing commands go backwards in time, or keep the oldest versin and
have editing commands go forwards. Although the latter is slightly easier to
program, the former is faster if there are many versions, because we are
almost always interested in recent versions.
We chose the former organization. In a single file, which we'll cali the history file, there is the current versin followed by sets of editing commands that
convert each versin into the previous (i.e., next older) one. Each set of editing commands begins with a line that looks like
@@@ person date
summary
The summary is a single line, provided by person, that describes the change.
There are two commands to maintain versions: g e t extracts a versin from
the history file, and p u t enters a new versin into the history file after asking
for a one-line summary of the changes.
Before showing the implementation, here is an example to show how g e t
and p u t work and how the history file is maintained:
166
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 5
The editing c o m m a n d s run top to bottom throughout the history file to extract
the desired versin: the first set converts the newest to the second newest, the
next converts that to the third newest, etc. T h e r e f o r e , we are actually converting the new file into the od one a versin at a time when r u n n i n g e d .
SHELL P R O G R A M M I N G
CHAPTER 5
167
PATH=/bin:/usr/bin
case $# in
1)
HIST=$1.H ;;
*)
echo 'Usage: put file' 1>&.2; exit 1 ;;
esac
if test ! -r $1
then
echo "put: can't open $1" 1>&2
exit 1
fi
trap 'rm -f /tmp/put.[ab]$$; exit 1' 1 2 15
echo -n 'Summary: '
read Summary
if get -o /tmp/put.a$$ $1
# previous versin
then
# merge pieces
cp $1 /tmp/put.b$$
# current versin
echo "@>@@ 'getname' M a t e ' $Summary" >>/tmp/put. b$$
diff -e $1 /tmp/put.a$$ >>/tmp/put.b$$ # latest diffs
sed -n '/~@@@/,$p' <$HIST >>/tmp/put.b$$ # od diffs
overwrite $HIST cat /tmp/put.b$$
# put it back
else
# make a new one
echo "put: creating $HIST"
cp $1 $HIST
echo "@@@ 'getname' 'date' Summary" >>$HIST
fi
rm -f /tmp/put.[ab]$$
A f t e r reading the one-line s u m m a r y , p u t calis g e t t o extract the previous versin of the file f r o m the history file. The -o option to g e t specifies an altrnate output file. If g e t couldn't find the history file, it returns an error status
and p u t creates a new history file. If the history file does exist, the t h e n
clause creates the new history in a temporary file f r o m , in o r d e r , the newest
versin, the @@@ line, the editor c o m m a n d s to convert f r o m the newest versin
to the previous, and the od editor c o m m a n d s and @@@ lines. Finally, the temporary file is copied o n t o the history file using o v e r w r i t e .
168
CHAPTER 5
PATH=/bin:/usr/bin
VERSION=0
while test "$1" !=
do
case "$1" in
-i) INPUT=$2; shift ;;
-o) 0UTPUT=$2; shift ;;
-[0-9]) VERSION=$1 ;;
-*) echo "get: Unknown argument $i" 1>&2; exit 1 ;;
*) case "$OUTPUT" in
"") OUTPUT=$1 ;;
*) INPUT = $ 1.H ;;
esac
esac
shift
done
OUTPUT=${OUTPUT?"Usage: get [-o outfile] [-i file.H] file"}
INPUT=${INPUT-$OUTPUT.H}
test -r $ INPUT !! { echo "get: no file $INPUT" 1 >6.2; exit 1; }
trap 'rm -f /tmp/get.[ab]$$; exit 1' 1 2 15
# split into current versin and editing commands
sed <$INPUT -n '1,/A@@@/w /tmp/get.a'$$'
//v@@@/, $w /tmp/get .b' $$
# perform the edits
awk </tmp/get.b$$ '
/ ^@@(5)/ { C ount + + }
!/~@@@/ && count > 0 &L&L count <= - '$VERSION'
END { print "$d"; print "w" , '"OUTPUT"' }
' ! ed - /tmp/get.a$$
rm -f /tmp/get.[ab]$$
T h e options are fairly ordinary. - i and - o specify alternate input and output.
- [ 0 - 9 ] selects a particular versin: 0 is the newest versin (the d e f a u l t ) , -1
the newest-but-one, etc. The loop over a r g u m e n t s is a w h i l e with a t e s t
and a s h i f t , rather than a f o r , because some o f the options ( - i , - o ) consume another argument and must t h e r e f o r e s h i f t i t out, and f o r loops and
s h i f t s d o not cooperate properly i f the s h i f t i s inside the f o r . T h e e d
option
turns off the character count that normally accompanies reading or
writing a file.
T h e line
test -r $INPUT { echo "get: no file $INPUT" 1>&2; exit 1; }
is equivalent to
SHELL P R O G R A M M I N G
CHAPTER 5
169
if test ! -r $INPUT
then
echo "get: no file $INPUT" 1>&2
exit 1
fi
(which is the f o r m we used in p u t ) but is shorter to write and clearer to prog r a m m e r s who are familiar with the ! ! operator. C o m m a n d s between { and }
are executed in the current shell, not a sub-shell; this is necessary here so the
e x i t will exit f r o m g e t and not just a sub-shell. T h e characters { and } are
like do and d o n e they have special meaning only if they follow a semicolon, newline or other c o m m a n d t e r m i n a t o r .
Finally, we come to the code in g e t that does the work. First, s e d b r e a k s
the history file into two pieces: the most recent versin and the set of edits.
The a w k p r o g r a m then processes the editing c o m m a n d s . @@@ lines are counted
(but not p r i n t e d ) , and as long as the count is not greater than the desired versin, the editing c o m m a n d s are passed through (recall that the default awk
action is to print the input line). T w o ed c o m m a n d s are a d d e d after those
f r o m the history file: $d deletes the single @@@ line that s e d left on the
current versin, and a w c o m m a n d writes the file to its final location.
o v e r w r i t e i s unnecessary here because g e t changes only the versin o f the
file, not the precious history file.
Exercise 5-29.
W r i t e a c o m m a n d v e r s i n that d o e s t w o things:
$ versin -5 file
r e p o r t s the s u m m a r y , m o d i f i c a t i o n d a t e a n d person m a k i n g the m o d i f i c a t i o n o f the
selected versin in the history file.
$ versin sep 20 file
r e p o r t s which versin n u m b e r w a s c u r r e n t on S e p t e m b e r 20.
T h i s w o u l d typically be
used in:
$ get
170
CHAPTER 5
C H A P T E R 6:
So far we have used existing tools to build new ones, but we are at the limit
of what can be reasonably done with the shell, s e d and a w k . In this chapter
we are going to write some simple p r o g r a m s in the C p r o g r a m m i n g language.
The basic philosophy of m a k i n g things that work together will continu to
domnate the discussion and the design of the p r o g r a m s we want to create
tools that others can use and build on. In each case, we will also try to show a
sensible implementation strategy: start with the bare m i n i m u m that does something useful, then add features and options (only) if the need arises.
T h e r e are good reasons for writing new p r o g r a m s f r o m scratch. It m a y be
that the problem at h a n d just can't be solved with existing p r o g r a m s . T h i s is
often true when the p r o g r a m must deal with non-text files, for example the
majority of the p r o g r a m s we have shown so far really work well only on textual information. Or it may be too difficult to achieve a d e q u a t e robustness or
fficiency with just the shell and other general-purpose tools. In such cases, a
shell versin may be good for honing the definition and user interface of a program. ( A n d if it works well enough, there's no point re-doing it.) T h e z a p
program f r o m the last chapter is a good example: it took only a few minutes to
write the first versin in the shell, and the final versin has an a d e q u a t e user
interface, but it's too slow.
We will be writing in C because it is the standard language of UNIX systems
the kernel and all user p r o g r a m s are written in C a n d , realistically, no
other language is nearly as well supported. We will assume that you know C,
at least well enough to read along. If not, read The C Programming Language,
by B. W. Kernighan and D. M. Ritchie (Prentice-Hall, 1978).
We will also be using the " s t a n d a r d I/O l i b r a r y , " a collection of routines
that provide efficient and portable I/O and system services for C p r o g r a m s .
The standard I/O library is available on many non-UNlX systems that support
C, so p r o g r a m s that confine their system interactions to its facilities can easily
be t r a n s p o n e d .
The examples we have chosen for this chapter have a c o m m o n property:
they are small tools that we use regularly, but that were not part of the 7th
Edition. If your system has similar p r o g r a m s , you m a y find it enlightening to
171
172
CHAPTER 6
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
abe
$ vis
x
<x
abc\010\010\010
$
To sean mltiple files with this rudimentary versin of v i s , you can use c a t
to collect the files:
$ cat
filel
file2
...
I vis
$ cat
filel
file2
...
I vis
I grep
'\\'
1 x
Nothing at all!
P R O G R A M M I N G WITH S T A N D A R D I/O
CHAPTER 6
173
#include <stdio.h>
#include <ctype.h>
main()
{
int c;
while ((c = getchar()) != EOF)
if (isascii(c) &&
(isprint(c) !! c=='\n' !! c=='\t' !! c==' '))
putchar(c);
else
printf("\\%03o", c);
exit(O);
}
174
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
helio world\007
ctl-d
$
Normally you would rename a . o u t once it's working, o r use the c c option - o
to do it directly:
$ cc
-o
vis
vis.c
Output in v i s , not a . o u t
Exercise 6-1. We decided that tabs should be left alone, r a t h e r than m a d e visible as
\ 0 1 1 o r > o r \ t , since our main use o f v i s i s looking for truly a n o m a l o u s characters.
An alternate design is to identify every character of output u n a m b i g u o u s l y t a b s , nongraphics, blanks at line ends, etc. M o d i f y v i s so that characters like tab, backslash,
backspace, f o r m f e e d , etc., are printed i n their conventional C representations \ t , \ \ ,
\ b , \ f , etc., and so that blanks at the ends of lines a r e m a r k e d . C a n you do this
u n a m b i g u o u s l y ? C o m p a r e your design with
$ sed -n 1
Exercise 6-2. M o d i f y v i s so that it folds long lines at some reasonable length. H o w
does this interact with the u n a m b i g u o u s output required in the previous exercise?
P R O G R A M M I N G W I T H S T A N D A R D I/O
CHAPTER 6
T a b l e 6.1:
isalpha(c)
isupper(c)
islower(c)
isdigit(c)
isxdigit(c)
isalnum(c)
isspace(c)
ispunct(c)
isprint(c)
iscntrl(c)
isascii(c)
175
alphabetic: a - z A - Z
upper case: A - Z
lower case: a - z
digit: 0 - 9
hexadecimal digit: 0 - 9 a - f A - F
alphabetic or digit
blank, tab, newline, vertical tab, f o r m f e e d , return
not alphanumeric or control or space
printable: any graphic
control character: 0 <= c < 0 4 0 ! ! c == 0 1 7 7
ASCII character: 0 <= c <= 0 1 7 7
#include <stdio.h>
#include <ctype.h>
mainargc, argv)
int argc;
char *argv[];
{
int c, strip = 0;
176
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
faster than what you can write yourself because they have been optimized for
particular machines (sometimes by being written in assembly language).
Exercise 6-3. C h a n g e the -s argument so that vis -sn will print only strings of n or
m o r e consecutive printable characters, discarding non-printing c h a r a c t e r s and short
sequences of printable ones. This is valuable for isolating the text parts of non-text files
such as executable p r o g r a m s . Some versions of t h e system provide a strings p r o g r a m
that does this. Is it better to have a separate p r o g r a m or an a r g u m e n t to vis?
Exercise 6-4. T h e availability of the C source code is one of the strengths of the UNIX
system the code illustrates elegant solutions to many p r o g r a m m i n g p r o b l e m s . C o m ment on the tradeoff between readability of the C source and the occasional optimizations obtained f r o m rewriting in assembly language.
file 1 file2
...
will sean the named files instead of the standard input. If there are no
filename a r g u m e n t s , though, we still want v i s to read its standard input.
T h e question is how to arrange for the files to be read that is, how to
connect the filenames to the I/O statements that actually read the data.
T h e rules are simple. Before it can be read or written a file must be opened
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
177
178
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
p u t c (c , s t d o u t ) . In fact, all four of these " f u n c t i o n s " are defined as macros in < s t d i o . h > , since they run faster by avoiding the overhead of a f u n c tion cali for each character. See Table 6.3 for some other definitions in
<stdio.h>.
With some of the preliminaries out of the way, we can now write the third
versin of v i s . If there are command-line a r g u m e n t s , they are processed in
o r d e r . If there are no a r g u m e n t s , the standard input is processed.
/* vis:
#include <stdio.h>
#include <ctype.h>
int strip = 0 ;
main(argc, argv)
int argc;
char *argv[];
{
int i;
FILE *fp;
After
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
179
standard input
standard output
standard error
end of file; normally -1
invalid pointer; normally 0
used for declaring file pointers
normal I/O b u f f e r size (often 512 or 1024)
getc(fp)
getchar()
putc(c,fp)
putchar(c)
feof(fp)
ferror(fp)
fileno(fp)
int c;
while ((c = getc(fp)) 1= EOF)
if (isascii(c) &&.
(isprint(c) !! c=='\n' !! c=='\t' ! c==' '))
putchar(c);
else if (1strip)
printf("\\%03o", c);
}
180
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
W r i t e a p r o g r a m p r i n t a b l e that p r i n t s t h e a m e o f e a c h a r g u m e n t file
that c o n t a i n s o n l y p r i n t a b l e c h a r a c t e r s ; if t h e file c o n t a i n s a n y n o n - p r i n t a b l e c h a r a c t e r ,
t h e a m e is not p r i n t e d . p r i n t a b l e is u s e f u l in s i t u a t i o n s like this:
$ pr
Add
the
option
printable
return?
-v
to
invert
the
sense
of
the
test,
as
in
grep.
What
should
W h a t status should p r i n t a b l e
6 . 4 A screen-at-a-ime p r i n t e r : p
So far we have used c a t to examine files. But if a file is long, and if you
are connected to your system by a high-speed connection, c a t produces the
output too fast to be read, even if you are quick with ctl-s and ctl-q.
T h e r e clearly should be a program to print a file in small, controllable
c h u n k s , but there isn't a standard one, probably because the original UNIX system was written in the days of hard-copy (paper) terminis and slow c o m m u n i cations lines. So our next example is a program called p that will print a file a
screenful at a time, waiting for a response f r o m the user after each screen
before continuing to the next. ( " p " is a nice short ame for a p r o g r a m that we
use a lot.) As with other programs, p reads either f r o m files n a m e d as arguments or f r o m its standard input:
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
181
$ p VS.C
$ grep
'define'
*.[ch]
I p
This program is best written in C because it's easy in C, and h a r d otherwise; the standard tools are not good at mixing the input f r o m a file or pipe
with terminal input.
T h e basic, no-frills design is to print the input in small c h u n k s . A suitable
chunk size is 22 lines: that's slightly less than the 24-line screen of most video
terminis, and one third of a standard 66-line page. A simple way for p to
prompt the user is to not print the last newline of each 22-line chunk. T h e
cursor will thus pause at the right end of the line rather than at the left margin. W h e n the user presses RETURN, that will supply the missing newline and
thus cause the next line to appear in the proper place. If the user types ctl-d or
q at the end of a screen, p will exit.
We will take no special action for long lines. We will also not worry about
mltiple files: we'll merely skip f r o m one to the next without c o m m e n t . That
way the behavior of
$ p file ames...
! p
>
> done
in
filenames...
echo
$i:
cat $i
I p
Indeed, there are too m a n y features that we can add to this p r o g r a m . It's
better to make a stripped-down versin, then let it evolve as experience dictates. That way, the f e a t u r e s are the ones that people really want, not the ones
we thought they would want.
T h e basic structure of p is the same as v i s : the main routine cycles
through the files, calling a routine p r i n t that does the work on each.
182
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
/* p:
CHAPTER 6
#include <stdio.h>
#define PAGESIZE
char
*progname;
22
/* program ame for error message */
main(argc, argv)
int argc;
char *argv[];
{
int i;
FILE *fp, *efopen();
progname = argv[0];
if (argc == 1)
print(stdin, PAGESIZE);
else
for (i = 1; i < argc; i++) {
fp = efopen(argv[i], "r");
print(fp, PAGESIZE);
fcise(fp);
}
exit(0);
}
T h e routine e f o p e n encapsulates a very common operation: try to open a
file; if it's not possible, print an error message and exit. To encourage error
messages that identify the offending (or o f f e n d e d ) p r o g r a m , e f o p e n r e f e r s to
an external string p r o g n a m e containing the a m e of the p r o g r a m , which is set
in m a i n .
FILE *efopen(file, mode)
char *file, *mode;
{
FILE *fp, *fopen();
extern char progname;
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
183
184
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
if (tty == NULL)
tty = efopen("/dev/tty", "r");
if (fgets(buf, BUFSIZ, tty) == NULL !! buf[0] == 'q' )
exit(0);
else
/* ordinary line */
return buf[0];
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
185
186
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
shell built-in
(see
E x e r c i s e 6-9. If you f o r g e t to specify an input for p, it sits quietly waiting for input
f r o m the t e r m i n a l . Is it worth detecting this p r o b a b l e e r r o r ? If so, h o w ? H i n t :
isatty(3).
6.5 An example: p i c k
The versin of p i c k in Chapter 5 was clearly stretching the capabilities of
the shell. The C versin that follows is somewhat different from the one in
Chapter 5. If it has arguments, they are processed as before. But if the single
argument
is specified, p i c k processes its standard input.
Why not just read the standard input if there are no arguments? Consider
the second versin of the z a p command in Section 5.6:
kill
$SIG
'pick
Vps
-ag
! egrep
"$*"V
! awk
$1}'
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
/ pick:
187
#include <stdio.h>
char
progname;
main(argc, argv)
int argc;
char *argv[];
{
int i;
char buf[BUFSIZ];
progname = argv[0];
if (argc == 2 &&. s t r c m p ( a r g v [ 1 ] , ) = = 0 ) /* pick - */
while (fgets(buf, sizeof buf, stdin) != NULL) {
buf[strlen(buf)-1] = '\0'; /* drop newline */
pick(buf);
}
else
for (i = 1; i < argc; i++)
pick(argv[i]);
exit(0);
}
pick(s) /* offer choice of s */
char *s;
{
fprintf(stderr, "%s?
s);
if (ttyin() == 'y')
printf("%s\n", s);
}
p i c k centralizes in one program a facility for interactively selecting arguments. This not only provides a useful service, but also reduces the need for
" i n t e r a c t i v e " options on other c o m m a n d s .
Exercise 6-10. Given p i c k , is there a need for rm - i ?
6.6 On bugs and debugging
If you've ever written a program b e f o r e , the notion of a bug will be familiar. T h e r e ' s no good solution to writing bug-free code except to take care to
produce a clean, simple design, to implement it carefully, and to keep it clean
as you m o d i f y it.
T h e r e are a h a n d f u l of UNIX tools that will help you to find bugs, though
none is really first-rate. To Ilstrate t h e m , however, we need a b u g , and all
of the p r o g r a m s n this book are perfect. T h e r e f o r e we'll create a typical bug.
Consider the function p i c k shown above. Here it is again, this time containing an e r r o r . (No fair looking back at the original.)
188
CHAPTER 6
-o pick
Try it
Disaster!
P R O G R A M M I N G W I T H S T A N D A R D 1/0
CHAPTER 6
189
s);
190
CHAPTER 6
bad design. It's also possible to find errors like this, in which a function is
called with the wrong arguments, by using the C verifier l i n t ( l ) . l i n t
examines C programs for potential errors, portability problems, and dubious
constructions. If we run l i n t on the whole p i c k . c file, the e r r o r is identified:
$ lint
pick.c
:: "pick.c"(28)
In translation, this says that f p r i n t f ' s first argument is different in the standard library definition from its use in line 28 of our program. That is a strong
hint about what's wrong.
l i n t is a mixed success. It says exactly what's wrong with this program,
but also produces a lot of irrelevant messages that we've elided above, and it
takes some experience to know what to heed and what to ignore. It's worth
the effort, though, because l i n t finds some errors that are almost impossible
for people to see. It's always worth running l i n t after a long stretch of editing, making sure that you understand each warning that it gives.
6.7 An example: z a p
z a p , which selectively kills processes, is another program that we presented
as a shell file in Chapter 5. The main problem with that versin is speed: it
creates so many processes that it runs slowly, which is especially undesirable
for a program that kills errant processes. Rewriting z a p in C will make it faster. We are not going to do the whole job, however: we will still use ps to
find the process information. This is rnuch easier than digging the information
out of the kernel, and it is also portable, z a p opens a pipe with ps on the
input end, and reads from that instead of from a file. The function p o p e n ( 3 )
is analogous to f o p e n , except that the first argument is a command instead of
a filename. There is also a p e l s e that we don't need here.
P R O G R A M M I N G W I T H S T A N D A R D I/O
CHAPTER 6
/* zap:
191
#include <stdio.h>
#include <signal.h>
char
*progname;
/* program ame for error message */
char
*ps = "ps -ag"; /* system dependent */
main(argc, argv)
int argc;
char *argv[];
{
FILE *fin, *popen();
char buf[BUFSIZ];
int pid;
progname = argv[0];
if ((fin = popen(ps, "r")) == NULL) {
fprintf(stderr, "%s: can't run %s\n", progname, ps);
exit(1);
}
fgets(buf, sizeof buf, fin);
/* get header line */
fprintf(stderr, "%s", buf);
while (fgets(buf, sizeof buf, fin) != NULL)
if (argc == 1 !! strindex(buf, argv[1]) > = 0 ) {
buf[strlen(buf)-1] = '\0'; /* suppress \n */
fprintf(stderr, "%s? ", buf);
if (ttyin() == 'y') {
sscanf(buf, "%d", &pid);
kill(pid, SIGKILL);
}
}
exit(0);
}
We wrote the program to use ps -ag (the option is system dependent), but
unless you're the super-user you can kill only your own processes.
The first cali to fgets picks up the header line from ps; it's an interesting
exercise to deduce what happens if you try to kill the "process" corresponding
to that header line.
The function sscanf is a member of the scanf(3) family for doing input
format conversin. It converts from a string instead of a file. The system cali
kill sends the specified signal to the process; signal SIGKILL, defined in
<signal.h>, can't be caught or ignored. You may remember from Chapter
5 that its numeric valu is 9, but it's better practice to use the symbolic constants from header files than to sprinkle your programs with magic numbers.
If there are no arguments, z a p presents each line of the ps output for possible selection. If there is an argument, then z a p offers only ps output lines
that match it. The function s t r i n d e x ( s 1, s 2 ) tests whether the argument
192
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
n = strlen(t);
for (i = 0; s[i] != '\0'; i++)
if (strncmp(s+i, t, n) == 0)
return i;
return -1;
file2:
This is
a test
of
your
skill
and comprehension.
This is
not a test
of
our
ability.
d i f f produces
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
193
fscanf (fp,...)
s s c a n f ( s ,...)
p r i n t f ( fmt ,a1,...)
f p r i n t f ( f p,...)
s p r i n t f ( s ,...)
fgets(s,n,fp)
fputs(s,fp)
fflush(fp)
fclose(fp)
fp=popen(s,mode)
pclose(fp)
system(s)
open file s ; mode " r " , " w " , " a " for r e a d , write,
append (returns NULL for e r r o r )
get character; g e t c h a r ( ) i s g e t c ( s t d i n )
put character; p u t e h a r ( c ) is p u t e ( c , s t d o u t )
put character back on input file f p ; at most 1 char
can be pushed back at one time
read characters from s t d i n into a 1 , . . . according
to f m t . Each a must be a pointer.
R e t u r n s EOF or n u m b e r of fields converted.
read f r o m file f p
read f r o m string s
f o r m a t a 1 , . . . according t o f m t , print o n s t d o u t
print ... o n file f p
print ... into string s
read at most n characters into s f r o m f p .
R e t u r n s NULL at end of file
print string s on file fp
flush any buffered output o n file f p
cise file f p
open pipe to c o m m a n d s. See f o p e n .
cise pipe f p
run c o m m a n d s and wait for completion
$ d i f f f i l e l file2
2c2
< a test
> not a test
4,6c4,5
< your
< skill
< and comprehension.
> our
> ability.
$
A dialog with i d i f f
194
$ i d i f f f i l e l file2
2c2
< a test
> not a test
? >
4,6c4,5
< your
< skill
< and comprehension.
CHAPTER 6
> our
> ability.
? <
User chooses first (<) versin
idiff output in file idiff.out
$ cat i d i f f . out
Output put in this file
This is
not a test
of
your
skill
and comprehension.
$
If the response e is given instead of < or >, i d i f f invokes ed with the two
groups of lines already read in. If the second response had been e, the editor
b u f f e r would look like this:
your
skill
and comprehension.
our
ability.
W h a t e v e r is written back into the file by ed is what goes into the final output.
Finally, any c o m m a n d can be executed f r o m within i d i f f by escaping with
! cmd.
Technically, the hardest part of the job is d i f f , and that h a s already been
done for us. S o the real job o f i d i f f i s parsing d i f f ' s output, and opening,
closing, reading and writing the proper files at the right time. T h e main routine o f i d i f f sets u p the files and runs the d i f f process:
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
/* idiff:
195
interactive diff */
#include <stdio.h>
#include <ctype.h>
char
*progname;
#define HUGE
10000
main(argc, argv)
int argc;
char *argv[];
{
FILE *fin, *fout, *f1, *f2, *efopen();
char buf[BUFSIZ], *mktemp();
char *diffout = "idiff.XXXXXX";
progname = argv[0];
if (argc != 3) {
fprintf(stderr, "Usage: idiff filel file2\n");
exit(1);
}
f1 = efopen(argv[1], "r" ) ;
f2 = efopen(argv[2], "r");
fout = efopen("idiff.out", "w");
mktemp(diffout);
sprintf(buf,"diff %s %s >%s",argv[1],argv[2],diffout);
system(buf);
fin = efopen(diffout, "r");
idiff(f1, f2, fin, fout);
unlink(diffout);
printf("%s output in file idiff.out\n", progname);
exit(0);
}
The function mktemp(3) creates a file whose ame is guaranteed to be different from any existing file, m k t e m p overwrites its argument: the six X's are
replaced by the process-id of the i d i f f process and a letter. The system cali
u n l i n k ( 2 ) removes the named file from the file system.
The job of looping through the changes reported by d i f f is handled by a
function called i d i f f . The basic idea is simple enough: print a chunk of
d i f f output, skip over the unwanted data in one file, then copy the desired
versin from the other. There is a lot of tedious detail, so the code is bigger
than we'd like, but it's easy enough to understand in pieces.
196
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D 1/0
CHAPTER 6
197
fcise(ft);
break;
The function p a r s e does the mundane but tricky job of parsing the lines
produced by d i f f , extracting the four line numbers and the command (one of
a, c or d ) . p a r s e is complicated a bit because d i f f can produce either one
line number or two on either side of the command letter.
parse(s, pfroml, ptol, pcmd, pfrom2, pto2)
char *s;
int *pcmd, *pfrom1, *pto1, *pfrom2, *pto2;
s + +;
a2i(*pto1);
} else
*pto1 = *pfrom1;
*pcmd = *s++;
a2i(*pfrom2);
if (*s == ',') {
s + +;
a2i(*pto2);
} else
*pto2 = *pfrom2;
}
The macro a 2 i handles our specialized conversin from ASCII to integer in the
four places it occurs.
n s k i p and n c o p y skip over or copy the specified number of lines from a
file:
198
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
nskip(fin, n)
/* skip n lines of file fin */
FILE *fin;
{
char buf[BUFSIZ];
file2
CHAPTER 6
P R O G R A M M I N G W I T H S T A N D A R D I/O
199
-36
...
-36 $*
The routine g e t e n v ( " v a r " ) searches the environment for the shell variable var and returns its valu as a string of characters, or NULL if the variable
is not defined. Given g e t e n v , it's easy to modify p. All that is needed is to
add a couple of declarations and a cali to g e t e n v to the beginning of the main
routine.
/* p:
(versin 3) */
((p=getenv("PAGESIZE")) != NULL)
pagesize = atoi(p);
if (argc > 1 &&. argv[1][0] == ' - ' ) {
pagesize = atoi (&.argv[ 1 ] [ 1 ] ) ;
argc--;
argv++;
Optional arguments are processed after the environment variable, so any explicit page size will still override an implicit one.
Exercise 6-17. M o d i f y i d i f f t o search the e n v i r o n m e n t for the a m e o f the editor t o
be used. M o d i f y 2, 3, etc., to use PAGESIZE.
200
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 6
CHAPTER 7:
202
CHAPTER 7
you are going to write on a file, it may also be necessary to create it. The system checks your right to do so (Does the file exist? Do you have permission to
access it?), and if all is well, returns a non-negative integer called a file
descriptor. Whenever I/O is to be done on the file, the file descriptor is used
instead of the ame to identify the file. All information about an open file is
maintained by the system; your program refers to the file only by the file
descriptor. A FILE pointer as discussed in Chapter 6 points to a structure that
contains, among other things, the file descriptor; the macro f i l e n o ( f p )
defined in < s t d i o . h > returns the file descriptor.
There are special arrangements to make terminal input and output convenient. When it is started by the shell, a program inherits three open files,
with file descriptors 0, 1, and 2, called the standard input, the standard output,
and the standard error. All of these are by default connected to the terminal,
so if a program only reads file descriptor 0 and writes file descriptors 1 and 2,
it can do I/O without having to open files. If the program opens any other
files, they will have file descriptors 3, 4, etc.
If I/O is redirected to or from files or pipes, the shell changes the default
assignments for file descriptors 0 and 1 from the terminal to the named files.
Normally file descriptor 2 remains attached to the terminal, so error messages
can go there. Shell incantations such as 2>filename and 2>&1 will cause
rearrangements of the defaults, but the file assignments are changed by the
shell, not by the program. (The program itself can rearrange these further if it
wishes, but this is rare.)
File IIO read and write
All input and output is done by two system calis, r e a d and w r i t e , which
are accessed from C by functions of the same ame. For both, the first argument is a file descriptor. The second argument is an array of bytes that serves
as the data source or destination. The third argument is the number of bytes
to be transferred.
int fd, n, nread, nwritten;
char buf[SIZE];
nread = read(fd, buf, n);
nwritten = write(fd, buf, n);
Each cali returns a count of the number of bytes transferred. On reading, the
number of bytes returned may be less than the number requested, because
fewer than n bytes remained to be read. (When the file is a terminal, r e a d
normally reads only up to the next newline, which is usually less than what
was requested.) A return valu of zero implies end of file, and -1 indicates an
error of some sort. For writing, the valu returned is the number of bytes
actually written; an error has occurred if this isn't equal to the number supposed to be written.
While the number of bytes to be read or written is not restricted, the two
CHAPTER 7
203
most c o m m o n vales are 1, which means one character at a time ( " u n b u f f e r e d " ) , and the size of a block on a disc, most often 512 or 1024 bytes. ( T h e
p a r a m e t e r BUFSIZ in < s t d i o . h > has this valu.)
To Ilstrate, here is a program to copy its input to its output. Since the
input and output can be redirected to any file or device, it will actually copy
anything to anything: it's a bare-bones implementation of c a t .
/* cat: minimal versin */
#define SIZE
512 /* arbitrary */
main()
{
char buf[SIZE];
int n;
SIZE
1
10
100
512
1024
5120
188.8
19.3
2.6
1.0
0.6
0.6
The disc block size is 512 bytes on the PDP-11 system and 1024 on the VAX.
It is quite legal for several processes to be accessing the same file at the
same time; indeed, one process can be writing while another is reading. If this
isn't what you w a n t e d , it can be disconcerting, but it's sometimes useful. Even
though one cali to r e a d returns 0 and thus signis end of file, if m o r e data is
written on that file, a subsequent r e a d will find more bytes available. This
observation is the basis of a p r o g r a m called r e a d s l o w , which contines to
read its input, regardless of whether it got an end of file or not. r e a d s l o w is
204
CHAPTER 7
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
>temp
&
<temp
I grep
Process-id
something
k e e p r e a d i n g , w a i t i n g f o r more * /
512 / * a r b i t r a r y * /
main()
char buf[SIZE];
i n t n;
for (;;) {
while ((n = read(0, buf,
write(1, buf, n);
sleep(10);
}
sizeof
buf))
> 0)
}
T h e function s l e e p causes the p r o g r a m to be suspended for the specified
n u m b e r of seconds; it is described in s l e e p ( 3 ) . We don't want r e a d s l o w to
bang away at the file continuously looking for m o r e data; that would be too
costly in CPU time. T h u s this versin of r e a d s l o w copies its input up to the
end of file, sleeps a while, then tries again. If m o r e data arrives while it is
asleep, it will be read by the next r e a d .
Exercise 7-1. Add a -n argument to r e a d s l o w so the default sleep time can be
changed to n seconds. Some systems provide an option -f ("forever") for t a i l that
combines the functions of t a i l with those of r e a d s l o w . Comment on this design.
Exercise 7-2. What happens to r e a d s l o w if the file being read is truncated?
would you fix it? Hint: read about f s t a t in Section 7.3.
How
File creation o p e n , c r e a t , c i s e , u n l i n k
O t h e r than the default standard input, output and error files, you must
explicitly open files in order to read or write t h e m . T h e r e are t w o system calis
for this, o p e n and c r e a t . +
t K e n T h o m p s o n w a s o n c e a s k e d w h a t h e w o u l d d o d i f f e r e n t l y i f h e w e r e r e d e s i g n i n g t h e UNIX system.
CHAPTER 7
205
206
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
/* cp: copy f1 to f2 */
char *argv[];
{
int f1, f2, n;
char buf[BUFSIZ];
progname = argv[0];
if (argc != 3)
error("Usage: %s from to", progname);
if ((f1 = open(argv[1], 0)) == -1)
error("can't open %s", argv[1]);
if ((f2 = creat(argv[2], PERMS)) == -1)
error("can't create %s", argv[2]);
while ((n = read(f1, buf, BUFSIZ)) > 0)
if (write(f2, buf, n) != n)
exit(0);
CHAPTER 7
UNIX SYSTEM C A L L S
207
(progname)
f p r i n t f ( s t d e r r , "%s:
progname);
f p r i n t f ( s t d e r r , s1, s2);
if ( e r r n o > 0 &&. e r r n o < s y s . n e r r )
f p r i n t f ( s t d e r r , " (%s)", s y s _ e r r l i s t [ e r r n o ] ) ;
fprintf(stderr, "\n");
exit(1);
}
e r r n o is initially zero, and should always be less than s y s . n e r r . It is not
reset to zero when things go well, however, so you must reset it after each
error if your p r o g r a m intends to continu.
H e r e is how error messages appear with this versin of c p :
$ cp foo bar
c p : c a n ' t o p e n f o o (No s u c h f i l e o r d i r e c t o r y )
$ date >foo; chmod 0 foo
Make an unreadable file
$ cp foo bar
cp: c a n ' t open f o o ( P e r m i s s i o n d e n i e d )
$
Random access l s e e k
File I/O is normally sequential: each r e a d or w r i t e takes place in the file
right after the previous one. When necessary, however, a file can be read or
written in an arbitrary o r d e r . The system cali l s e e k provides a way to move
around in a file without actually reading or writing:
int fd, origin;
long o f f s e t , pos,
pos = l s e e k ( f d ,
lseek();
offset, origin);
forces the current position in the file whose descriptor is fd to move to position o f f s e t , which is taken relative to the location specified by o r i g i n .
Subsequent reading or writing will begin at that position. o r i g i n can be 0, 1,
or 2 to specify that o f f s e t is to be measured f r o m the beginning, f r o m the
current position, or f r o m the end of the file. T h e valu returned is the new
absolute position, or -1 for an e r r o r . For example, to append to a file, seek to
the end before writing:
lseek(fd,
0L, 2 ) ;
208
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
0L, 0 ) ;
0L,
1);
-e
causes r e a d s l o w to seek to the end of the input before beginning to read. What does
l s e e k do on a pipe?
Exercise 7-4. Rewrite e f o p e n from Chapter 6 to cali e r r o r .
7 . 2 File system: directories
T h e next topic is how to walk through the directory hierarchy. This doesn't
actually use any new system calis, just some od ones in a new context. We
will Ilstrate by writing a function called s p n a m e that tries to cope with
misspelled filenames. T h e function
n = spname (ame, newname) ;
searches for a file with a ame "cise e n o u g h " to ame. If one is f o u n d , it is
copied into newname.
T h e valu n returned by s p n a m e is -1 if nothing cise
enough was f o u n d , 0 if there was an exact match, and 1 if a correction was
made.
s p n a m e is a convenient addition to the p c o m m a n d : if you try to print a
file but misspell the a m e , p can ask if you really meant something else:
CHAPTER 7
UNIX SYSTEM C A L L S
209
$ p /urs/srx/ccmd/p/spnam.c
Horribly botched ame
"/usr/src/cmd/p/spname . c"? y
Suggested correction accepted
/* spname: return correctly spelled filename */
As we will write it, s p n a m e will try to correct, in each component of the
filename, mismatches in which a single letter has been dropped or a d d e d , or a
single letter is wrong, or a pair of letters exchanged; all of these are illustrated
above. This is a boon for sloppy typists.
Before writing the code, a short review of file system structure is in o r d e r .
A directory is a file containing a list of file ames and an indication of where
they are located. T h e " l o c a t i o n " is actually an index into another table called
the inode table. The inode for a file is where all information about the file
except its ame is kept. A directory entry thus consists of only two items, an
inode n u m b e r and the file a m e . The precise specification can be found in the
file < s y s / d i r . h > :
$ cat /usr/include/sys/dir.h
#define DIRSIZ 14 /* max length of file ame */
struct direct
/* structure of directory entry */
{
ino_t d_ino;
/* inode number */
char d.name[DIRSIZ];
/* file ame */
};
$
The " t y p e " i n o _ t is a t y p e d e f describing the index into the inode table.
It happens to be u n s i g n e d s h o r t on PDP-11 and VAX versions of the system, but this is definitely not the sort of information to embed in a program: it
might be different on a different machine. Henee the t y p e d e f . A complete
set of " s y s t e m " types is found in < s y s / t y p e s . h > , which must be included
before < s y s / d i r . h > .
The operation of s p n a m e is straightforward enough, although there are a
lot of b o u n d a r y conditions to get right. Suppose the file ame is / d l / d 2 / f .
The basic idea is to peel off the first component ( / ) , then search that directory
for a a m e cise to the next component (di), then search that directory for
something near d2, and so on, until a match has been found for each component. If at any stage there isn't a plausible candidate in the directory, the
search is a b a n d o n e d .
We have divided the job into three functions. s p n a m e itself isolates the
components of the path and builds them into a "best match so f a r " filename.
It calis m i n d i s t , which searches a given directory for the file that is closest to
the current guess, using a third function, s p d i s t , to compute the distance
between two ames.
210
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
/* spname:
CHAPTER 7
/ *
#include <sys/types.h>
#include <sys/dir.h>
spname(oldname, newname)
char oldname, newname;
{
char *p, guess[DIRSIZ+1], best[DIRSIZ+1];
char *new = newname, *old = oldname;
for (;;) {
while (*old == '/') /* skip slashes */
*new++ = *old++;
*new = '\0';
if (*old == '\0')
/* exact or corrected */
return strcmp(oldname,newname) != 0;
p = guess;
/* copy next component into guess */
for ( ; *old != '/' &.&. *old != '\0'; old + +)
if (p < guess+DIRSIZ)
*p++ = *old;
*p = '\0';
if (mindist(newname, guess, best) >= 3)
return -1; /* hopeless */
for (p = best; *new = *p++; ) /* add to end */
new++;
/* of newname */
CHAPTER 7
UNIX SYSTEM C A L L S
211
{
/* set best, return distance 0..3 */
int d, nd, fd;
struct {
ino_t ino;
char name[DIRSIZ+1];
/* 1 more than in dir.h */
} nbuf;
nbuf.ame[DIRSIZ] = '\0';
/* +1 for terminal '\0' */
if (dir[0] == '\0')
/* current directory */
dir =
d = 3; /* minimum distance */
if ((fd=open(dir, 0)) == -1)
return d;
while (read(fd, (char *) &.nbuf , sizeof ( struct direct)) > 0)
if (nbuf.ino) {
nd = spdist(nbuf.ame, guess);
if (nd <= d && nd != 3) {
strcpy(best, nbuf.ame);
d = nd;
if (d == 0)
/* exact match */
break;
}
}
cise(fd);
return d;
}
instead of
if (nd < d ...)
which is always
212
CHAPTER
{
while (*s++ == *t)
if (*t++ == '\0')
return 0;
/* exact match */
if (* s) {
if (*t) {
if (s[ 1 ] && t[1] && *s == t[1]
&& *t == s[1] && EQ(s+2, t+2))
return 1;
/* transposition */
if (EQ(s+1, t+1))
return 2;
/* 1 char mismatch */
}
if (EQ(s+1, t))
return 2;
/* extra character */
}
if
(*t
SL&L E Q ( s ,
return 2;
return 3;
t+1))
/* missing character */
CHAPTER 7
UNIX SYSTEM C A L L S
/* p:
#include <stdio.h>
#define PAGESIZE
char
*progname;
213
(versin 4) */
22
/* program ame for error message */
mainfargc, argv)
int argc;
char *argv[];
{
FILE *fp, *efopen();
int i, pagesize = PAGESIZE;
char *p, *getenv(), buf[BUFSIZ];
progname = argv[0];
if ((p=getenv("PAGESIZE")) != NULL)
pagesize = atoi(p);
if (argc > 1 && argv[1][0] == '-') {
pagesize = atoi(&argv[1][1]);
argc--;
argv++;
if (argc == 1)
print(stdin, pagesize);
else
for (i = 1; i < argc; i++)
switch (spname(argv[i], buf)) {
case -1:
/* no match possible */
fp = efopen(argv[i], "r");
break;
case 1:
/* corrected */
fprintf(stderr, "\"%s\"?
buf);
if (ttyin() == 'n')
break;
argv[i] = buf;
/* fall through... */
case 0: /* exact match */
fp = efopen(argv[i], "r");
print(fp, pagesize);
fclose(fp);
exit(0 ) ;
}
Spelling correction is not s o m e t h i n g to be blindly applied to every p r o g r a m
t h a t u s e s f i l e n a m e s . It w o r k s w e l l w i t h p b e c a u s e p is i n t e r a c t i v e , b u t it's not
suitable for p r o g r a m s that might not be interactive.
Exercise 7-5. H o w much can you improve on the heuristic for selecting the best match
in spname? For example, it is foolish to treat a regular file as if it were a directory;
214
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
Can you write a versin of cd that uses spname? How would you install it?
7.3 File system: inodes
In this section we will discuss system calis that deal with the file system and
in particular with the information about files, such as size, dates, permissions,
and so on. These system calis allow you to get at all the information we talked
about in C h a p t e r 2.
L e t ' s dig into the inode itself. Part of the inode is described by a structure
called stat, defined in <sys/stat .h>:
struct stat
{
dev_t
ino_t
short
short
short
short
dev_t
of f _t
time_t
time_t
time_t
};
/*
/ *
/ *
/ *
/ *
/ *
/*
/*
/*
/*
/ *
device of inode */
inode number */
mode bits */
number of links to file * /
owner's userid */
owner's group id */
for special files */
file size in characters * /
time file last read */
time file last written or created */
time file or inode last changed */
Most of the fields are explained by the c o m m e n t s . Types like dev_t and
ino_t are defined in <sys/types . h > , as discussed above. The st_raode
entry contains a set of flags describing the file; for convenience, the flag definitions are also part of the file <sys/stat . h > :
CHAPTER 7
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
S_IFMT
0170000
S_IFDIR 0040000
S.IFCHR 0020000
S_IFBLK 0060000
S_IFREG 0100000
S_ISUID
0004000
S_ISGID
0002000
S_ISVTX
0001000
S_IREAD
0000400
S_IWRITE 0000200
S_IEXEC
0000100
/*
/*
/*
/*
/
/*
/*
/*
/*
/*
/*
215
type of file */
directory */
character special */
block special */
regular */
set user id on execution */
set group id on execution */
save swapped text even after use */
read permission, owner */
write permission, owner */
execute/search permission, owner */
The inode for a file is accessed by a pair of system calis named s t a t and
f s t a t . s t a t takes a filename and returns inode information for that file (or
-1 if there is an error), f s t a t does the same from a file descriptor for an
open file (not from a F I L E pointer). That is,
char name;
int fd;
struct stat stbuf;
stat(ame, kstbuf);
fstat (fd, &.stbuf ) ;
filis the structure s t b u f with the inode information for the file ame or file
descriptor f d .
With all these facts in hand, we can start to write some useful code. Let us
begin with a C versin of c h e c k m a i l , a program that watches your mailbox.
If the file grows larger, c h e c k m a i l prints "You h a v e m a i l " and rings the
bell. (If the file gets shorter, that is presumably because you have just read
and deleted some mail, and no message is wanted.) This is entirely adequate
as a first step; you can get fancier once this works.
216
CHAPTER 7
CHAPTER 7
UNIX SYSTEM C A L L S
filel
file2
217
sv uses more
... dir
int i;
struct stat stbuf;
char *dir = argv[argc-1];
progname = argv[0];
if (argc <= 2)
error("Usage: %s files... dir", progname);
if (stat(dir, &.stbuf) == -1)
error("can't access directory %s", dir);
if ((stbuf.st.mode & S.IFMT) != S.IFDIR)
error("%s is not a directory", dir);
for (i = 1; i < argc-1; i++)
sv(argv[i], dir);
exit(0);
}
218
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
sv(file, dir)
/* save file in dir */
char *file, *dir;
{
struct stat sti, sto;
int fin, fout, n;
char target[BUFSIZ], buf[BUFSIZ], *index();
sprintf(target, "%s/%s", dir, file);
if (index(file, '/') != NULL) /* strchr() in some systems */
error("won't handle /'s in %s", file);
if (stat(file, &sti) == -1)
error("can't stat %s", file);
if (stat(target, &.sto) == -1)
/* target not present */
sto.st_mtime = 0 ;
/* so make it look od */
if (sti.st.mtime < sto.st_mtime)
/* target is newer */
fprintf(stderr, "%s: %s not copied\n",
progname, file);
else if ((fin = open(file, 0)) == -1)
error("can't open file %s", file);
else if ((fout = creat(target, sti.st_mode)) == -1)
error("can't create %s", target);
else
while ((n = read(fin, buf, sizeof buf)) > 0)
if (write(fout, buf, n) != n)
error("error writing %s", target);
cise(fin);
cise(fout);
}
CHAPTER 7
UNIX SYSTEM C A L L S
219
sv isn't proof against all possible disasters it doesn't deal with interrupts
at a w k w a r d times, for instance but it's more careful than most p r o g r a m s .
To focus on just one point for a m o m e n t , consider the final w r i t e statement.
It is rare that a w r i t e fails, so many programs ignore the possibility. But
discs run out of space; users exceed quotas; communications lines break. All
of these can cause write errors, and you are a lot better off if you hear about
them than if the program silently pretends that all is well.
T h e moral is that error checking is tedious but important. We have been
cavalier in most of the p r o g r a m s in this book because of space limitations and
to focus on more interesting topics. But for real, production p r o g r a m s , you
can't afford to ignore errors.
Exercise 7-10. Modify c h e c k m a i l to identify the sender of the mail as part of the
"You h a v e m a i l " message. Hint: s s c a n f , l s e e k .
Exercise 7-11. Modify c h e c k m a i l so that it does not change to the mail directory
before it enters its loop. Does this have a measurable effect on its performance?
(Harder) Can you write a versin of c h e c k m a i l that only needs one process to notify
all users?
Exercise 7-12. Write a program w a t c h f i l e that monitors a file and prints the file
from the beginning each time it changes. When would you use it?
Exercise 7-13. sv is quite rigid in its error handling. Modify it to continu even if it
can't process some file.
Exercise 7-14. Make sv recursive: if one of the source files is a directory, that directory and its files are processed in the same manner. Make cp recursive. Discuss
whether cp and sv ought to be the same program, so that cp -v doesn't do the copy if
the target is newer.
Exercise 7-15. Write the program random:
$ random filename
produces one line chosen at random from the file. Given a file p e o p l e of ames,
random can be used in a program called s c a p e g o a t , which is valuable for allocating
blame:
$ cat scapegoat
echo
"It's
all
'random
people''s
fault!"
$ scapegoat
It's
all
Ken's
fault!
Make sure that random is fair regardless of the distribution of line lengths.
Exercise 7-16. There's other information in the inode as well, in particular, disc
addresses where the file blocks are located. Examine the file < s y s / i n o . h > , then write
a program i c a t that will read files specified by inode number and disc device. (It will
work only if the disc in question is readable, of course.) Under what circumstances is
i c a t useful?
220
CHAPTER 7
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
7.4 Processes
This section describes how to execute one program from within another.
The easiest way is with the standard library routine s y s t e m , mentioned but
censured in Chapter 6. s y s t e m takes one argument, a command line exactly
as typed at the terminal (except for the newline at the end) and executes it in a
sub-shell. If the command line has to be built from pieces, the in-memory formatting capabilities of s p r i n t f may be useful. At the end of this section we
will show a safer versin of s y s t e m for use by interactive programs, but first
we must examine the pieces from which it is built.
Low-levelprocess
creation e x e c l p and e x e c v p
The most basic operation is to execute another program without returning,
by using the system cali e x e c l p . For example, to print the date as the last
action of a running program, use
execlp("date",
"date",
(char *) 0);
(char *) 0);
CHAPTER 7
UNIX SYSTEM C A L L S
221
The com-
mand
$ waitfile
filename
[ command ]
t r o f f . o u t echo
t r o f f done
&
222
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
/* child */
/* parent */
CHAPTER 7
UNIX SYSTEM C A L L S
223
zero to indcate various kinds of problems. The next higher eight bits are
taken from the argument of the cali to e x i t or return from m a i n that caused
termination of the child process.
When a program is called by the shell, the three file descriptors 0, 1, and 2
are set up pointing at the right files, and all other file descriptors are available
for use. When this program calis another one, correct etiquette suggests making sure the same conditions hold. Neither f o r k or e x e c calis affect open
files in any way; both parent and child have the same open files. f the parent
is buffering output that must come out before output from the child, the parent
must flush its buffers before the e x e c l p . Conversely, if the parent buffers an
input stream, the child will lose any information that has been read by the
parent. Output can be flushed, but input cannot be put back. Both of these
considerations arise if the input or output is being done with the standard I/O
library discussed in Chapter 6, since it normally buffers both input and output.
It is the inheritance of file descriptors across an e x e c l p that breaks
s y s t e m : if the calling program does not have its standard input and output
connected to the terminal, neither will the command called by s y s t e m . This
may be what is wanted; in an ed script, for example, the input for a command
started with an exclamation mark ! should probably come from the script.
Even then ed must read its input one character at a time to avoid input buffering problems.
For interactive programs like p, however, s y s t e m should reconnect standard input and output to the terminal. One way is to connect them to
/dev/tty.
The system cali d u p ( f d ) duplicates the file descriptor fd on the lowestnumbered unallocated file descriptor, returning a new descriptor that refers to
the same open file. This code connects the standard input of a program to a
file:
int fd;
fd = open("file", 0);
cise(0);
dup(fd);
cise(fd);
224
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
/ *
if (w == -1)
status = -1;
signal(SIGINT, istat);
signal(SIGQUIT, qstat);
return status;
}
Note that / d e v / t t y
i s o p e n e d with m o d e 2 r e a d a n d w r i t e a n d t h e n
d u p ' e d to f o r m the standard input and output. This is actually h o w the system
a s s e m b l e s t h e s t a n d a r d i n p u t , o u t p u t a n d e r r o r w h e n you l o g i n . T h e r e f o r e ,
y o u r s t a n d a r d input is writable:
$ echo helio
helio
$
1>&0
T h i s m e a n s w e c o u l d h a v e d u p ' e d file d e s c r i p t o r 2 t o r e c o n n e c t t h e s t a n d a r d
i n p u t a n d o u t p u t , but o p e n i n g / d e v / t t y i s c l e a n e r a n d s a f e r . E v e n this
CHAPTER 7
UNIX SYSTEM C A L L S
225
226
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 7
#include <signal.h>
char *tempfile = "temp.XXXXXX";
main()
{
extern onintr();
if (signal(SIGINT, SIG.IGN) 1= SIG_IGN)
signal(SIGINT, onintr);
mktemp(tempfile);
/* Process
... */
exit(0);
}
onintr()
/* clean up if interrupted */
{
}
unlink(tempfile);
exit(1);
Why the test and the double cali to s i g n a l in m a i n ? Recall that signis
are sent to all processes started from a particular terminal. Accordingly, when
a program is to be run non-interactively (started by &.), the shell arranges that
the program will ignore interrupts, so it won't be stopped by interrupts
intended for foreground processes. If this program began by announcing that
all interrupts were to be sent to the o n i n t r routine regardless, that would
undo the shell's effort to protect it when.run in the background.
The solution, shown above, is to test the state of interrupt handling, and to
continu to ignore interrupts if they are already being ignored. The code as
written depends on the fact that s i g n a l returns the previous state of a particular signal. If signis were already being ignored, the process should continu
to ignore them; otherwise, they should be caught.
A more sophisticated program may wish to intercept an interrupt and interpret it as a request to stop what it is doing and return to its own commandprocessing loop. Think of a text editor: interrupting a long printout should not
cause it to exit and lose the work already done. The code for this case can be
written like this:
CHAPTER 7
UNIX SYSTEM C A L L S
227
#include <signal.h>
#include <setjmp.h>
jmp_buf sjbuf;
main()
int onintr();
if (signal(SIGINT, SIG.IGN) != SIG.IGN)
signal(SIGINT, onintr);
setjmp(sjbuf);
/* save current stack position /
for (;;) {
/* main processing loop */
}
}
onintr()
/* reset if interrupted */
{
signal(SIGINT, onintr); /* reset for next interrupt */
printf("\nlnterrupt\n");
longjmp(sjbuf, 0);
/* return to saved state */
}
The file < s e t j m p . h > declares the type j m p _ b u f as an object in which the
stack position can be saved; s j b u f is declared to be such an object. The function s e t j m p ( 3 ) saves a record of where the program was executing. The
vales of variables are not saved. When an interrupt occurs, a cali is forced to
the o n i n t r routine, which can print a message, set flags, or whatever.
l o n g j m p takes as argument an object stored into by s e t j m p , and restores
control to the location after the cali to s e t j m p . So control (and the stack
level) will pop back to the place in the main routine where the main loop is
entered.
Notice that the signal is set again in o n i n t r after an interrupt occurs.
This is necessary: signis are automatically reset to their default action when
they occur.
Some programs that want to detect signis simply can't be stopped at an
arbitrary point, for example in the middle of updating a complicated data structure. The solution is to have the interrupt routine set a flag and return instead
of calling e x i t or l o n g j m p . Execution will continu at the exact point it was
interrupted, and the interrupt flag can be tested later.
There is one difficulty associated with this approach. Suppose the program
is reading the terminal when the interrupt is sent. The specified routine is duly
called; it sets its flag and returns. If it were really true, as we said above, that
execution resumes "at the exact point it was interrupted," the program would
continu reading the terminal until the user typed another line. This behavior
228
CHAPTER 7
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
might well be confusing, since the user might not know that the program is
reading, and presumably would prefer to have the signal take effect instantly.
To resolve this difficulty, the system terminates the read, but with an error
status that indicates what happened: errno is set to EINTR, defined in
<errno.h>, to indcate an interrupted system cali.
Thus programs that catch and resume execution after signis should be
prepared for " e r r o r s " caused by interrupted system calis. (The system calis to
watch out for are r e a d s from a terminal, w a i t , and p a u s e . ) Such a program
could use code like the following when it reads the standard input:
#include <errno.h>
extern int errno;
Why is this? Signis are sent to all your processes. Suppose the program you
cali catches its own interrupts, as an editor does. If you interrupt the subprogram, it will get the signal and return to its main loop, and probably read your
terminal. But the calling program will also pop out of its w a i t for the subprogram and read your terminal. Having two processes reading your terminal is
very confusing, since in effect the system flips a coin to decide who should get
each line of input. The solution is to have the parent program ignore interrupts until the child is done. This reasoning is reflected in the signal handling
in s y s t e m :
CHAPTER 7
U N I X SYSTEM C A L L S
#include
229
<signal.h>
system(s)
/* run command
char *s;
line s */
if
((pid
= f o r k ( ) ) == 0) {
execlp("sh",
exit(127);
"sh",
"-c", s,
(char *) 0);
}
istat = s i g n a l ( S I G I N T , S I G _ I G N ) ;
qstat = s i g n a l ( S I G Q U I T , S I G _ I G N ) ;
w h i l e ((w = wait (&status) ) != pid &&. w
!= - 1 )
if
(w == - 1 )
status = -1;
s i g n a l ( S I G I N T , istat);
s i g n a l ( S I G Q U I T , qstat);
r e t u r n status;
}
SIG_DFL
SIG.IGN
(int
(int
(*)())0
(*)())1
Alarms
The system cali a l a r m ( n ) causes a signal SIGALRM to be sent to your process n seconds later. The alarm signal can be used for making sure that something happens within the proper amount of time; if the something happens, the
alarm signal can be turned off, but if it does not, the process can regain control
by catching the alarm signal.
To illustrate, here is a program called t i m e o u t that runs another command; if that command has not finished by the specified time, it will be
aborted when the alarm goes off. For example, recall the w a t c h f o r command from Chapter 5. Rather than having it run indefinitely, you might set a
230
CHAPTER 7
limit of an h o u r :
$ timeout
-3600
watchfor
dmg &
*/
main(argc, argv)
int argc;
char *argv[];
{
int sec = 10, status, o n a l a r m ( ) ;
p r o g n a m e = argv[0];
if (argc > 1 && a r g v [ 1 ] [ 0 ] ==
{
sec = a t o i ( & a r g v [ 1 ] [ 1 ] ) ;
argc--;
argv++;
}
if (argc < 2)
e r r o r ( " U s a g e : %s [ - 1 0 ] c o m m a n d " , p r o g n a m e ) ;
if ((pid=fork()) == 0) {
execvpfargv[1], &argv[1]);
e r r o r ( " c o u l d n ' t start %s", a r g v [ 1 ] ) ;
}
s i g n a l ( S I G A L R M , onalarm);
alarm(sec);
if (wait(Estatus) == -1 i! (status &. 0 1 7 7 ) != 0)
error("%s killed", argv[1]);
e x i t ( ( s t a t u s >> 8) & 0377);
}
onalarm()
/* kill child w h e n alarm a r r i v e s
{
kill(pid, SIGKILL);
}
*/
CHAPTER 7
UNIX SYSTEM C A L L S
231
CHAPTER 8:
PROGRAM DEVELOPMENT
The UNIX system was originally meant as a program development environment. In this chapter we'll talk about some of the tools that are particularly
suited for developing programs. Our vehicle is a substantial program, an interpreter for a programming language comparable in power to BASIC. We chose
to implement a language because it's representative of problems encountered in
large programs. Furthermore, many programs can profitably be viewed as
languages that convert a systematic input into a sequence of actions and outputs, so we want to Ilstrate the language development tools.
In this chapter, we will cover specific lessons about
y a c c , a parser generator, a program that generales a parser from a grammatical description of a language;
m a k e , a program for specifying and controlling the processes by which a
complicated program is compiled;
o l e x , a program analogous to y a c c , for making lexical analyzers.
We also want to convey some notions of how to go about such a project the
importance of starting with something small and letting it grow; language evolution; and the use of tools.
We will describe the implementation of the language in six stages, each of
which would be useful even if the development went no further. These stages
closely parallel the way that we actually wrote the program.
(1)A four-function calculator, providing +, -, *, / and parentheses, that
operates on floating point numbers. One expression is typed on each line;
its valu is printed immediately.
(2) Variables with ames a through z. This versin also has unary minus and
some defenses against errors.
(3) Arbitrarily-long variable ames, built-in functions for s i n , e x p , etc., useful constants like -TT (spelled PI because of typographic limitations), and an
exponentiation operator.
(4) A change in internis: code is generated for each statement and subsequently interpreted, rather than being evaluated on the fly. No new
features are added, but it leads to (5).
(5) Control flow: if-else and while, statement grouping with { and }, and
233
234
CHAPTER 8
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
(1+2)
* (3+4)
21
1/2
0.5
355/113
3. 1415929
-3-4
hoc1: syntax error near line 4
It doesrit
Grammars
Ever since Backus-Naur Form was developed for Algol, languages have
been described b y f o r m a l g r a m m a r s . The g r a m m a r for h o d i s small and simple in its abstract representation:
CHAPTER 8
list:
expr:
PROGRAM DEVELOPMENT
235
expr \n
l i s t expr \n
NUMBER
expr + expr
expr - expr
expr * expr
expr / expr
( expr )
In other words, a l i s t is a sequence of expressions, each followed by a newline. An expression is a number, or a pair of expressions joined by an operator, or a parenthesized expression.
This is not complete. Among other things, it does not specify the normal
precedence and associativity of the operators, or does it attach a meaning to
any construct. And although l i s t is defined in terms of e x p r , and e x p r is
defined in terms of NUMBER, NUMBER itself is nowhere defined. These details
have to be filled in to go from a sketch of the language to a working program.
Overview of y a c c
y a c c is a parser generator,t that is, a program for converting a grammatical specification of a language like the one above into a parser that will parse
statements in the language. y a c c provides a way to associate meanings with
the components of the grammar in such a way that as the parsing takes place,
the meaning can be "evaluated" as well. The stages in using y a c c are the following.
First, a grammar is written, like the one above, but more precise. This
specifies the syntax of the language. y a c c can be used at this stage to warn of
errors and ambiguities in the grammar.
Second, each rule or production of the grammar can be augmented with an
action a statement of what to do when an instance of that grammatical form
is found in a program being parsed. The "what to d o " part is written in C,
with conventions for connecting the grammar to the C code. This defines the
semantics of the language.
Third, a lexical analyzer is needed, which will read the input being parsed
and break it up into meaningful chunks for the parser. A NUMBER is an example of a lexical chunk that is several characters long; single-character operators
like + and * are also chunks. A lexical chunk is traditionally called a token.
Finally, a controlling routine is needed, to cali the parser that y a c c built.
y a c c processes the grammar and the semantic actions into a parsing function, named y y p a r s e , and writes it out as a file of C code. If y a c c finds no
errors, the parser, the lexical analyzer, and the control routine can be
t y a c c stands for "yet another compiler-compiler," a comment by its creator, Steve Johnson, on
the number of such programs extant at the time it was being developed (around 1972). y a c c is
one of a handful that have flourished.
236
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 8
...
...
PROGRAM DEVELOPMENT
CHAPTER 8
237
$ cat hoc.y
%{
# d e f i n e Y Y S T Y P E double
*/
%}
%token
%left
%left
%%
list:
NUMBER
'+'
'/'
/* left a s s o c i a t i v e , same p r e c e d e n c e */
/* left assoc., higher p r e c e d e n c e */
/* nothing */
! list '\n'
! list expr '\n'
expr:
!
!
!
!
NUMBER
expr '+'
expr
expr '*'
expr '/'
'(' expr
expr
expr
expr
expr
')'
{ printf("\t%.8g\n",
{
{
{
{
{
{
$$ = $1; }
$ $ = $ 1 + $ 3 ;
$$ = $1 - $3;
$$ = $1 * $3;
$ $ = $ 1 / $ 3 ;
$ $ = $ 2; }
$2);
}
}
}
}
y
%%
/* end of g r a m m a r */
T h e r e ' s a lot of new information packed into these few lines. We are not
going to explain all of it, and certainly not how the parser works for that,
you will have to read the y a c c m a n u a l .
A l t e r n a t e rules are separated by ' ! ' . A n y g r a m m a r rule can have an associated action, which will be p e r f o r m e d when an instance of that rule is recognized in the input. An action is a sequence of C statements enclosed in braces
{ and }. Within an action, $n (that is, $ 1 , $ 2 , etc.) refers to the valu
returned by the n-th component of the rule, and $$ is the valu to be returned
as the valu of the whole rule. So, for example, in the rule
expr:
NUMBER
{ $$ = $1;
expr
'+' expr
{ $ $ = $ 1 + $ 3 ;
the valu of the result e x p r is the sum of the vales f r o m the two component
e x p r ' s . Notice that ' + ' is $2; every component is n u m b e r e d .
At the level above this, an expression followed by a newline ( ' \ n ' ) is
recognized as a list and its valu printed. If the end of the input follows such a
construction, the parsing process terminates cleanly. A l i s t can be an empty
string; this is how blank input lines are handled.
y a c c input is free f o r m ; our format is the r e c o m m e n d e d s t a n d a r d .
238
CHAPTER 8
CHAPTER 8
PROGRAM DEVELOPMENT
239
Continuing hoc. y
# i n c l u d e <stdio.h>
# i n c l u d e <ctype.h>
char
progname;
int
lineno = 1;
/* for error m e s s a g e s
main(argc, argv)
/* hoc1
char *argv[];
{
p r o g n a m e = argv[0];
yyparse();
}
*/
*/
/* hoc1
*/
{
int c;
while
c = = '\t')
9
if
(c == E O F )
if
(c ==
}
if
r e t u r n 0;
!! i s d i g i t ( c ) ) {
n g e t e ( c , stdin);
scanf("%lf", kyylval);
r e t u r n NUMBER;
/* n u m b e r */
(c ==
'\n')
lineno++;
return c;
}
The variable y y l v a l is used for communication between the parser and the
lexical analyzer; it is defined by y y p a r s e , and has the same type as the y a c c
stack. y y l e x returns the type of a token as its function valu, and sets
y y l v a l to the valu of the token (if there is one). For instance, a floating
240
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 8
point n u m b e r has the type NUMBER and a valu like 12.34. For some tokens,
especially single characters like ' + ' and ' \ n ' , the g r a m m a r does not use the
valu, only the type. In that case, y y l v a l need not be set.
T h e y a c c declaration % t o k e n NUMBER is converted into a # d e f i n e statement in the y a c c output file y . t a b . c , so NUMBER can be used as a constant
a n y w h e r e in the C p r o g r a m . y a c c chooses vales that w o n ' t collide with
ASCII characters.
If there is a syntax error, y y p a r s e calis y y e r r o r with a string containing
the cryptic message " s y n t a x e r r o r . " The y a c c user i s expected t o provide
a y y e r r o r ; ours just passes the string on to another f u n c t i o n , w a r n i n g ,
which prints somewhat m o r e information. Later versions of h o c will m a k e
direct use of w a r n i n g .
yyerror(s)
/* called for yacc syntax error
char *s;
{
w a r n i n g ( s , (char *) 0);
*/
w a r n i n g ( s , t)
/* print warning m e s s a g e */
char *s, *t;
{
f p r i n t f ( s t d e r r , "%s: %s", p r o g n a m e , s);
if (t)
fprintf(stderr, " %s", t);
f p r i n t f ( s t d e r r , " near line %d\n", lineno);
}
-o hoc1
0.66666667
-3-4
h o c 1 : syntax error near
$
line
Exercise 8-1. Examine the structure of the y.tab.c file. (It's about 300 lines long for
hocl.)
CHAPTER 8
PROGRAM DEVELOPMENT
241
'+'
Xleft
Xleft
'/'
UNARYMINUS
/* new /
NUMBER
expr
{ $$ = $1; }
Xprec U N A R Y M I N U S
{ $$ = -$2;
} /* n e w */
The % p r e c says that a unary minus sign (that is, a minus sign before an
expression) has the precedence of UNARYMINUS (high); the action is to change
the sign. A minus sign between two expressions takes the default precedence.
Exercise 8-2. Add the operators X (modulus or remainder) and unary + to h o c l .
Suggestion: look at f r e x p ( 3 ) .
A digression on make
It's a nuisance to have to type two commands to compile a new versin of
h o c l . Although it's certainly easy to make a shell file that does the job,
there's a better way, one that will generalize nicely later on when there is more
than one source file in the program. The program make reads a specification
of how the components of a program depend on each other, and how to process them to create an up-to-date versin of the program. It checks the times
at which the various components were last modified, figures out the mnimum
amount of recompilation that has to be done to make a consistent new versin,
then runs the processes. make also understands the intricacies of multi-step
processes like y a c c , so these tasks can be put into a make specification
without spelling out the individual steps.
make is most useful when the program being created is large enough to be
spread over several source files, but it's handy even for something as small as
h o c l . Here is the make specification for h o c l , which make expects in a file
called m a k e f i l e .
$ cat makefile
hoc1:
hoc.o
cc hoc.o
-o hocl
242
$ make
CHAPTER 8
yacc
hoc.y
cc
-c y.tab.c
rm y.tab.c
mv y . t a b . o hoc.o
cc hoc.o -o hocl
$ make
Do it again
hoc1' is up to date.
VAR
VAR
'=' expr
PROGRAM DEVELOPMENT
CHAPTER 8
243
$ cat hoc.y
%{
double
mem[26];
/* m e m o r y for v a r i a b l e s
'a'
*/
%}
Xunion
}
Xtoken
%token
%type
Xright
%lef t
%left
Xleft
list:
expr:
{
double
int
<val>
<index>
<val>
val;
index;
/* stack type */
/* actual valu */
/* index into m e m [ ] */
NUMBER
VAR
expr
UNARYMINUS
/* nothing */
! list '\n'
! list expr '\n'
list error '\n'
{ printf("\tX.8g\n",
{ yyerrok; }
NUMBER
{ $$ = mem[$ 1]; }
VAR
{ $ $ = mem[$ 1] = $ 3; }
V A R ' = expr
'+' expr { $$ = $1 + $3; }
expr '
expr { $$ = $1 - $3; }
expr '
expr { $ $ = $ 1 * $ 3 ; }
expr '
expr '/' expr {
if ($3 == 0.0)
e x e c e r r o r ( " d i v i s i n b y zero",
$$ = $1 / $3; }
' ( '
expr ')'
{ $$ = $2; }
expr
Xprec U N A R Y M I N U S
{ $$ = -$2; }
$2);
);
/* end of g r a m m a r */
244
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 8
/* h o c 2 */
p r o g n a m e = argv[0];
setjmp(begin);
signal(SIGFPE, fpecatch);
yyparse();
}
e x e c e r r o r ( s , t) /* recover from r u n - t i m e error
char *s, *t;
{
w a r n i n g ( s , t);
l o n g j m p ( b e g i n , 0);
}
fpecatch()
/* c a t c h floating
execerror("floating
point
*/
exceptions
point e x c e p t i o n " ,
*/
(char *) 0);
}
For debugging, we found it convenient to have e x e c e r r o r cali a b o r t (see
a b o r t ( 3 ) ) , which causes a core dump that can be perused with a d b or s d b .
Once the program is fairly robust, a b o r t is replaced by l o n g j m p .
The lexical analyzer is a little different in h o c 2 . There is an extra test for
a lower-case letter, and since y y l v a l is now a unin, the proper member has
to be set before y y l e x returns. Here are the parts that have changed:
CHAPTER 8
PROGRAM DEVELOPMENT
yylex()
245
/* h o c 2 */
if (c ==
!! i s d i g i t ( c ) ) {
/* n u m b e r */
n g e t e ( c , stdin);
scanf("%lf", & y y l v a l . v a l ) ;
r e t u r n NUMBER;
}
if
(islower(c)) {
y y l v a l . i n d e x = c - 'a'; /* A S C I I only */
return V A R ;
A g a i n , notice how the token type (e.g., NUMBER) is distinct f r o m its valu
(e.g., 3.1416).
Let us illustrate variables and error recovery, the new things in h o c 2 :
$ hoc2
x = 355
355
y = 113
113
p = x/z
h o c 2 : d i v i s i n by zero near
line 4
Error recovery
x/y
3. 1415929
1e30
* 1e30
Overflow
line 5
eos
int
atan
abs
exp
log
log10
246
CHAPTER 8
single character, it isn't much extra effort to permit variable a m e s to be arbitrarily long as well. We will need a m o r e sophisticated symbol table to k e e p
track of these variables, but once we have it, we can pre-load it with a m e s
and vales for some useful constants:
PI
E
GAMMA
DEG
PHI
3.14159265358979323846
2.71828182845904523536
0.57721566490153286060
57.29577951308232087680
1.61803398874989484820
ir
Base of natural logarithms
E u l e r - M a s c h e r o n i constant
Degrees per radian
Golden ratio
exp(2.3*log(1.5))
2.5410306
sin(PI/2)
1
atan(1)+DEG
45
T h e program that results f r o m all these changes is big enough (about 250
lines) that it is best split into separate files for easier editing and faster compilation. T h e r e are now five files instead of one:
PROGRAM DEVELOPMENT
CHAPTER 8
hoc.y
247
hoc. h
symbol.c
init.c
math.c
This requires that we learn more about how to organize a multi-file C program, and more about make so it can do some of the work for us.
We'll get back to make shortly. First, let us look at the symbol table code.
A symbol has a ame, a type (it's either a VAR or a BLTIN), and a valu. If
the symbol is a VAR, the valu is a d o u b l e ; if the symbol is a built-in, the
valu is a pointer to a function that returns a d o u b l e . This information is
needed in h o c . y , s y m b o l . c , and i n i t . c . We could just make three copies,
but it's too easy to make a mistake or forget to update one copy when a change
is made. Instead we put the common information into a header file h o c . h
that will be included by any file that needs it. (The suffix .h is conventional
but not enforced by any program.) We will also add to the m a k e f i l e the fact
that these files depend on h o c . h , so that when it changes, the necessary
recompilations are done too.
$ cat hoc.h
typedef
} u;
struct S y m b o l
*next;
} Symbol;
Symbol
*install(), *lookup();
$
/* to link to another
*/
The type UNDEF is a VAR that has not yet been assigned a valu.
The symbols are linked together in a list using the next field in Symbol.
The list itself is local to symbol. c; the only access to it is through the functions lookup and install. This makes it easy to change to symbol table
organization if it becomes necessary. (We did that once.) lookup searches
the list for a particular ame and returns a pointer to the Symbol with that
ame if found, and zero otherwise. The symbol table uses linear search, which
is entirely adequate for our interactive calculator, since variables are looked up
only during parsing, not execution. install puts a variable with its associated type and valu at the head of the list. emalloc calis malloc, the standard storage allocator (malloc(3)), and checks the result. These three routines are the contents of symbol.c. The file y.tab.h is generated by running yacc -d; it contains #define statements that yacc has generated for
tokens like NUMBER, VAR, BLTIN, etc.
248
CHAPTER 8
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
$ cat
symbol.c
#include
#include
static
"hoc.h"
"y.tab.h"
Symbol *symlist
=0;
Symbol *lookup(s)
char *s;
{
Symbol *sp;
/ * symbol t a b l e :
linked
list
*/
for
t, d)
*/
S y m b o l sp;
char *emalloc();
sp = (Symbol *) e m a l l o c ( s i z e o f ( S y m b o l ) ) ;
s p - > n a m e = e m a l l o c ( s t r l e n ( s ) + 1 ) ; /* +1 for '\0' */
s t r c p y ( s p - > n a m e , s);
sp->type = t;
sp->u.val = d;
sp->next = symlist; /* put at front of list */
symlist = sp;
r e t u r n sp;
char * e m a l l o c ( n )
u n s i g n e d n;
*/
of m e m o r y " ,
(char *) 0);
}
The file init.c contains definitions for the constants (PI, etc.) and function pointers for built-ins; they are installed in the symbol table by the function
init, which is called by main.
CHAPTER 8
$ cat
PROGRAM DEVELOPMENT
249
init.c
#include
#include
#include
"hoc.h"
"y.tab.h"
<math.h>
e x t e r n double
Log(), Log10(), Exp(), Sqrt(), integer();
static struct {
/* Constants */
char
*name;
double
cval;
} consts[] = {
"PI",
3.,14159265358979323846,
"E" ,
2..71828182845904523536,
" G A M M A " , 0., 5 7 7 2 1 5 6 6 4 9 0 1 5 3 2 8 6 0 6 0 , / * Euler */
"DEG",
57.,29577951308232087680,
/ * d e g / r a d i a n */
"PHI",
1..61803398874989484820,
/ * g o l d e n ratio */
o,
0
};
static struct {
/* B u i l t - i n s */
char
*name;
double
(*func)();
} builtins[] = {
"sin",
sin,
"eos",
eos,
"atan", atan,
"log",
Log,
/ * checks argument * /
"log10" , Log10, / * checks argument * /
"exp",
Exp,
/ * checks argument * /
"sqrt", Sqrt,
/ *
checks argument * /
"int",
integer
"abs",
f abs,
0,
0
};
init()
/* install constants and b u i l t - i n s in table */
{
int i;
Symbol *s;
for
for
(i = 0; consts[i].ame; i++)
install(consts[i].ame, VAR, consts[i].cval);
(i = 0; b u i l t i n s [ i ] . a m e ; i++) {
s = i n s t a l l ( b u i l t i n s [ i ] . a m e , BLTIN, 0.0);
s->u.ptr = builtins[i].func;
The data is kept in tables rather than being wired into the code because tables
are easier to read and to change. The tables are declared static so that they
are visible only within this file rather than throughout the program. We'll
come back to the math routines like Log and Sqrt shortly.
250
CHAPTER 8
With the foundation in place, we can move on to the changes in the grammar that make use of it.
$ cat hoc.y
%{
# i n c l u d e "hoc.h"
extern
double
Pow();
%}
%union {
double
val;
/* actual valu */
Symbol
*sym;
/* symbol table p o i n t e r
}
%token
<val>
NUMBER
%token
<sym>
VAR BLTIN UNDEF
%type
<val>
expr asgn
%right
%left
'+'
%left
Xleft
UNARYMINUS
""
/ * exponentiation * /
%right
list:
!
!
!
/* nothing */
list '\n'
list a s g n '\n'
list expr '\n'
list error '\n'
asgn:
VAR
'=' expr
expr:
NUMBER
*/
{ printf("\t%.8g\n",
{ yyerrok; }
{ $$ = $1->u.val = $3 ; $1->type
($ 1->type == U N D E F )
execerror("undefined
$$ = $1->u.val; }
$2);
= VAR;
V A R { if
variable",
$1->name);
asgn
B L T I N '(' expr ')'
{ $$ = (*($ 1 - > u . p t r ) ) ( $ 3 ) ;
expr '+' expr { $ $ = $ 1 + $ 3 ; }
expr
expr { $$ = $1 $3; }
expr
expr { $ $ = $ 1 * $ 3 ; }
expr '/' expr {
if ($3 == 0.0)
e x e c e r r o r ( " d i v i s i n by zero", "");
$$ = $1 / $3; }
expr '*' expr { $$ = Pow($1, $3); }
'(' expr ')'
{ $$ = $2; }
expr
%prec U N A R Y M I N U S
{ $$ = -$2; }
%%
/* end of g r a m m a r */
CHAPTER 8
PROGRAM DEVELOPMENT
251
/* h o c 3 */
if
(isalpha(c)) {
Symbol *s;
char sbuf[100], *p = sbuf;
do {
*p++ = c;
} while ((c=getchar()) != EOF && i s a l n u m ( c ) )
n g e t e ( c , stdin);
*p = '\0';
if ( ( s = l o o k u p ( s b u f ) ) == 0)
s = i n s t a l l ( s b u f , U N D E F , 0.0);
y y l v a l . s y m = s;
return s - > t y p e == U N D E F ? V A R : s - > t y p e ;
}
m a i n has one extra line, which calis the initialization routine i n i t
install built-ins and pre-defined ames like PI in the symbol table.
to
252
CHAPTER 8
main(argc, argv)
/* hoc3
char *argv[];
{
int f p e c a t c h ( ) ;
*/
p r o g n a m e = argv[0];
init();
setjmp(begin);
signal(SIGFPE, fpecatch);
yyparse();
}
"log");
{
return e r r c h e c k ( l o g 1 0 ( x ) ,
}
double
"log10");
Exp(x)
d o u b l e x;
{
return e r r c h e c k ( e x p ( x ) , "exp");
}
double
Sqrt(x)
double x;
{
return e r r c h e c k ( s q r t ( x ) ,
"sqrt");
CHAPTER 8
PROGRAM DEVELOPMENT
253
d o u b l e Pow(x, y )
double x, y;
{
return errcheck(pow(x,y), "exponentiation");
}
double i n t e g e r ( x )
d o u b l e x;
{
return (double)(long)x;
}
d o u b l e e r r c h e c k ( d , s)
/* check result of l i b r a r y cali */
d o u b l e d;
char *s;
{
if (errno == EDOM) {
errno = 0;
execerror(s, "argument out of d o m a i n " ) ;
} else if (errno == E R A N G E ) {
errno = 0;
execerror(s, "result out of range");
}
return d;
}
hoc.y
conflicts:
$
1 shift/reduce
254
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 8
list
ex
listt
(empty)
list
as
x = 1
list
\n
(empty)
x = 1
\n
The parser can decide that the asgn should be reduced to an expr and then to a
list, as in the parse tree on the left, or it can decide to use the following \n
immediately ( " s h i f t " ) and convert the whole thing to a list without the intermedate rule, as in the tree on the right. Given the ambiguity, y a c c chooses
to shift, since this is almost always the right thing to do with real grammars.
You should try to understand such messages, to be sure that y a c c has made
the right decisin.t Running y a c c with the option -v produces a voluminous
file called y . o u t p u t that hints at the origin of conflicts.
Exercise 8-5. As h o c 3 stands, it's legal to say
PI
= 3
Is this a good idea? How would you change h o c 3 to prohibit assignment to "constants"?
Exercise 8-6. Add the built-in function a t a n 2 ( y , x ) , which returns the angle whose
tangent is y / x . Add the built-in r a n d ( ), which returns a floating point random variable uniformly distributed on the interval (0,1). How do you have to change the grammar to allow for built-ins with different numbers of arguments?
Exercise 8-7. How would you add a facility to execute commands from within hoc,
similar to the ! feature of other UNIX programs?
Exercise 8-8. Revise the code in m a t h . c to use a table instead of the set of essentially
identical functions that we presented.
Another digression on make
Since the program for h o c 3 now lives on five files, not one, the m a k e f i l e
is more complicated:
t The y a c c message "reduce/reduce conflict" indicates a serious problem, more often the symptom
of an outright error in the grammar than an intentional ambiguity.
CHAPTER 8
$ cat
PROGRAM DEVELOPMENT
makefile
Y F L A G S = -d
O B J S = hoc.o
# forc creation of y . t a b . h
init.o m a t h . o symbol.o
# abbreviation
hoc3:
$(OBJS)
cc $ ( O B J S ) -lm -o h o c 3
hoc.o:
hoc.h
init.o
255
symbol.o:
hoc.h y.tab.h
pr:
@pr h o c . y h o c . h init.c m a t h . c
symbol.c m a k e f i l e
clean:
rm -f $ ( O B J S ) y . t a b . [ c h ]
The YFLAGS = - d line adds the option - d t o the y a c c c o m m a n d line generated b y m a k e ; this tells y a c c t o produce the y . t a b . h file o f # d e f i n e
statements. The OBJS=... line defines a shorthand for a construct to be used
several times subsequently. The syntax is not the same as for shell variables
the parentheses are m a n d a t o r y . The flag - l m causes the m a t h library to be
searched for the mathematical functions.
h o c 3 now d e p e n d s o n four . o files; some o f the . o files depend o n . h
files. Given these dependencies, m a k e can deduce what recompilation is
needed after changes are m a d e to any of the files involved. If you want to see
what m a k e will do without actually running the processes, try
$ make
-n
On the other h a n d , if you want to forc the file times into a consistent state,
the -t ( " t o u c h " ) option will update them without doing any compilation steps.
Notice that we have added not only a set of dependencies for the source
files but miscellaneous utility routines as well, all neatly encapsulated in one
place. By d e f a u l t , m a k e makes the first thing listed in the m a k e f i l e , but if
you a m e an item that labels a dependency rule, like s y m b o l . o or p r , that
will be m a d e instead. An empty dependency is taken to m e a n that the item is
never " u p to d a t e , " so that action will always be done when requested. T h u s
$ make pr
I lpr
produces the listing you asked for on a line printer. ( T h e leading @ in " @ p r "
suppresses the echo of the c o m m a n d being executed by m a k e . ) A n d
$ make
clean
in
the
makefile
is often
256
CHAPTER 8
preferable to a shell file as a way to keep all the related computations in a single file. A n d m a k e is not restricted to program development it is valuable
for packaging any set of operations that have time dependencies.
A digression on l e x
T h e p r o g r a m l e x creates lexical analyzers in a m a n n e r analogous to the
way that y a c c creates parsers: you write a specification of the lexical rules of
your language, using regular expressions and f r a g m e n t s of C to be executed
when a matching string is f o u n d . l e x translates that into a recognizer. l e x
and y a c c cooperate by the same mechanism as the lexical analyzers we have
already written. We are not going into any great detail on l e x here; the following discussion is mainly to interest you in learning m o r e . See the reference
m a n u a l for l e x in V o l u m e 2B of the UNIX Programmer's Manual.
First, here i s the l e x program, f r o m the file l e x . l ; i t replaces the function y y l e x that we have used so far.
$ cat lex.l
%{
# i n c l u d e "hoc.h"
# i n c l u d e "y.tab.h"
extern int lineno;
%}
%%
[ \t]
{ ; }
/* skip blanks and t a b s */
[0-9]+\.?![0-9]*\.[0-9]+ {
s s c a n f ( y y t e x t , "%lf", k y y l v a l . v a l ) ; r e t u r n NUMBER;
[a-zA-Z][a-zA-Z0-9]* {
Symbol *s;
if ((s=lookup(yytext)) == 0)
s = i n s t a l l ( y y t e x t , U N D E F , 0.0);
y y l v a l . s y m = s;
return s->type == UNDEF ? V A R : s - > t y p e ; }
\n
{ lineno++; return '\n'; }
/* e v e r y t h i n g else */
{ return yytext[0]; }
$
CHAPTER 8
$ cat
PROGRAM DEVELOPMENT
257
makefile
Y F L A G S = -d
O B J S = h o c . o lex.o init.o m a t h . o s y m b o l . o
hoc3:
$(OBJS)
cc $ ( O B J S ) -lm -11 -o h o c 3
hoc.o:
hoc.h
lex.o i n i t . o symbol.o:
hoc.h y.tab.h
lex.l
lex
lex.l
cc
-c lex.yy.c
rm lex.yy.c
mv lex.yy.o lex.o
cc h o c . o lex.o init.o m a t h . o s y m b o l . o - 1 1 - l m -o h o c 3
$
258
CHAPTER 8
main problem with l e x (aside from requiring that the user learn yet another
language) is that it tends to be slow to run and to produce bigger and slower
recognizers than the equivalent C versions. It is also somewhat h a r d e r to
adapt its input mechanism if one is doing anything unusual, such as error
recovery or even input f r o m files. None of these issues is serious in the context of h o c . T h e main limitation is space: it takes m o r e pages to describe the
l e x versin, so (regretfully) we will revert to C for subsequent lexical
analysis. It is a good exercise to do the l e x versions, however.
Exercise 8-9. Compare the sizes of the two versions of h o c 3 . Hint: see s i z e ( l ) .
8 . 4 Stage 4: C o m p i l a t i o n into a m a c h i n e
We are heading towards h o c 5 , an interpreter for a language with control
flow. h o c 4 is an intermedate step, providing the same functions as h o c 3 , but
implemented within the interpreter f r a m e w o r k of h o c 5 . We actually wrote
h o c 4 this way, since it gives us two p r o g r a m s that should behave identically,
which is valuable for debugging. As the input is parsed, h o c 4 generates code
for a simple computer instead of immediately computing answers. Once the
end of a statement is reached, the generated code is executed ( " i n t e r p r e t e d " )
to compute the desired result.
T h e simple computer is a stack machine: when an o p e r a n d is e n c o u n t e r e d , it
is pushed onto a stack ( m o r e precisely, code is generated to push it o n t o a
stack); most operators operate on items on the top of the stack. For example,
to handle the assignment
x = 2 * y
the following code is generated:
constpush
2
varpush
y
eval
mu
varpush
X
assign
pop
STOP
W h e n this code is executed, the expression is evaluated and the result is stored
in x, as indicated by the comments. The final p o p clears the valu off the
stack because it is not needed any longer.
Stack machines usually result in simple interpreters, and ours is no exception it's just an array containing operators and operands. T h e operators are
the machine instructions; each is a function cali with its a r g u m e n t s , if any, following the instruction. Other o p e r a n d s may already be on the stack, as they
CHAPTER 8
PROGRAM DEVELOPMENT
259
%token
%right
%left
%left
%left
%right
%%
list:
code(c1); c o d e ( c 2 )
code(c1); code(c2); c o d e ( c 3 )
/* symbol table p o i n t e r */
/* machine i n s t r u c t i o n */
<sym>
N U M B E R VAR BLTIN U N D E F
'='
'+'
'/'
UNARYMINUS
'A/
/* exponentiation */
!
!
!
!
/* nothing */
list '\n'
list a s g n '\n'
{ code2(pop, STOP); r e t u r n 1; }
list expr '\n'
{ code2(print, STOP); r e t u r n 1; }
list error '\n' { y y e r r o k ; }
i
asgn:
VAR
'=' expr
{ code3(varpush,(Inst)$1,assign);
260
expr:
!
!
!
!
!
!
!
!
!
!
CHAPTER 8
NUMBER
{ c o d e 2 ( c o n s t p u s h , (Inst)$1); }
VAR
{ c o d e 3 ( v a r p u s h , (Inst)$1, e v a l ) ; }
asgn
B L T I N '(' expr ')' { c o d e 2 ( b l t i n , (Inst)$ 1->u.ptr);
'(' expr ')'
expr '+' expr { code(add); }
expr ' - ' expr { code(sub); }
expr '*' expr { code(mu); }
expr '/' expr { code(div); }
expr ,/v/ expr { code(power); }
expr
%prec U N A R Y M I N U S
{ code(negate); }
%%
/* end of g r a m m a r */
Inst is the data type of a machine instruction (a pointer to a function returning an int), which we will return to shortly. Notice that the arguments to
c o d e are function ames, that is, pointers to functions, or other vales tha
are coerced to function pointers.
We have changed m a i n somewhat. The parser now returns after each
statement or expression; the code that it generated is executed. yyparse
returns zero at end of file.
main(argc, argv)
char *argv[];
{
int fpecatch();
/* h o c 4 */
p r o g n a m e = argv[0];
init();
setjmp(begin);
s i g n a l ( S I G F P E , fpecatch);
for (initcode(); y y p a r s e ( ) ;
execute(prog);
r e t u r n 0;
initcodeO)
The lexical analyzer is only a little different. The main change is that
numbers have to be preserved, not used immediately. The easiest way to do
this is to install them in the symbol table along with the variables. Here is the
changed part of yylex:
CHAPTER 8
PROGRAM DEVELOPMENT
yylex()
261
/* h o c 4 */
if
(c ==
!! i s d i g i t ( c ) ) {
/* n u m b e r */
double d;
n g e t e ( c , stdin);
scanf ( "%lf " , Std) ;
y y l v a l . s y m = install("", N U M B E R , d);
return NUMBER;
t y p e d e f u n i n Datum {
double
val;
Symbol
*sym;
} Datum;
extern
Datum pop();
/* interpreter
stack type */
instruction
*/
Inst prog[];
eval(), add(), sub(), m u l ( ) , div(), n e g a t e ( ) , p o w e r ( )
a s s i g n ( ) , b l t i n ( ) , v a r p u s h ( ) , c o n s t p u s h ( ) , print();
The routines that execute the machine instructions and maniplate the stack
are kept in a new file called c o d e . c . Since it is about 150 lines long, we will
262
CHAPTER 8
show it in pieces.
$ cat code.c
#include
#include
"hoc.h"
"y.tab.h"
#define NSTACK
static
Datum
static
Datum
256
stack[NSTACK];
*stackp;
#define NPROG
2000
Inst
prog[NPROG];
Inst
*progp;
Inst
*pc;
/* the stack */
/* next free spot on stack */
/* the m a c h i n e */
/* next free spot for code g e n e r a t i o n */
/* p r o g r a m counter d u r i n g e x e c u t i o n */
initcode()
/* initialize for code g e n e r a t i o n
{
stackp = stack;
p r o g p = prog;
}
*/
{
if
(char *) 0);
}
Datum p o p ( )
/* pop and return top elem from stack */
{
if (stackp <= stack)
e x e c e r r o r ( " s t a c k u n d e r f l o w " , (char *) 0);
return * - - s t a c k p ;
}
T h e machine is generated during parsing by calis to the function c o d e ,
which simply puts an instruction into the next free spot in the array p r o g . it
returns the location of the instruction (which is not used in h o c 4 ) .
CHAPTER 8
Inst
PROGRAM DEVELOPMENT
*code(f)
/* install one i n s t r u c t i o n or o p e r a n d
Inst f;
263
*/
{
Inst *oprogp = progp;
if (progp >= &.prog[NPROG] )
e x e c e r r o r ( " p r o g r a m too big",
*progp++ = f;
return oprogp;
(char *) 0);
Execution of the machine is simple; in fact, it's rather neat how small the
routine is that " r u n s " the machine once it's set up:
execute(p)
/* run the m a c h i n e */
Inst *p;
{
for (pe = p; *pc != STOP; )
(*(*pc++) ) ( );
}
Each eyele executes the function pointed to by the instruction pointed to by the
program counter p e , and increments pe so it's ready for the next instruction.
An instruction with opcode STOP terminates the loop. Some instructions, such
as c o n s t p u s h and v a r p u s h , also increment pe to step over any arguments
that follow the instruction.
constpush()
/* push constant o n t o stack
{
Datum d;
d.val = ((Symbol * ) * p c + + ) - > u . v a l ;
push(d);
}
*/
varpush()
*/
/* push v a r i a b l e o n t o stack
Datum d;
d.sym = (Symbol *)(*pc++);
push(d);
}
The rest of the machine is easy. For instance, the arithmetic operations are
all basically the same, and were created by editing a single prototype. Here is
add:
264
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
add()
{
CHAPTER 8
}
The remaining routines are equally simple.
eval()
{
/* evalate v a r i a b l e on stack */
Datum d;
d = pop();
if (d.sym~>type == U N D E F )
execerror("undefined
d . v a l = d.sym->u.val;
push(d);
variable", d.sym->name);
}
assign()
{
*/
}
print()
{
}
bltin()
{
it */
d.val);
*/
(*)())(*pc++))(d.val);
The hardest part is the cast in b l t i n , which says that * p c should be cast to
"pointer to function returning a d o u b l e , " and that function executed with
d . v a l a s argument.
The diagnostics in e v a l and a s s i g n should never occur if everything is
PROGRAM DEVELOPMENT
CHAPTER 8
265
working properly; we left them in in case some program error causes the stack
to be curdled. The overhead in time and space is small compared to the benefit of detecting the error if we make a careless change in the program. (We
did, several times.)
C's ability to maniplate pointers to functions leads to compact and efficient
code. An alternative, to make the operators constants and combine the semantic functions into a big s w i t c h statement in e x e c u t e , is straightforward and
is left as an exercise.
A third digression on make
As the source code for h o c grows, it becomes more and more valuable to
keep track mechanically of what has changed and what depends on that. The
beauty of m a k e is that it automates jobs that we would otherwise do by hand
(and get wrong sometimes) or by creating a specialized shell file.
We have made two improvements to the m a k e f i l e . The first is based on
the observation that although several files depend on the y a c c - d e f i n e d constants in y . t a b . h , there's no need to recompile them unless the constants
change changes to the C code in h o c . y don't affect anything else. In the
new m a k e f i l e the .o files depend on a new file x . t a b . h that is updated
only when the contents of y . t a b . h change. The second improvement is to
make the rule for pr (printing the source files) depend on the source files, so
that only changed files are printed.
The first of these changes is a great time-saver for larger programs when
the grammar is static but the semantics are not (the usual situation). The
second change is a great paper-saver.
Here is the new m a k e f i l e for h o c 4 :
Y F L A G S = -d
OBJS = h o c . o code.o init.o m a t h . o s y m b o l . o
hoc4:
$(OBJS)
cc $(OBJS) -lm -o h o c 4
h o c . o c o d e . o init.o s y m b o l . o :
hoc.h
c o d e . o i n i t . o symbol.o: x . t a b . h
x.tab.h: y.tab.h
- c m p -s x . t a b . h y . t a b . h
pr:
h o c . y h o c . h code.c
@ p r $?
@ t o u c h pr
i! cp y . t a b . h x . t a b . h
init.c m a t h . c
clean:
rm -f $ ( O B J S ) [xy].tab.[ch]
symbol.c
266
CHAPTER 8
The
before cmp tells m a k e to carry on even if the cmp fails; this permits
the process t o work even i f x . t a b . h doesn't exist. ( T h e - s option causes
cmp to produce no output but set the exit status.) T h e symbol $? e x p a n d s into
the list of items f r o m the rule that are not up to date. R e g r e t t a b l y , m a k e ' s
notational conventions are at best loosely related to those of the shell.
To Ilstrate how these operate, suppose that everything is up to d a t e .
Then
$ touch hoc. y
$ make
yacc - d h o c . y
Change dale of h o c .y
conflicts: 1 shift/reduce
cc -c y.tab.c
rm y . t a b . c
mv y . t a b . o h o c . o
cmp - s x . t a b . h y . t a b . h ! ! c p y . t a b . h x . t a b . h
cc h o c . o c o d e . o i n i t . o math.o symbol.o -lm -o hoc4
$ make -n pr
Print changed files
pr hoc.y
touch pr
$
Notice that nothing was recompiled except h o c . y , because the y . t a b . h file
was the same as the previous one.
Exercise 8-10. Make the sizes of s t a c k and p r o g dynamic, so that h o c 4 never runs
out of space if memory can be obtained by calling mal l o e .
Exercise 8-11. Modify h o c 4 to use a s w i t c h on the type of operation in e x e c u t e
instead of calling functions. How do the versions compare in lines of source code and
execution speed? How are they likely to compare in ease of maintenance and growth?
PROGRAM DEVELOPMENT
CHAPTER 8
$ cat
%{
hoc.y
#include "hoc.h"
#define code2(c1,c2)
#define code3(c1,c2,c3)
%union
}
%token
%type
%right
%left
Xleft
Xleft
Xleft
%left
%left
%right
267
code(c1);
code(c1);
code(c2)
code(c2);
code(c3)
{
Symbol
Inst
*sym;
*inst;
<sym>
<inst>
IF ELSE
i f end
OR
AND
G T G E LT L E E Q N E
/+ / / _ /
UNARYMINUS
NOT
%%
list:
/* nothing */
l i s t '\n'
l i s t a s g n '\n'
l i s t s t m t '\n'
l i s t e x p r '\n'
l i s t e r r o r '\n'
'=' e x p r
{
{
{
{
c o d e 2 ( p o p , S T O P ) ; r e t u r n 1; }
c o d e ( S T O P ) ; r e t u r n 1; }
c o d e 2 ( p r i n t , S T O P ) ; r e t u r n 1; }
yyerrok; }
asgn:
VAR
{ $$=$3;
code3(varpush,(Inst)$1,assign);
stmt:
{ code(pop); }
{ c o d e ( p r e x p r ) ; $$ = $2; }
w h i l e c o n d s t m t end {
/* body of loop * /
( $ 1 ) [ 1 ] = (Inst)$3;
/* e n d , if c o n d f a i l s * /
( $ 1 ) [ 2 ] = (Inst)$4; }
/* e l s e - l e s s if */
if c o n d s t m t end {
Inst)$3;
/* thenpart * /
($1)[1] =
/* e n d , if c o n d f a i l s */
( $ 1 ) [ 3 ] = Inst)$4; }
/* if w i t h e l s e */
if c o n d s t m t end E L S E stmt end {
($ 1) C1 ] = ( I n s t ) $ 3 ;
/* t h e n p a r t * /
($ 1)[2] = ( I n s t ) $ 6 ;
/* e l s e p a r t * /
($ 1) [3] = ( I n s t ) $ 7 ; }
/* e n d , if c o n d f a i l s */
'{' s t m t l i s t
{ $$ = $2; }
cond:
'(' e x p r
while:
WHILE
expr
PRINT expr
')'
{ code(STOP);
$$ = $2;
{ $$ = c o d e 3 ( w h i l e c o d e ,
STOP,
}
STOP);
268
CHAPTER 8
if:
IF
end:
/* nothing
*/
{ code(STOP);
$$ = p r o g p ;
stmtlist
/* nothing */
stmtlist '\n'
stmtlist stmt
{ $$ = progp;
{ $$=code(ifcode);
code3(STOP,
STOP, S T O P ) ;
NUMBER
{ $$ = c o d e 2 ( c o n s t p u s h , (Inst)$1); }
VAR
{ $$ = c o d e 3 ( v a r p u s h , (Inst)$1, eval);
asgn
B L T I N '(' expr ' ) '
{ $$ = $3; c o d e 2 ( b l t i n , ( I n s t ) $ 1->u.ptr); }
'(' expr ')'
{ $$ = $ 2 ; }
expr '+' expr { code(add);
expr
expr { code(sub);
expr '*' expr { code(mu);
expr '/' expr { code(div);
expr '~' expr { code (power); }
' - ' expr
%prec U N A R Y M I N U S
{ $$ = $2; c o d e ( n e g a t e ) ;
expr GT expr
{ code(gt); }
expr GE expr
{ code(ge); }
expr LT expr
{ code(lt); }
expr LE expr
{ code(le); }
expr EQ expr
{ code(eq); }
expr NE expr
{ code(ne); }
expr A N D expr { code(and); }
expr OR expr
{ code(or); }
N O T expr
{ $$ = $2; code(not); }
%%
The grammar has five shift/reduce conflicts, all like the one mentioned in
hoc3.
Notice that STOP instructions are now generated in several places to termnate a sequence; as before, p r o g p is the location of the next instruction that
will be generated. When executed these STOP instructions will termnate the
loop in e x e c u t e . The production for e n d is in effect a subroutine, called
from several places, that generates a STOP and returns the location of the
instruction that follows it.
The code generated for w h i l e and if needs particular study. When the
keyword w h i l e is encountered, the operation w h i l e c o d e is generated, and
its position in the machine is returned as the valu of the production
while:
WHILE
At the same time, however, the two following positions in the machine are also
reserved, to be filled in later. The next code generated is the expression that
makes up the condition part of the w h i l e . The valu returned by c o n d is the
CHAPTER 8
PROGRAM DEVELOPMENT
269
beginning of the code for the condition. After the whole w h i l e statement has
been recognized, the two extra positions reserved after the w h i l e c o d e
instruction are filled with the locations of the loop body and the statement that
follows the loop. (Code for that statement will be generated next.)
! while cond stmt end {
($1)[1] = (Inst)$3;
($1)[2] = (Inst)$4;
/* body of loop */
/* end, if cond fails */
The situation for an if is similar, except that three spots are reserved, for
the then and else parts and the statement that follows the i f . We will
return shortly to how this operates.
Lexical analysis is somewhat longer this time, mainly to pick up the additional operators:
270
CHAPTER 8
yylex()
/* hoc5
switch (c) {
case
case
case
case ' ! '
case ' !'
case
case ' \n' :
default:
}
*/
return follow('=
return follow('=
return follow('=
return follow('=
return follow('!
return f o l l o w ( ' &
lineno++; r e t u r n
return c;
, GE, GT) ;
, LE, L T ) ;
, EQ, ' = ' );
, NE, N O T ) ;
, OR, ' ');
, A N D , '&');
' \n' ;
f o l l o w looks ahead one character, and puts it back on the input with n g e t e
if it was not what was expected.
f o l l o w ( e x p e c t , ifyes, ifno)
{
int c = g e t c h a r ( ) ;
>=, etc. */
if
(c == e x p e c t )
return ifyes;
u n g e t c ( c , stdin);
return ifno;
}
int (*Inst)();
/* m a c h i n e
STOP
(Inst) 0
instruction
*/
extern
extern
extern
extern
extern
extern
$
Most of c o d e . c is the same too, although there are a lot of obvious new routines to handle the relational operators. The function le ("less than or equal
to") is a typical example:
PROGRAM DEVELOPMENT
CHAPTER 8
271
le ( )
{
Datum d1, d2 ;
d2 = pop();
d1 = pop();
d l . v a l = (double)(d1.val
push(d1);
<= d2.val);
The two routines that are not obvious are w h i l e c o d e and i f c o d e . The
critical point for understanding them is to realize that e x e c u t e marches along
a sequence of instructions until it finds a STOP, whereupon it returns. Code
generation during parsing has carefully arranged that a STOP terminates each
sequence of instructions that should be handled by a single cali of e x e c u t e .
The body of a w h i l e , and the condition, t h e n and e l s e parts of an if are
all handled by recursive calis to e x e c u t e that return to the parent level when
they have finished their task. The control of these recursive tasks is done by
code i n w h i l e c o d e and i f c o d e that corresponds directly t o w h i l e and i f
statements.
whilecode()
{
Datum d;
Inst *savepc
= pe;
/* loop body #/
execute(savepc+2);
/* c o n d i t i o n */
d = pop();
while (d.val) {
execute(*((Inst **)(savepc)));
/* body */
execute(savepc+2);
d = pop);
}
pe = *((Inst **)(savepc+1));
/* next statement */
}
272
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 8
ifcode()
{
Datum d;
Inst savepc
= pe;
/* t h e n part
*/
execute(savepc+3);
/* c o n d i t i o n */
d = pop();
if (d.val)
execute(*((Inst * * ) ( s a v e p c ) ) ) ;
else if (*((Inst * * ) ( s a v e p c + 1 ) ) ) /* else part? */
execute(*((Inst **)(savepc+1)));
pe = *((Inst **)(savepc+2));
/* next stmt */
}
struct {
char
*name
int
kval;
} keywords[] = {
"if " ,
"else",
"while",
"print",
0,
/* K e y w o r d s
*/
IF,
ELSE,
WHILE,
PRINT,
0,
};
(i = 0; k e y w o r d s [ i ] . a m e ; i++)
install(keywords[i].ame, keywordsti]kval,
0.0);
/* print numeric v a l u
*/
Datum d;
d = pop();
p r i n t f ( " % . 8 g \ n " , d.val);
}
This is not the p r i n t function that is called automatically to print the final
result of an evaluation; that one pops the stack and adds a tab to the output.
h o c 5 is by now quite a serviceable calculator, although for serious programming, more facilities are needed. The following exercises suggest some
CHAPTER 8
PROGRAM DEVELOPMENT
273
possibilities.
Exercise 8-12. Modify hoc5 to print the machine it generates in a readable form for
debugging.
Exercise 8-13. Add the assignment operators of C, such as +=, * = , etc., and the increment and decrement operators ++ and
Modify &.&. and ! ! so they guarantee leftto-right evaluation and early termination, as in C.
Exercise 8-14. Add a f o r statement like that of C to hoc5. Add b r e a k and
continu.
Exercise 8-15. How would you modify the grammar or the lexical analyzer (or both) of
hoc5 to make it more forgiving about the placement of newlines? How would you add
semicolon as a synonym for newline? How would you add a comment convention?
What syntax would you use?
Exercise 8-16. Add interrupt handling to hoc5, so that a runaway computation can be
stopped without losing the state of variables already computed.
Exercise 8-17. It is a nuisance to have to create a program in a file, run it, then edit
the file to make a trivial change. How would you modify hoc5 to provide an edit command that would cause you to be placed in an editor with a copy of your hoc program
already read in? Hint: consider a t e x t opcode.
8.6 Stage 6: Functions and procedures; input/output
The final stage in the evolution of h o c , at least for this book, is a major
increase in functionality: the addition of functions and procedures. We have
also added the ability to print character strings as well as numbers, and to read
vales from the standard input. h o c 6 also accepts filename arguments, including the ame
for the standard input. Together, these changes add 235
lines of code, bringing the total to about 810, but in effect convert h o c from a
calculator into a programming language. We won't show every line here;
Appendix 3 is a listing of the entire program so you can see how the pieces fit
together.
In the grammar, function calis are expressions; procedure calis are statements. Both are explained in detail in Appendix 2, which also has some more
examples. For instance, the definition and use of a procedure for printing all
the Fibonacci numbers less than its argument looks like this:
274
CHAPTER 8
$ cat fib
proc f i b ( ) {
a = 0
b = 1
while (b < $1) {
print b
c = b
b = a+b
a = c
}
print "\n"
}
$ hoc6 fib
fib(1000)
1 1 2 3 5 8 13 21 34 55 89
$ hoc6
fac(O)
fac
1 else r e t u r n $1 * f a c ( $ 1 - 1 )
fac(7)
5040
fac(10)
3628800
PROGRAM DEVELOPMENT
CHAPTER 8
$ cat
275
hoc.y
%union
}
%token
%token
%token
%type
%type
%type
%type
{
Symbol
Inst
int
sym;
*inst;
narg;
<sym>
<sym>
<narg>
<inst>
<inst>
<sym>
<narg>
/* nothing
list '\n'
list d e f n
list asgn
list stmt
list expr
list error
list:
VAR
ARG
asgn:
/* symbol table p o i n t e r */
/* machine i n s t r u c t i o n */
/* n u m b e r of a r g u m e n t s */
*/
'\n'
'\n'
'\n'
'\n'
'\n'
{
{
{
{
{ c o d e 3 ( v a r p u s h , ( I n s t ) $ 1,assign);
{ defnonly("$");
stmt;
expr:
c o d e 2 ( a r g a s s i g n , ( I n s t ) $ 1); $$ = $3;}
expr
{ code(pop); }
RETURN { defnonly("return"); code(procret); }
R E T U R N expr
{ d e f n o n l y ( " r e t u r n " ) ; $$=$2; c o d e ( f u n c r e t ) ;
P R O C E D U R E b e g i n '(' arglist ')'
{ $$ = $2; c o d e 3 ( c a l l , (Inst)$1, (Inst)$4);
PRINT prlist
{ $$ = $2; }
}
}
N U M B E R { $$ = c o d e 2 ( c o n s t p u s h , (Inst)$1); }
VAR
{ $$ = c o d e 3 ( v a r p u s h , (Inst)$1, eval); }
ARG
{ d e f n o n l y ( " $ " ) ; $$ = code2(arg, (Inst)$1); }
asgn
F U N C T I O N b e g i n '(' arglist ')'
{ $$ = $2; c o d e 3 ( c a l i , ( I n s t ) $ 1 , ( I n s t ) $ 4 ) ; }
! R E A D '(' V A R ')' { $$ = c o d e 2 ( v a r r e a d , (Inst)$3); }
!
!
!
!
begin:
$$ = $3; }
/* nothing
*/
{ $$ = progp;
276
prlist:
defn:
expr
STRING
prlist
prlist
',' expr
',' STRING
CHAPTER 8
{
{
{
{
code(prexpr); }
$$ = c o d e 2 ( p r s t r , (Inst)$ 1) ; }
code(prexpr); }
c o d e 2 ( p r s t r , (Inst)$3); }
}
}
procname: VAR
i FUNCTION
! PROCEDURE
arglist:
/* n o t h i n g */
! expr
! arglist ',' expr
{ $$ = 0; }
{
{
$$
$$
= 1; }
= $1 + 1;
%%
*/
{
if
(!indef)
execerror(s,
CHAPTER 8
PROGRAM DEVELOPMENT
yylex()
277
/* hoc6 */
if
(c ==
}
if
(c ==
'$') { /* argument? */
int n = 0;
while ( i s d i g i t ( c = g e t c ( f i n ) ) )
n = 1 0 * n + c - ' 0 ' ;
u n g e t c ( c , fin);
if (n == 0)
execerror("strange
y y l v a l . n a r g = n;
r e t u r n ARG;
(char *)0);
*p = 0;
y y l v a l . s y m = (Symbol * ) e m a l l o c ( s t r l e n ( s b u f ) + 1 ) ;
s t r c p y ( y y l v a l . s y m , sbuf);
return STRING;
}
backslash(c)
/* get next char with \'s i n t e r p r e t e d */
int c;
{
char *index( ) ; /* *strchr()' in some s y s t e m s */
static char t r a n s t a b f ] = " b \ b f \ f n \ n r \ r t \ t " ;
if (c ! = ' W )
return c;
c = getc(fin);
if (islower(c) &.&. i n d e x ( t r a n s t a b , c) )
return index(transtab, c ) [ 1 ];
r e t u r n c;
}
278
CHAPTER 8
augmented with a second stack to keep track of nested function and procedure
calis. (A second stack is easier than piling more things into the existing one.)
Here is the beginning of c o d e . c :
$ cat code.c
#define NPROG
2000
Inst
prog[NPROG];
/* the m a c h i n e */
Inst
progp;
/* next free spot for code g e n e r a t i o n /
Inst
*pc;
/* program counter d u r i n g e x e c u t i o n */
Inst
*progbase = prog; /* start of current s u b p r o g r a m */
int
returning;
/ 1 if return stmt s e e n */
typedef
struct Frame {
Symbol
*sp;
Inst
retpc;
Datum
*argn;
int
nargs;
} Frame;
#define NFRAME
100
Frame
frame[NFRAME];
Frame
*fp;
/*
/*
/*
/*
/*
/* frame p o i n t e r
*/
initcode() {
progp = progbase;
stackp = stack;
fp = frame;
r e t u r n i n g = 0;
Since the symbol table now holds pointers to procedures and functions, and
to strings for printing, an addition is made to the unin type in h o c . h :
$ c a t hoc.h
typedef
struct S y m b o l {
char
ame;
type;
short
unin {
double
double
int
char
} u;
struct Symbol
} Symbol;
/* symbol table e n t r y */
val;
(*ptr)(
(*defn)
*str;
*next;
/ *
);
/ *
();
/ *
/
/ *
V A R */
B L T I N */
F U N C T I O N , P R O C E D U R E */
STRING */
to link to a n o t h e r
*/
CHAPTER 8
PROGRAM DEVELOPMENT
279
/* cali a function */
{
S y m b o l *sp = (Symbol *)pc[0];
if
/* symbol table e n t r y */
/* for f u n c t i o n */
(fp++
>= & f r a m e [ N F R A M E - 1 ] )
e x e c e r r o r ( s p - > n a m e , "cali nested t o o d e e p l y " ) ;
fp->sp = sp;
f p - > n a r g s = (int)pc[1];
fp->retpc = pe + 2;
f p - > a r g n = stackp - 1; /* last argument */
execute(sp->u.defn);
r e t u r n i n g = 0;
}
280
Machine
CHAPTER 8
Frame
Stack
/* return from a p r o c e d u r e
*/
if
(fp->sp->type == F U N C T I O N )
execerror(fp->sp->name,
"(func) r e t u r n s no v a l u " ) ;
ret();
}
The function r e t pops the arguments off the stack, restores the f r a m e pointer
f p , and sets the program counter.
ret()
*/
*/
Several of the interpreter routines need minor fiddling to handle the situation when a r e t u r n occurs in a nested statement. This is done inelegantly but
adequately by a flag called r e t u r n i n g , which is true when a r e t u r n statement has been seen. i f e o d e , w h i l e c o d e and e x e c u t e termnate early if
r e t u r n i n g is set; c a l i resets it to zero.
CHAPTER 8
PROGRAM DEVELOPMENT
281
ifcode)
{
Datum d;
Inst *savepc
= pe;
/* t h e n part
*/
execute(savepc+3);
/* c o n d i t i o n */
d = pop);
if (d.val)
execute(*((Inst **)(savepc)));
else if (*((Inst * * ) ( s a v e p c + 1 ) ) ) /* else part? */
execute(*((Inst **)(savepct1)));
if (Ireturning)
pe = *((Inst **)(savepc+2)); /* next stmt */
}
whilecode()
{
Datum d;
Inst savepc
= pe;
execute(savepc+2);
/* c o n d i t i o n */
d = pop();
while (d.val) {
execute(*((Inst **)(savepc)));
/* body */
if (returning)
break;
execute(savepc+2);
/* c o n d i t i o n */
d = pop);
}
if (Ireturning)
pe = *((Inst * * ) ( s a v e p c t 1 ) ) ; /* next stmt */
}
execute(p)
Inst *p;
{
for
Ireturning;
*getarg()
*/
{
int nargs = (int) *pc++;
if (nargs > f p - > n a r g s )
e x e c e r r o r ( f p - > s p - > n a m e , "not enough a r g u m e n t s " ) ;
r e t u r n &.fp->argn[ nargs - fp->nargs ] . v a l ;
}
282
arg( )
/* push argument
CHAPTER 8
onto stack */
{
Datum d;
d.val = *getarg();
push(d);
}
argassign()
/* store top of stack in a r g u m e n t */
{
Datum d;
d = pop();
push(d);
/* leave valu on stack */
* g e t a r g ( ) = d.val;
/* print
printf("%s",
string valu */
(char *) *pc++);
}
prexpr()
{
/* print n u m e r i c valu */
Datum d;
d = pop();
printf("%.8g
d.val);
PROGRAM DEVELOPMENT
CHAPTER 8
283
varreadf)
/* read into v a r i a b l e */
{
Datum d;
e x t e r n FILE *fin;
S y m b o l *var = (Symbol *) *pc++;
Again:
switch (fscanf(fin, "%lf", & v a r - > u . v a l ) ) {
case EOF:
if (moreinput())
goto Again;
d.val = v a r - > u . v a l = 0.0;
break;
case 0:
e x e c e r r o r ( " n o n - n u m b e r read into", v a r - > n a m e
break;
default:
d.val = 1.0;
break;
}
var->type
push(d);
= VAR;
59
94
248
396
574
809
'/~$/d'
*pick
#.[chyl]x
I wc -1
The language is by no means finished, at least in the sense that it's still easy to
think of useful extensions, but we will go no further here. The following exercises suggest some of the enhancements that are likely to be of valu.
Exercise 8-18. Modify hoc6 to permit named formal parameters in subroutines as an
alternative to $1, etc.
Exercise 8-19. As it stands, all variables are global except for parameters. Most of the
mechanism for adding local variables maintained on the stack is already present. One
approach is to have an a u t o declaration that makes space on the stack for variables
284
CHAPTER 8
listed; variables not so named are assumed to be global. The symbol table will also
have to be extended, so that a search is made first for locis, then for globals. How
does this interact with named arguments?
Exercise 8-20. How would you add arrays to hoc? How should they be passed to functions and procedures? How are they returned?
Exercise 8-21. Generalize string handling, so that variables can hold strings instead of
numbers. What operators are needed? The hard part of this is storage management:
making sure that strings are stored in such a way that they are freed when they are not
needed, so that storage does not leak away. As an interim step, add better facilities for
output formatting, for example, access to some form of the C p r i n t f statement.
8.7 Performance evaluation
We compared h o c to some of the other UNIX calculator programs, to get a
rough idea of how well it works. The table below should be taken with a grain
of salt, but it does indcate that our implementation is reasonable. All times
are in seconds of user time on a PDP-11/70. There were two tasks. The first is
computing Ackermann's function a c k ( 3 , 3 ) . This is a good test of the
function-call mechanism; it requires 2432 calis, some nested quite deeply.
func a c k ( ) {
if ($1 == 0) return $2+1
if ($2 == 0) return ack($1-1, 1)
return ack($1-1, ack($1, $ 2 - 1 ) )
}
ack(3,3)
T h e second test is computing the Fibonacci numbers with vales less than 1000
a total of one hundred times; this involves mostly arithmetic with an occasional
function cali.
proc f i b ( ) {
a = 0
b = 1
w h i l e (b < $ 1 ) {
c = b
b = a+b
a = c
}
}
i = 1
while (i < 100) {
fib(1000)
i = i + 1
}
CHAPTER 8
PROGRAM DEVELOPMENT
285
ack(3,3)
hoc
bas
be
100Xfib(1000)
5.5
1.3
39.7
<0.1
5.0
0.7
14.9
<0.1
$(OBJS)
cc $(CFLAGS) $ ( O B J S ) -lm -o hoc6
so that the cc command uses the variable CFLAGS, and then say
$ make
clean;
make
CFLAGS=-p
<fibtest
hoc6 I sed
a m e %time
_pop
15. 6
_push
14. 3
mcount
11. 3
CSV
10. 1
cret
8. 8
_assign
8. 2
_eval
8. 2
.execute
6. 0
_varpush
5. 9
_lt
2. 7
_constpu
2. 0
_add
1 .7
_getarg
1. 5
_yyparse
0. 6
$
15q
cumsecs
#call
0 . 85 32182
1 .63 32182
2. 25
2. 80
3. 28
3. 73
5050
4. 18
8218
4. 51
3567
4. 83 13268
4. 98
1783
5. 09
497
5. 18
1683
5. 26
1683
5. 30
3
ms/call
0 , 03
0.
,02
0 . .09
0. ,
05
0,. 09
0.
,02
0., 08
0.,22
0 , ,05
0 . ,05
11., 11
286
CHAPTER 8
pushing and popping the stack. The overhead is larger if we include the times
for the C subroutine linkage functions c s v and c r e t . ( m c o u n t is a piece of
the profiling code compiled in by cc - p . ) Replacing the function calis by macros should make a noticeable difference.
To test this expectation, we modified c o d e . c , replacing calis to p u s h and
p o p with macros for stack manipulation:
#define
#define
push(d) *stackp++ =
popm()
*--stackp
(d)
/* function
still needed
#/
CHAPTER 8
PROGRAM DEVELOPMENT
287
CHAPTER 9:
DOCUMENT PREPARATION
One of the first applications of the UNIX system was editing and formatting
documents; indeed, Bell Labs management was persuaded to buy the first
PDP-11 hardware by promises of a document preparation system, not an
operating system. (Fortunately, they got more than they bargained for.)
T h e first formatting program was called roff. It was small, fast, and easy
to work with, so long as one was producing simple documents on a line
printer. The next formatter, nroff, by Joe Ossanna, was much more ambitious. Rather than trying to provide every style of document that users might
ever want, Ossanna made nroff programmable, so that many formatting tasks
were handled by programming in the nroff language.
When a small typesetter was acquired in 1973, n r o f f was extended to handle the mltiple sizes and fonts and the richer character set that the typesetter
provided. The new program was called t r o f f (which by analogy to " e n - r o f f "
i s pronounced "tee-roff.") n r o f f and t r o f f are basically the same program,
and accept the same input language; n r o f f ignores commands like size
changes that it can't honor. We will talk mainly about t r o f f but most of our
comments apply to n r o f f as well, subject to the limitations of output devices.
The great strength of t r o f f is the flexibility of the basic language and its
programmability it can be made to do almost any formatting task. But the
flexibility comes at a high price t r o f f is often astonishingly hard to use. It
is fair to say that almost all of the UNIX document preparation software is
designed to cover up some part of naked t r o f f .
One example is page layout the general style of a document, what the
titles, headings and paragraphs look like, where the page numbers appear, how
big the pages are, and so on. These are not built in; they have to be programmed. Rather than forcing each user to specify all of these details in every
document, however, a package of standard formatting commands is provided.
A user of the package does not say "the next line is to be centered, in bigger
letters, and in a bold f o n t . " Instead, the user says "the next line is a title,"
and the packaged definition of the style of a title is used. Users talk about the
logical components of a document titles, headings, paragraphs, footnotes,
etc. instead of sizes, fonts, and positions.
289
290
CHAPTER 9
CHAPTER 9
DOCUMENT PREPARATION
291
t r o f f built-in commands all have lower-case ames, so by convention commands in macro packages are given upper-case ames. In this example, . P P is
the ms command for a paragraph, and . f t B is a t r o f f command that causes
a change to the bold font. (Fonts have upper case ames; the fonts available
may be different on different typesetters.)
The second form of t r o f f command is a sequence of characters that
begins with a backslash \, and may appear anywhere in the input; for example,
\ f B also causes a switch to the bold font. This form of command is pur
t r o f f ; we'll come back to it shortly.
You can format with nothing more than a . P P command before each paragraph, and for most documents, you can get by with about a dozen different
ms commands. For example, Appendix 2, which describes h o c , has a title, the
authors' ames, an abstract, automatically-numbered section headings, and
paragraphs. It uses only 14 distinct commands, several of which come in pairs.
The paper takes this general form in ms:
.TL
Abstract, terminated by . AE
. AE
.NH
Paragraph ...
.PP
292
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 9
.TL
Hoc - An Interactive Language For F l o a t i n g Point A r i t h m e t i c
.AU
Brian Kernighan
R o b Pike
. AB
.1 Hoc
is a simple p r o g r a m m a b l e interpreter
for floating point expressions.
It has C - s t y l e control flow,
f u n c t i o n d e f i n i t i o n and the usual
numerical built-in functions
such as cosine and logarithm.
.AE
NH
Expressions
.PP
.1 Hoc
is an e x p r e s s i o n language,
m u c h like C:
a l t h o u g h there are several c o n t r o l - f l o w s t a t e m e n t s ,
most s t a t e m e n t s such as a s s i g n m e n t s
are e x p r e s s i o n s whose valu is d i s r e g a r d e d .
CHAPTER 9
DOCUMENT PREPARATION
293
294
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 9
.DS
.1
expr:
number
variable
( expr )
expr binop expr
unop expr
function ( arguments
.R
.DE
Numbers are floating point.
which prints as
Hoc is an expression language, much like C: although there are several controlflow statements, most statements such as assignments are expressions whose valu is
disregarded. For example, the assignment operator = assigns the valu of its right
operand to its left operand, and yields the valu, so mltiple assignments work. The
expression grammar is:
expr:
number
variable
( expr )
expr binop expr
unop expr
function ( arguments )
CHAPTER 9
T h i s text
DOCUMENT PREPARATION
295
is romn, but
.1
t h i s text is italic,
.R
this is romn again, and
.B
this is b o l d f a c e .
is printed as
This is romn, but this is italic, and hese words are bold.
Finally, a second argument to . I or . B is printed in romn, appended
without spaces to the first argument. This feature is most commonly used to
produce punctuation in the right font. Compare the last parenthesis of
(parenthetical
.1 "italic w o r d s ) "
296
CHAPTER 9
Miscellaneous commands
Footnotes are introduced with . F S and terminated with .FE. You are
responsible for any identifying mark like an sterisk or a dagger.f This footnote was created with
i d e n t i f y i n g m a r k like
.FS
\(dg Like this one.
an asterisk
or a d a g g e r . \ ( d g
.FE
This
footnote
...
(1)
A . P P or .LP (left-justified paragraph) terminates an . I P . The . I P argument can be any string; use quotes to protect blanks if necessary. A second
argument can be used to specify the amount of indent.
The command pair .KS and .KE causes text to be kept together; text
enclosed between these commands will be forced onto a new page if it won't all
fit on the current page. If .KF is used instead of .KS, the text will float past
subsequent text to the top of the next page if necessary to keep it on one page.
We used .KF for all the tables in this book.
You can change most of ms's default vales by setting number registers,
which are troff variables used by ms. Perhaps the most common are the
registers that control the size of text and the spacing between lines. Normal
text size (what you are reading now) is "10 p o i n t , " where a point is about 1/72
of an inch, a unit inherited from the printing industry. Lines are normally
printed at 12-point separation. To change these, for example to 9 and 11 (as in
our displays), set the number registers PS and VS with
.nr PS 9
.nr V S 11
Other number registers include LL for line length, Pl for paragraph indent,
and PD for the separation between paragraphs. These take effect at the next
. P P or . L P .
t Like this one.
CHAPTER 9
DOCUMENT PREPARATION
297
of ms, mm or
so is like procautiously and
size and font
Character ames
Access to strange characters Greek letters like TI, graphics like and t,
and a variety of lines and spaces is easy, though not very systematic. Each
298
CHAPTER 9
DF
.DS
.EQ
.FS
.I
.H
.HU "..."
.P
.R
.TL
.TS
CHAPTER 9
DOCUMENT PREPARATION
Table 9.3:
-
\(hy
\ -
\ (mi
\ (em
\&
\blank
\!
\e
\ (bu
\(dg
\ (*a
\fX
\f
{XX
\s n
\s
299
\e&.TL
\&.I "Title of document"
\e&.AU
300
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
a \fBfriv\fIolousXfR
\fIvar\fBiety\fR
CHAPTER 9
of \ f I f o n t s \ f P
is output as
a fri\olous variey of fonts
The font change \ f P reverts to the previous font whatever the font was
before the last switch. (There's only one previous font, not a stack.)
Some fonts have two-character ames. These are specified by the formal
\f (XX where XX is the font ame. For example, the font on our typesetter in
which programs in this book are printed is called CW (Courier Constant
Width), so k e y w o r d is written as
\f(CWkeywordXfP
...
\ s 0 causes the size to revert to its previous valu. It's the analog of \ f P , but
in the t r o f f tradition, it isn't spelled \ s P . Our extensions to ms include a
macro .UC (upper case) for this job.
Basic t r o f f commands
Realistically, even with a good macro package, you have to know a handful
of t r o f f commands for controlling spacing and filling, setting tab stops, and
the like. The command . b r causes a break, that is, the next input that follows
the . b r will appear on a new output line. This could be used, for example, to
split a long title at the proper place:
TL
Hoc - An Interactive Language
. br
For Floating Point A r i t h m e t i c
The command . n f turns off the normal filling of output lines; each line of
input goes directly into one line of output. The command . f i turns filling
DOCUMENT PREPARATION
CHAPTER 9
3
.5
1. 5i
3p
3.1c
301
3 blank lines
blank half-line
7.5 inches
3 points
3.1 centimeters
Start a definition
Font change around first argument
End of definition
\$n produces the valu of the n-th argument when the macro is invoked; it is
empty if no n-th argument was provided. The double \ delays evaluation of
\$n during macro definition. The \& prevens the argument from being interpreted as a t r o f f command, in case it begins with a period, as in
.cw . s p
9.3 The t b l and e q n preprocessors
t r o f f is a big and complicated program, both inside and out, so modifying
it to take on a new task is not something to be undertaken lightly. Accordingly the development of programs for typesetting mathematics and tables took
a different approach the design of separate languages implemented by
separate programs e q n and t b l that act a s "preprocessors" for t r o f f . I n
effect, t r o f f is an assembly language for a typesetting machine, and e q n and
t b l compile into it.
302
CHAPTER 9
t It is improbable that e q n would exist if y a c c had not been available at the right time.
CHAPTER 9
DOCUMENT PREPARATION
303
.TS
center, box;
c s
lfCW 1.
XfBTable 1:\fP
Operators, in decreasing order of precedence
. sp .5
exponentiation (\s-1FORTRAN\sO **), right associative
! \(unary) logical and arithmetic negation
* /
multiplication, divisin
+ \addition, subtraction
> >=
relational operators: greater, greater or equal,
< <=
less, less or equal,
\&== !=
equal, not equal (all same precedence)
&.&.
logical A N D (both operands always evaluated)
!!
logical OR (both operands always evaluated)
\&=
assignment, right associative
.TE
304
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 9
well as the first. A font can be defined for a column; the t b l specification
l f C W prints a left-justified column in the CW font.
T h e text of the table follows the formatting information. T a b characters
separate columns, and some t r o f f c o m m a n d s such a s . s p are understood
inside tables. (Note a couple of appearances of \&: unprotected leading - and
= signs in columns tell t b l to d r a w lines across the table at that point.)
t b l produces a wider variety of tables than this simple example would suggest: it will fill text in boxes, vertically justify column headings, and so on.
T h e easiest way to use it for complicated tables is to look for a similar example
in the manual in V o l u m e 2A of the UNIX Programmer's
Manual and adapt the
commands.
Mathematical expressions
T h e second t r o f f preprocessor is e q n , which converts a language describing mathematical expressions into the t r o f f c o m m a n d s t o print t h e m . I t
automatically handles font and size changes, and also provides a m e s for standard mathematical characters. e q n input usually appears between .EQ and
.EN lines, analogous to t b l ' s . T S and .TE. For example,
.EQ
x sub i
.EN
(9.1)
2TT q
z l,
is written as
.EQ (9.1)
f( zeta ) -=~ 1 over {2 pi i} int from C
f ( z ) over {z - zeta} dz
.EN
CHAPTER 9
DOCUMENT PREPARATION
305
i=0
i
-
7 r
1 over
{2 pi}
.EN
00
In-line expressions are used for mathematics within a table, as this example
from the h o c document shows:
.TS
center, box;
c s s
lfCW n 1.
\fBTable 3:\fP Built-in Constants
.sp .5
DEG
57.29577951308232087680
E
2.71828182845904523536
GAMMA
0.57721566490153286060
PHI
1.61803398874989484820
PI
3.14159265358979323846
.TE
This table also shows how t b l lines up the decimal points in numeric (n)
columns. The output appears below.
306
CHAPTER 9
57.29577951308232087680
2.71828182845904523536
0.57721566490153286060
1.61803398874989484820
3.14159265358979323846
Finally, since eqn italicizes any string of letters that it doesn't recognize, it
is a common idiom to italicize ordinary words using eqn. @Word@, for example, prints as Word. But beware: eqn recognizes some common words (such
as from and to) and treats them specially, and it discards blanks, so this trick
has to be used carefully.
Getting output
Once you have your document ready, you have to line up all the preprocessors and t r o f f to get output. The order of commands is t b l , then e q n , then
t r o f f . I f you are just using t r o f f , type
$ t r o f f -ms filenames
(Or -mm)
Otherwise, you must specify the argument filenames to the first command in
the pipeline and let the others read their standard input, as in
$ eqn filenames I t r o f f -ms
I t r o f f -ms
ch9.*
$ doctype
cat hoc.ms
$
! pie
! tbl
! eqn
troff
-ms
hoc.ms
! tbl
! eqn
troff
-ms
CHAPTER 9
$ cat
DOCUMENT PREPARATION
307
doctype
# doctype:
synthesize proper command line for troff
e c h o -n "cat $* ! "
egrep -h ' A \ . ( E Q T S ! \ [ ! P S ! I S ! P P ) ' $*
sort -u !
awk '
/ " \ . P P / { ms++ }
/ ~ \ . E Q / { eqn++ }
/ * \ . T S / { tbl++ }
/ " \ . P S / { pic + + }
/ " \ . I S / { ideal++ }
/ A \ . \ [ / { refer++ }
END {
if (refer > 0) printf "refer !
if (pie > 0)
printf "pie ! "
if (ideal > 0) printf "ideal !
if (tbl > 0)
printf "tbl ! "
if (eqn > 0)
printf "eqn ! "
printf "troff "
if (ms > 0) printf "-ms"
printf "\n"
} '
$
308
CHAPTER 9
$ time awk
doctype
without egrep
cat ch9.1 ch9.2 ch9.3 ch9.4 ! pie
real
user
sys
... ' c h 9 . *
! t b l ! eqn
! troff
-ms
! tbl
troff
-ms
31.0
8.9
2.8
ch9.1 ch9.2
real
user
sys
$
ch9.3 ch9.4
! pie
! eqn
7.0
1.0
2.3
Rewrite
Exercise 9-6. Is it better to use d o c t y p e or to write a shell file containing the commands to format a specific document?
Exercise 9-7. Experiment with various combinations of g r e p , e g r e p , f g r e p , s e d ,
awk and s o r t to create the fastest possible versin of d o c t y p e .
CHAPTER 9
$ man
DOCUMENT PREPARATION
309
7 man
prints only the description of the macros. The default action is to print all
pages with the specified ame, using n r o f f , but man -t generates typeset
pages using t r o f f .
The author of a manual page creates a file in the proper subdirectory of
/ u s r / m a n . The man command calis n r o f f o r t r o f f with a macro package
to print the page, as we can see by searching the man command for formatter
invocations. Our result would be
$ grep roff lwhich man'
n r o f f $ o p t -man $ a l l ; ;
n e q n $ a l l ! n r o f f $ o p t -man ;;
t r o f f $ o p t -man $ a l l ; ;
t r o f f - t $ o p t -man $ a l l ! t e ; ;
eqn $ a l l t r o f f $ o p t -man ; ;
eqn $ a l l t r o f f - t $ o p t -man ! t e
$
;;
If any section is empty, its header is omitted. The .TH line and the AME,
SYNOPSIS and DESCRIPTION sections are mandatory.
The line
310
. TH COMMAND
CHAPTER 9
section-number
ames the command and specifies the section number. The various .SH lines
identify sections of the manual page. The AME and SYNOPSIS sections are
special; the others contain ordinary prose. The AME section ames the command (this time in lower case) and provides a one-line description of it. The
SYNOPSIS section ames the options, but doesn't describe them. As in any section, the input is free form, so font changes can be specified with the .B, .1
and . R macros. In the SYNOPSIS section, the ame and options are bold, and
the rest of the information is romn. The e d ( l ) AME and SYNOPSIS sections, for example, are:
.SH AME
ed \- text editor
.SH SYNOPSIS
. B ed
[
.B \ ] [
.B \ - x
] [ narne ]
CHAPTER 9
DOCUMENT PREPARATION
311
.TH HOC 1
.SH AME
hoc \- interactive floating point language
.SH SYNOPSIS
.B hoc
[ file ... ]
.SH DESCRIPTION
.1 Hoc
interprets a simple language for floating point arithraetic,
at about the level of BASIC, with C-like syntax and
functions and procedures with arguments and recursion.
.PP
The named
.IR file s
are read and interpreted in order.
If no
.1 file
is given or if
.1 file
is
. I hoc
interprets the standard input.
.PP
.1 Hoc
input consists of
.1 expressions
and
.IR statements .
Expressions are evalated and their results printed.
Statements, typically assignments and function or procedure
definitions, produce no output unless they explicitly cali
.IR print .
.SH "SEE ALS0"
Hoc \- An Interactive Language for Floating Point Arithmetic
by Brian Kernighan and Rob Pike.
.br
.IR bas (1),
.IR be (1)
and
.IR de (1).
.SH BUGS
Error recovery is imperfect within function and procedure definitions.
. br
The treatment of newlines is not exactly user-friendly.
Figure 9.1: / u s r / m a n / m a n 1 / h o c . 1
variations of the command's normal behavior. The BUGS section is also somewhat misnamed. Defects reported here aren't so much bugs as shortcomings
simple bugs should be fixed before the command is installed. To get a feeling for what goes in the DIAGNOSTICS and BUGS sections, you might browse
hrough the standard manual.
312
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
CHAPTER 9
An example should clarify how to write the manual page. T h e source for
h o c ( l ) , / u s r / m a n / m a n 1 / h o c . 1, is shown in Figure 9.1, and Figure 9.2 is
the output of
$ man
-t hoc
Exercise 9-8. Write a manual page for d o c t y p e . Write a versin of the man command that looks in your own man directory for documentation on your personal programs.
HOC(l)
HOC(l)
AME
Hoc interprets a simple language for floating point arithmetic, at about the level
of BASIC, with C-like syntax and functions and procedures with arguments and
recursion.
The named files are read and interpreted in order. If no file is given or if file is
' hoc interprets the standard input.
Hoc input consists of expressions and statements.
Expressions are evaluated and
their results printed. Statements, typically assignments and function or procedure
definitions, produce no output unless they explicitly cali print.
SEE ALSO
by Brian Kernighan
BUGS
Error recovery is imperfect within function and procedure definitions.
The treatment of newlines is not exactly user-friendly.
8th Edition
Figure 9.2: h o c ( l )
DOCUMENT PREPARATION
CHAPTER 9
313
document-
pie
tbl
.ne at
eqn
2nd
troff
last
box.s
typesetter
macro
package
The pictures in this book were all done with p i e . p i e and i d e a l are not
part of the 7th Edition but are now available.
r e f e r , p i e and i d e a l are all t r o f f preprocessors. There are also programs to examine and comment on the prose in your documents. The best
known of these is s p e l l ( l ) , which reports on possible spelling errors in files;
we used it extensively. s t y l e ( l ) and d i c t i o n ( l ) analyze punctuation, grammar and language usage. These in turn developed into the Writer's Workbench, a set of programs to help improve writing style. The Writer's Workbench programs are good at identifying clichs, unnecessary words and sexist
phrases.
s p e l l is standard. The others may be on your system; you can easily find
out by using man:
314
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
$ man style
diction
CHAPTER 9
wwb
o r b y listing / b i n and / u s r / b i n .
History and bibliographic notes
t r o f f , written by he late Joe Ossanna for the Graphics Systems CAT-4
typesetter, has a long lineage, going back to RUNOFF, which was written by J.
E. Saltzer for CTSS at MIT in the early 1960's. These programs share the
basic command syntax and ideas, although t r o f f is certainly the most complicated and powerful, and the pre&ence of e q n and the other preprocessors adds
significantly to its utility. There are several newer typesetting programs with
more civilized input format; TEX, by Don Knuth (TEX and Metafont: New
Directions in Typesetting, Digital Press, 1979), and Scribe, by Brian Reid
("Scribe: a high-level approach to computer document formatting," 7th Symposium on the Principies of Programming Languages, 1980), are probably the
best known. The paper "Document Formatting Systems: Survey, Concepts and
Issues" by Richard Furuta, Jeffrey Scofield, and Alan Shaw (Computing Survey s, September, 1982) is a good survey of the field.
The original paper on e q n is "A system for typesetting mathematics,"
(CACM, March 1975), by Brian Kernighan and Lorinda Cherry. The ms
macro package, t b l and r e f e r are all by Mike Lesk; they are documented
only in the UNIX Programmer's Manual, Volume 2A.
p i e is described in "PIC a language for typesetting graphics," by Brian
Kernighan, SoftwarePractice
and Experience,
January, 1982. i d e a l is
described in "A high-level language for describing pictures," by Chris Van
Wyk, ACM Transactions on Graphics, April, 1982.
s p e l l is a command that turned from a shell file, written by Steve Johnson, into a C program, by Doug Mcllroy. The 7th Edition s p e l l uses a hashing mechanism for quick lookup, and rules for automatically stripping suffixes
and prefixes to keep the dictionary small. See "Development of a spelling
list," M. D. Mcllroy, IEEE Transactions on Communications, January, 1982.
The s t y l e and d i c t i o n programs are described in "Computer aids for
writers," by Lorinda Cherry, SIGPLAN Symposium on Text Manipulation,
Portland, Oregon (June 1981).
C H A P T E R 10:
I P S L O Q
The U N I X operating system is well over ten years od, but the number of
computers running it is growing faster than ever. For a system designed with
no marketing goals or even intentions, it has been singularly successful.
T h e main reason for its commercial success is probably its portability the
feature that everything but small parts of the compilers and kernel runs
unchanged on any computer. Manufacturers that run U N I X software on their
machines therefore have comparatively little work to do to get the system running on new hardware, and can benefit from the expanding commercial market
for U N I X programs.
But the U N I X system was popular long before it was of commercial significance, and even before it ran on anything but the PDP-11. The 1974 CACM
paper by Ritchie and Thompson generated interest in the academic community,
and by 1975, 6th Edition systems were becoming common in universities.
Through the mid-1970's U N I X knowledge spread by word of mouth: although
the system carne unsupported and without guarantee, the people who used it
were enthusiastic enough to convince others to try it too. Once people tried it,
they tended to stick with it; another reason for its current success is that the
generation of programmers who used academic U N I X systems now expect to
find the U N I X environment where they work.
Why did it become popular in the first place? The central factor is that it
was designed and built by a small number (two) of exceptionally talented people, whose sol purpose was to create an environment that would be convenient
for program development, and who had the freedom to pursue that ideal. Free
of market pressure, the early systems were small enough to be understood by a
single person. John Lions taught the 6th Edition kernel in an undergraduate
operating systems course at the University of New South Wales in Australia.
In notes prepared for the class, he wrote, " . . . the whole documentation is not
unreasonably transportable in a student's briefcase." (This has been fixed in
recent versions.)
In that early system were packed a number of inventive applications of
computer science, including stream processing (pipes), regular expressions,
language theory ( y a c c , l e x , etc.) and more specific instances like the
315
316
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
C H A P T E R 10
C H A P T E R 10
EPILOG
317
and arbitrary limitations, you will surely agree. In spie of such blemishes,
however, the positive benefits far outweigh the occasional irritating rough
edges. The UNX system is really good at what it was designed to do: providing
a comfortable programming environment.
So although U N I X has begun to show some signs of middle age, it's still
viable and still gaining in popularity. And that popularity can be traced to the
clear thinking of a few people in 1969, who sketched on the blackboard a
design for a programming environment they would find comfortable.
Although they didn't expect their system to spread to tens of thousands of
computers, a generation of programmers is glad that it did.
APPENDIX 1:
EDITOR SUMMARY
320
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
APPENDIX 1
can be preceded by one or two line numbers, which indicate what line or lines
are to be affected by the command; a default line number is used otherwise.
Line numbers can be specified by absolute position in the file ( 1 , 2, ...), by
shorthand like $ for the last line and
for the current line, by pattern
searches using regular expressions, and by additive combinations of these.
Let us review how to create files with e d , using De Morgan's poem from
Chapter 1.
$ ed poem
?poem
Warning: the file p o e m doesn't exist
a
Start adding lines
Great fleas have little fleas
upon their backs to bite 'em,
And little fleas have lesser fleas,
and so ad infinitum.
Type a ' t o stop adding
w poem
Write lines to file poem
121
ed reports 121 characters written
q
Quit
$
APPENDIX 1
EDITOR SUMMARY
321
2 6 3 poem
You have returned from the command
Quit without w is OK: no change was made
Printing
The lines of the file are numbered 1, 2, ...; you can print the -th line by
giving the command np or just the number n, and lines m through n with
m,np.
T h e "line n u m b e r " $ is the last line, so you don't have to count lines.
1
$
1, $p
You can print a file one line at a time just by pressing RETURN; you can back
up one line at a time with
Line numbers can be combined with + and
$ - 2 , $p
1, 2 + 3p
But you can't print past the end or in reverse order; commands like $ , $ + 1 p
and $, 1p are illegal.
The list command 1 prints in a format that makes all characters visible; it's
good for finding control characters in files, for distinguishing blanks from tabs,
and so on. (See v i s in Chapter 6.)
Patterns
Once a file becomes longer than a few lines, it's a bother to have to print it
all to find a particular line, so ed provides a way to search for lines that match
a particular pattern: /pattern/
finds the next occurrence of pattern.
$ ed poem
263
/flea/
Search for next line containing f l e a
Great f l e a s have l i t t l e f l e a s
/flea/
Search for next one
And l i t t l e f l e a s h a v e l e s s e r f l e a s ,
//
Search for next using same pattern
And t h e g r e a t f l e a s t h e m s e l v e s , i n t u r n ,
??
Search backwards for same pattern
And l i t t l e f l e a s h a v e l e s s e r f l e a s ,
ed remembers the pattern you used last, so you can repeat a search with just
322
//.
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
APPENDIX 1
T o s e a r c h b a c k w a r d s , u s e Ipattern?
and ? ? .
S e a r c h e s with / . . . / a n d ? . . . ? " w r a p a r o u n d " a t e i t h e r e n d o f t h e text:
$p
Same as:
Shorthand:
.-1
. -2
.-n
$-1
+ + or
Same as:
.+1
+2
+n
.3
.+2
+n
.+3
delete, inser
c o m m a n d a a d d s lines a f t e r t h e specified line; t h e delete comlines; t h e inser c o m m a n d i i n s e r t s lines b e f o r e t h e specified
c o m m a n d c c h a n g e s lines, a c o m b i n a t i o n of d e l e t e a n d insert.
Add text after line n
Insert text before line n
Delete lines m through n
Change lines m through n
T h e n e w text f o r a,
c and i
APPENDIX 1
EDITOR SUMMARY
323
commands is terminated by a
on a line by itself; dot is left at the last line
added. Dot is set to the next line after the last deleted line, except that it
doesn't go past line $.
0a
dp
. , $dp
1, $d
?pat? , . - 1d
$dp
$c
1, $c
Substitution; undo
It's a pain to have to re-type a whole line to change a few letters in it. The
substitute command s is the way to replace one string of letters by another:
s/old/new/
s/old/new/p
s/old/new/g
s/old/new/gp
Change
Change
Change
Change
first
first
each
each
od
od
od
od
into
into
into
into
Only the leftmost occurrence of the pattern in the line is replaced, unless a ' g '
follows. The s command doesn't print the changed line unless there is a ' p ' at
the end. In fact, most ed commands do their job silently, but almost any command can be foliowed by p to print the result.
If a substitution didn't do what you wanted, the undo command u will undo
the most recent substitution. Dot must be set to the substituted line.
u
up
and print
Just as the p and d commands can be preceded by one or two line numbers
to indcate which lines are affected, so can the s command:
/old/s/old/new/
/old/s//new/
1, $ s / o l d / n e w / p
1, $ s / o l d / n e w / g p
Note that 1, $s applies the s command to each line, but it still means only the
leftmost match on each line; the trailing ' g ' is needed to replace all occurrences
in each line. Furthermore, the p prints only the last affected line; to print all
changed lines requires a global command, which we'll get to shortly.
The character & is shorthand; if it appears anywhere on the right side of an
s command, it is replaced by whatever was matched on the left side:
324
s / b i g / v e r y &/
s / b i g / & . &./
s / .*/(&) /
s/and/\&./
Replace b i g
Replace b i g
Parenthesize
Replace a n d
APPENDIX 1
by v e r y b i g
by b i g b i g
entire line (see . * below)
by & (\ turns off special meaning)
Pattern:
/ " $ /
/./
/ V
/thing/
/"thing/
/thing$/
/"thingS/
/thing.$/
/thing\.$/
/\/thing\//
/[tT]hing/
/thing[0-9]/
Matches:
empty line, i.e., newline only
non-empty, i.e., at least one character
all lines
t h i n g anywhere on line
t h i n g at beginning of line
t h i n g at end of line
line that contains only t h i n g
t h i n g plus any character at end of line
t h i n g . at end of line
/ t h i n g / anywhere on line
t h i n g or T h i n g anywhere on line
t h i n g followed by one digit
APPENDIX 1
EDITOR SUMMARY
/ t h i n g [ * 0 -9 ] /
/thing [0-9][~0-9]/
/thingl .*thing2/
/ " t h i n g 1. * t h i n g 2 $ /
325
t h i n g followed by a non-digit
t h i n g followed b y digit, non-digit
t h i n g l then any string then t h i n g 2
t h i n g l a t beginning and t h i n g 2 a t end
Note that x*
can m a t c h z e r o c h a r a c t e r s ; x x *
matches one or
more.
Global commands
T h e g l o b a l c o m m a n d s g a n d v a p p l y o n e o r m o r e o t h e r c o m m a n d s t o a set
of l i n e s s e l e c t e d by a r e g u l a r e x p r e s s i o n . T h e g c o m m a n d is m o s t o f t e n u s e d
f o r p r i n t i n g , s u b s t i t u t i n g or d e l e t i n g a set of lines:
m,nq/re/cmd
m,nv/re/cmd
T h e g o r v c o m m a n d s c a n b e p r e c e d e d b y line n u m b e r s t o limit t h e r a n g e ; t h e
default range is 1, $.
g/- . / p
g / . ./d
g/- ./s//repl/p
g / . ./s//repl/qp
g/- ,/s/pat/repl/
g/- ./s/pat/repl/p
g/- . / s /pat / repl / gp
gp
V/. ,/s/pat/repl/
V/~
g/- ./cmd\
cmd2\
cmd3
T h e c o m m a n d s c o n t r o l l e d by a g or v c o m m a n d c a n a l s o u s e l i n e n u m b e r s .
D o t is set in t u r n to e a c h l i n e s e l e c t e d .
g / t h i n g / . , . + 1p
Print each line with t h i n g and next
g/^X.EQ/. 1 , / " \ . E N / - s / a l p h a / b e t a / g p
Change a l p h a t o b e t a only
between . EQ and . EN, and print changed lines
Moving and copying lines
T h e c o m m a n d m m o v e s a c o n t i g u o u s g r o u p o f lines; t h e t c o m m a n d m a k e s
a c o p y of a g r o u p of lines s o m e w h e r e e l s e .
m.nm d
m,nt d
I f n o s o u r c e l i n e s a r e s p e c i f i e d , dot i s u s e d .
T h e d e s t i n a t i o n line d c a n n o t b e
in t h e r a n g e m, n 1. H e r e a r e s o m e c o m m o n i d i o m s u s i n g m a n d t:
326
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
m+
m-2
m- mm$
t.
.t.
1,$t$
g/VmO
APPENDIX 1
APPENDIX 1
EDITOR SUMMARY
s / \ ( . . . \) \ ( * \ ) / \ 2 \ 1 /
/\ ( . . * \ ) \ 1 /
327
Read file; add it after line n; set dot to last line read
Write lines m-n to file; dot is unchanged
Append lines m-n to file; dot is unchanged
The default range for w and W is the whole file. The default n for r is $, an
unfortunate choice. Beware.
ed remembers the first file ame used, either from the command line or
from an r or w command. The file command f prints or changes the ame of
the remembered file:
f
f
file
The edit command e reinitializes ed with the remembered file or with a new
one:
e
e
file
The e command is protected the same way as q is: if you haven't written your
changes, the first e will draw an error message. E reinitializes regardless of
changes. On some systems, ed is linked to e so that the same command
(e filename) can be used inside and outside the editor.
Encryption
Files may be encrypted upon writing and decrypted upon reading by giving
the x command; a password will be asked for. The encryption is the same as
in c r y p t ( l ) . The x command has been changed to X (upper case) on some
systems, to make it harder to encrypt unintentionally.
Summary of commands
Table 2 is a summary of ed commands, and Table 3 lists the valid line
numbers. Each command is preceded by zero, one or two line numbers that
indcate how many line numbers can be provided, and the default vales if
they are not. Most commands can be followed by a p to print the last line
affected, or 1 for list format. Dot is normally set to the last line affected; it is
unchanged by f, k, w, x, =, and !.
Exercise. When you think you know ed, try the editor quiz; see q u i z ( 6 ) .
328
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
APPENDIX 1
Table 2: Summary of ed C o m m a n d s
.a
. , .c
. , .d
e file
f file
1, $g/re/cmds
.i
. , . +1j
.kc
, .1
. , . m line
. , .p
q
$r file
. , . s/re/new/
. , . t line
.u
1 , $v/re/cmds
1, $w file
X
$=
! cmdline
( . +1) newline
A P P E N D I X 2:
HOC MANUAL
number
variable
( expr )
expr binop expr
unop expr
function ( arguments )
Numbers are floating point. The input format is that recognized by scanf (3): digits,
decimal point, digits, e or E, signed exponent. At least one digit or a decimal point
must be present; the other components are optional.
Variable ames are formed f r o m a letter followed by a string of letters and
numbers. binop refers to binary operators such as addition or logical comparison; unop
refers to the two negation operators, '!' (logical negation, 'not') and
' (arithmetic
negation, sign change). Table 1 lists the operators.
329
330
APPENDIX 2
Functions, as described later, may be defined by the user. Function arguments are
expressions separated by commas. There are also a number of built-in functions, all of
which take a single argument, described in Table 2.
Table 2: Built-in Functions
abs(x)
atan(x)
cos(x)
exp(x)
int(x)
log(x)
log10(x)
sin(x)
sqrt(x)
|* |, absolute valu of x
are tangent of x
cos(*), cosine of x
ex, exponential of x
integer par of x , truncated towards zero
log(x), logarithm base e of x
logio(-r), logarithm base 10 of x
sin(;t), sine of x
Vx ,x*
Logical expressions have valu 1.0 (true) and 0.0 (false). As in C, any non-zero
valu is taken to be true. As is always the case with floating point numbers, equality
comparisons are inherently suspect.
Hoc also has a few built-in constants, shown in Table 3.
Table 3: Built in Constants
DEG
E
GAMMA
PHI
PI
57.29577951308232087680
2.71828182845904523536
0.57721566490153286060
1.61803398874989484820
3.14159265358979323846
APPENDIX 2
HOC MANUAL
331
expr
variable = expr
procedure ( arglist )
while ( expr ) stmt
if ( expr ) stmt
if ( expr ) stmt else stmt
{ stmtlist }
print expr-list
return optional-expr
stmt:
stmtlist:
(nothing)
stmlist stmt
An assignment is parsed by default as a statement rather than an expression, so assignments typed interactively do not print their valu.
Note that semicolons are not special to hoc: statements are terminated by newlines.
This causes some peculiar behavior. The following are legal if statements:
if
(x < 0) p r i n t ( y )
else
print(z)
if
(x < 0) {
print(y)
} else {
print(z)
}
In the second example, the braces are mandatory: the newline after the if would termnate the statement and produce a syntax error were the brace omitted.
The syntax and semantics of hoc control flow facilities are basically the same as in
C. The while and if statements are just as in C, except there are no break or continu
statements.
3. Input and Output: read and print
The input function read, like the other built-ins, takes a single argument. Unlike
the built-ins, though, the argument is not an expression: it is the ame of a variable.
The next number (as defined above) is read from the standard input and assigned to the
named variable. The return valu of read is 1 (true) if a valu was read, and 0 (false)
if read encountered end of file or an error.
Output is generated with the print statement. The arguments to print are a commaseparated list of expressions and strings in double quotes, as in C. Newlines must be
supplied; they are never provided automatically by print.
Note that read is a special built-in function, and therefore takes a single
parenthesized argument, while print is a statement that takes a comma-separated,
unparenthesized list:
while
(read(x)) {
p r i n t "valu
is
x,
"\n"
332
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
APPENDIX 2
procedure:
ame may be the ame of any variable built-in functions are excluded. The definition, up to the opening brace or statement, must be on one line, as with the if statements above.
Unlike C, the body of a function or procedure may be any statement, not necessarily
a compound (brace-enclosed) statement. Since semicolons have no meaning in hoc, a
nuil procedure body is formed by an empty pair of braces.
Functions and procedures may take arguments, separated by commas, when
invoked. Arguments are referred to as in the shell: $3 refers to the third (1-indexed)
argument. They are passed by valu and within functions are semantically equivalent to
variables. It is an error to refer to an argument numbered greater than the number of
arguments passed to the routine. The error checking is done dynamically, however, so a
routine may have variable numbers of arguments if initial arguments affect the number
of arguments to be referenced (as in C's printf).
Functions and procedures may recurse, but the stack has limited depth (about a hundred calis). The following shows a hoc definition of Ackermann's function:
$ hoc
func
ack()
{
if
($1
if
($2
return
= = 0 ) r e t u r n $2+1
== 0) return
ack($1-1,
1)
ack($1-1,
ack($1,
$2-1))
ack(3,
ack(3,
2)
29
3)
61
ack(3,
4)
hoc: stack
line
HOC MANUAL
APPENDIX 2
5. Examples
Stirling's formula:
$ hoc
func stirl()
return
sqrt(2*$1*PI)
* ($1/E)~$1*(1
+ 1/(12*$1))
stirl(10)
3628684.7
stirl(20)
2 . 4 3 2 8 8 1 8 e + 18
Factorial function, n\\
func fac)
1 else return
10
11
12
13
14
15
16
17
18
19
20
1 ,. 0 0 0 0 3 1 8
1 . 0000265
1 .0000224
1 .0000192
1 .0000166
1 .0000146
1 . 0000128
1 .0000114
1 .0000102
1 .0 0 0 0 0 9 2
1 .0000083
"\n"
$1 * fac($1-
APPENDIX 3:
HOC LISTING
# m c l u d e "hoc.h"
#define c o d e 2 ( c 1 , c 2 )
code(c1); c o d e ( c 2 )
#define code3(c1,c2,c3) code(c1); code(c2); code(c3)
)
%token
Stoken
Jtoken
%type
56type
Xtype
%type
%right
%left
%left
%left
%left
%left
5left
%nght
%%
list:
symbol table p o m t e r /
machine m s t r u c t i o n */
number of arguments /
Symbol
Xnst
mt
sym;
mst;
narg;
<sym>
<sym>
<narg>
<inst>
<inst>
<sym>
<narg>
OR
AND
G T G E LT LE EQ N E
'+ ' ' - '
UNARYMINUS NOT
nothing
st '\n'
st defn
st asgn
st stmt
st expr
st error
/
'\n'
'\n'
'\n'
'\n'
'\n'
{
{
{
(
335
336
APPENDIX 3
expr
{ code(pop); }
RETURN ( defnonly("return"); code(procret); }
RETURN expr
( defnonlyC'return" ) ; $$=$2; code(funcret); }
PROCEDURE begin '(' arglist ')'
{ $$ = $2; code3(cali, (Inst)$1, (Inst)$4); }
PRINT prlist
{ $$ = $2; }
while cond stmt end {
($1)1 1] = (Inst)$3;
/ body of loop /
($1)12] = (Inst)$4; >
/ end, if cond fails /
if cond stmt end (
/ elae-less if /
($1)11] = (Inst)$3;
/. thenpart /
($1)13] = (Inst)$4; )
/ end, if cond fails */
if cond stmt end ELSE stmt end {
/ if with else /
($1)1 1] (Inst)$3;
/* thenpart /
($1)12] = ( I n s t ) $ 6 ;
/ elsepart /
($ 1)[3] = (Inst)$7; )
/ end, if cond fails /
'{' stmtlist '}'
{ $$ = $2; )
cond:
while:
WHILE ( $$ = code3(whilecode,STOP,STOP);
{ code(STOP); $$ = $2; }
if:
IF
begin:
/* n o t h m g */
{ $$ = progp; }
end:
/ nothing /
{ code(STOP); $$ = progp; }
( $$ = code(ifcode); code3(STOP,STOP,STOP);
stmtlist: /* nothing */
! stmtlist '\n'
! stmtlist stmt
{ $$ = progp; }
expr:
prlist:
expr
STRING
prlist ',' expr
prlist ',' STRING
{
{
{
{
code(prexpr); )
$$ = code2(prstr, ( I n s t ) $ 1 ) ;
code(prexpr); }
code2(prstr, (Inst)$3); }
XX
/ nothing /
expr
arglist ',' expr
( $$ = 0; 1
{ $$ - 1 ; >
{ $ $ = $ 1 + 1 ;
>
APPENDIX 3
H O C LISTING
/ end of grammar /
#include <stdio.h>
#include <ctype.h>
char
progname;
int
lineno = 1;
#include <signal.h>
#include <setjmp.h>
jmp_buf begin;
int
indef;
char
nfile;
/* input file ame /
FILE
fin;
/ input file pointer /
char
gargv;
/ global argument liat /
int
gargc;
int c; / global for use by warningl) /
yylexl)
/* hoc6 /
{
>
p++ = c;
} while ( (c=getc( f in) ) != EOF &S. isainum (c)) ;
ngetele, fin);
p = '\0';
if ((s=lookup(sbuf)) == 0)
s = install(sbuf, UNDEF, 0.0);
yylval.sym = s;
return s->type =- UNDEF ? VAR : s->type;
if (c = '$') { / argument? /
int n = 0;
while (isdigit(c=getc(fin)))
n = 1 0 * n + c - ' 0 ' ;
ngetele, fin);
if (n 0)
execerror("strange
(char )0);
yylval.narg = n;
return ARG;
)
if (c == '"') ( / quoted string /
char sbuf[100], p, emalloct);
for (p = sbuf; (c=getc(fin)) != "" ; p++) (
if (c == '\n' !! c == EOF)
execerror("missing quote", "");
if (p >= sbuf + sizeof(sbuf) - 1) {
p = '\0';
execerror("string too long", sbuf);
)
p = backslashlc);
>
>
P = 0;
yylval.sym = (Symbol )emalloc(strlenlsbuf)+1);
strcpylyylval.sym, sbuf);
return STRING;
switch (c) (
case
case
case
case 'I':
case
case '6.';
case '\n':
default:
337
338
backslash(c)
/ get next char with \'s interpreted /
int c;
{
char indexl); /* 'strchrl)' in some systems /
static char transtab[] = "b\bf\fn\nr\rt\t";
if (c 1= ' W ' )
return c;
c - getc(fin);
if (slower(c) 5.5. ndex(transtab, c))
return index(transtab, c)[1];
return c;
>
if (c == expect)
return ifyes;
ngetele, fin);
return ifno;
>
defnonly(s)
/ warn if llegal definition /
char s;
(
if (lindef)
execerrorls, "used outside defnition");
}
yyerror(s)
/ report compile-time error /
char s;
<
>
>
mainlargc, argv)
/ hoc6 */
char *argv[];
(
int i, fpecatchl);
progname = argv[0];
if (arge == 1) {
/ fake an argument list /
static char stdinonly[ ] = {
};
gargv
garge
> else {
gargv
garge
= stdinonly;
= 1;
= argv+1;
= argc-1;
init();
while (moremput( ))
run();
return 0;
APPENDIX 3
H O C LISTING
moreinput()
<
)
run()
<
if (gargc-- <= 0)
return 0;
if (fin S.& fin 1= atdin)
fclose(fin);
infile = gargv++;
l m e n o = 1;
if (strcmplinfile,
0) (
fin = stdin;
infile = 0;
} else if ((f in=fopen( mf lie, "r")) == NULL) (
fprintf(stderr, "Xs: can't open Xs\n", progname, infile);
return moreinputl);
}
return 1;
/* execute until EOF */
setjmp(begin);
signal(SIGFPE, fpecatch);
for (mtcodel); yyparseO; initcode(l)
execute(progbase);
warning(s, t)
/ print warning message */
char *s, *t;
1
fprintf(stderr, "Xs: Xs", progname, s);
if (t)
fprintf(stderr, " Xs", t);
if (infile)
fprintf(stderr, " in Xs", infile);
fprintf(stderr, " near line Xd\n", lineno);
while (c 1= '\n' 6>S> c != EOF)
c = getc(fin); / flush rest of input line /
if (c '\n')
lineno++;
hoc.h
typedef struct Symbol 1 /* symbol table entry /
char
ame;
short
type;
unin (
double val;
/* VAR /
double
(ptr)();
/* BLTIN /
int
(defn)();
/* FUNCTION, PROCEDURE */
char
str;
/ STRING /
) u;
struct Symbol
*next; / to link to another */
} Symbol;
Symbol install(), lookupO;
typedef unin Datum (
double val;
Symbol sym;
} Datum;
339
340
extern
extern
Datum pop()
eval(), add(), sub(), mul(), div(), negate), power();
symbol-c
#include "hoc.h"
#include "y.tab.h"
static Symbol symlist = 0 ;
Symbol lookup(s)
char s;
Symbol *sp;
Symbol nstalKs, t, d)
char s;
int t;
double d;
Symbol sp;
char *emalloc();
sp = (Symbol ) emalloc(sizeof(Symbol));
sp->name = emalloc(strlen(s)+1); / +1 for ' \ 0 '
strcpy(sp->name, s);
sp->type = t;
sp->u.val = d;
sp->next = symlist; /* put at front of list */
symlist = sp;
return sp;
char emallocln)
/ check return from malloc */
unsigned n;
I
char *p, malloc!);
p = malloc(n);
if (p == 0)
execerror("out of memory", (char *) 0);
return p;
#include "hoc.h"
#include "y.tab.h"
#include <stdio.h>
#define NSTACK
256
/* the stack /
/ next free spot on stack /
NPROG
2000
proglNPROG];
/ the machine /
progp;
/ next free spot for code generation
pe;
/ program counter during execution /
progbase = prog; / start of current subprogram /
returning;
/ 1 if return stmt seen */
/*
/
/
/
/
APPENDIX 3
H O C LISTING
APPENDIX 3
/ frame pointer */
initcode() {
progp = progbase;
stackp stack;
fp = frame;
returning = 0;
}
push(d)
Datum d;
<
Datum pop()
{
if (stackp stack)
execerror("stack underflow", (char *)0);
return --stackp;
}
constpush)
{
Datum d;
d.val = ((Symbol *)pc++)->u.val;
push(d);
1
varpush()
{
Datura d;
d.sym = (Symbol >(pc++);
push(d);
)
whilecode()
<
Datum d;
Inst savepc = pe;
execute(savepc*2);
/ condition /
d = pop();
while (d.val) {
execute!((Inst )(savepc))); / body /
if (returning)
break;
execute(savepc+2) ;
/ condition /
d = pop( );
)
if (Ireturning)
pe = ((Inst )(savepc+1)); / next stmt /
}
ifcode()
<
Datum d;
Inst savepc = pe;
/ then part /
execute(savepc+3);
/ condition /
d = pop();
if (d.val)
execute(((Inst )(savepc)));
else if (((Inst )(savepct1))) / else part? /
execute!((Inst )(savepc1)));
if (Ireturning)
pe = ((Inst )(savepc+2)); / next stmt /
define(sp)
/ put func/proc in symbol table /
Symbol sp;
<
sp->u.defn = (Inst)progbase;
/ start of code /
progbase - progp;
/ next code starts here */
)
341
342
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
callO
/* cali a function /
<
ret( )
int i;
for (i = 0; i < fp->nargs; i++)
pop O;
/* pop arguments /
pe = (Inst )fp->retpc;
--fp;
returning = 1;
funcrett)
Datum d;
if (fp->sp->type == PROCEDURE)
execerror(fp->sp->name, "(proc) returns valu");
d = pop();
/ preserve function return valu /
ret();
push(d);
>
procretO
/ return from a procedure /
(
if (fp->sp->type == FUNCTION)
execerror(fp->sp->name,
"(func) returns no valu");
ret) ;
1
double getarg( )
/ return p o m t e r to argument /
(
int nargs = (int) pc++;
if (nargs > fp->nargs)
execerror(fp->sp->name, "not enough arguments");
return Sfp->argn[ nargs - fp->nargs].val;
}
arg()
<
>
Datum d;
d.val = getargO;
push(d);
argassign()
/ store top of stack in argument /
1
Datum d;
d = pop();
push(d);
/ leave valu on stack /
getarg() = d.val;
}
bltm( )
<
Datum d;
d = pop();
d.val = ((double ()())pc++)(d.val);
push(d);
APPENDIX 3
H O C LISTING
APPENDIX 3
evalU
{
add( )
{
>
sub( )
<
>
mu ()
<
div( )
{
negate()
(
Datum d;
d = pop();
d.val = -d.val;
push(d);
>
gt( )
<
>
lt()
{
>
343
344
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
ge( )
<
Datum d1, d2 ;
d2 = pop();
d1 = pop();
dl.val = (double)(d1.val >= d2.val);
pushdl);
le )
{
eq( )
<
ne )
(
and( )
(
or )
(
>
not( )
1
Datum d;
d = pop) ;
d.val = (double)(d.val == 0.0);
pushd);
power()
(
APPENDIX 3
H O C LISTING
assign()
<
<
Datum d;
d = pop();
printf("\t%.8g\n", d.val);
}
prexprt)
(
}
prstrt)
{
}
Datum d;
d pop();
printf("%.8g ", d.val);
/ print string valu /
printf ( "54s" , (char ) pct+);
varreadf)
/* read into variable /
(
Datum d;
extern FILE fin;
Symbol var = (Symbol ) pc++;
Again:
switch (fscanfffin, "%lf", 5.var->u. val) ) (
case EOF;
if (moreinput())
goto Again;
d.val = var->u.val = 0.0;
break;
case 0.
execerror("non-number read into", var->name);
break;
default:
d.val = 1.0;
break;
)
var->type = VAR;
push(d);
}
Inst code(f)
/ install one instruction or operand /
Inst f;
{
execute(p)
Inst p;
<
345
346
APPENDIX 3
THE UNIX P R O G R A M M I N G E N V I R O N M E N T
#include "hoc.h"
#include "y.tab.h"
#include <math.h>
extern double
static struct {
char
ame;
int
kval;
} keywords[] = {
"proc",
"func",
"return",
"if" ,
"else",
"while",
"print",
"read",
0,
>;
PROC,
FUNC,
RETURN,
IF,
ELSE,
WHILE,
PRINT,
READ,
0,
/ Constants
static struct {
char ame;
double cval;
} constsl) = {
"PI",
3.14159265358979323846,
"E",
2.71828182845904523536,
"GAMMA", 0.57721566490153286060,
"DEG", 57.29577951308232087680,
"PHI",
1.61803398874989484820,
0,
0
>;
static struct {
/
char ame;
double
(nfunc)();
} builtins[] = {
"sin", sin.
"eos", eos,
"atan", atan,
"log", Log,
/.
"log10" , Log10, /
"exp", Exp,
/
"sqrt", Sqrt,
/
"int", integer
"abs", f abs,
0,
0
init()
m t e g e r ( );
/ Keywords /
/ Euler */
/ deg/radian /
/ golden ratio
Built-ins /
checks
checks
checks
checks
range
range
range
range
/
/
/
/
math.c
#include <math.h>
#include <errno.h>
extern int
errno;
double errcheckl );
double Log(x)
double x;
<
H O C LISTING
APPENDIX 3
double Log10(x)
double x;
return errcheckllog10(x), "log10");
double Sqrt(x)
double x;
return errchecklsqrt(x), "sqrt");
double Exp(x)
double x;
return errchecklexp(x), "exp");
double Pow(x, y)
double x, y;
return errcheck(pow(x,y), "exponentiation");
double integer(x)
double x;
return (double)(long)x;
double errcheck(d, s)
double d;
char s;
if (errno EDOM) (
errno = 0;
execerrorls, "argument out of domain");
> else if (errno == ERANGE) (
errno = 0;
execerror(s, "result out of range");
1
return d;
YFLAGS = -d
OBJS = hoc.o code.o init.o math.o symbol.o
hoc6:
$(OBJ S)
cc $(CFLAGS) $(OBJS) -lm -o hoc6
hoc.h
clean:
y.tab.h
-cmp -s x.tab.h y.tab.h !! cp y.tab.h x.tab.h
347
INDEX
349
a r g u m e n t s , h o c 332
a r g u m e n t s , nuil 84
a r g u m e n t s , optional 178
a r g u m e n t s , p r o g r a m 174, 220
a r g u m e n t s , shell 82, 160
a r g u m e n t s , t r o f f m a c r o 301
a r g v 174, 178
arithmetic, a w k 118
ASCII character set 42, 106, 107
a s s i g n function, h o c 4 264
a s s i g n m e n t , c o m m a n d - l i n e 90
assignment expression 242, 329
assignment expression, awk 126
a s s i g n m e n t . mltiple 242, 329
assignment vs expression 246
associative a r r a y , a w k 123, 128
associativity 238, 243, 251
a t c o m m a n d 35, 129
a t c o m m a n d , perpetual 129
a t o i 184
a w k # c o m m e n t 117
a w k % operator 117
a w k ++ operator 121
a w k + = o p e r a t o r 118
a w k - - o p e r a t o r 121
a w k arithmetic 118
a w k assignment expression 126
a w k associative array 123, 128
a w k BEGIN pattern 118
a w k b r e a k statement 121
a w k c o m m a n d 114
a w k control flow 119
a w k END pattern 118
a w k e x i t statement 122
a w k - f 114
a w k - F 115
a w k field, $/i 115
awk field s e p a r a t o r s 116
a w k fields 115
a w k FILENAME variable 121
a w k f o r statement 121, 124
a w k FS variable 118, 122
a w k functions, table of 123
a w k i f - e l s e statement 121
a w k input line, $0 116
a w k I/O redirection 130
a w k l e n g t h function 117
a w k , m e a n i n g of 131
a w k multi-line record 130
a w k negated pattern 117
a w k n e x t statement 122
a w k NF variable 115
350
awk
awk
awk
awk
awk
awk
awk
awk
awk
awk
awk
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
NR variable 116
o p e r a t o r s , table of 119
pattcrn r a n g e 130
p a t t e r n s 116
p r i n t statement 114
p r i n t f statement 116
s p l i t function 122
string concatenation 125
strings 1 1 9 , 1 2 5
s u b s t r function 117
variable initialization 118,
119
a w k variables, table of 119
a w k variables vs shell variables
115
a w k w h i l e statement 121
\ b backspace convention 4 3
.B c o m m a n d , ms 294
background process, & 33, 73,
226
>
backquotes, '
86, 139
b a c k q u o t e s , nested 87, 157
backslash 78, 157
backslash, erasing a 6
b a c k s l a s h function 277
backslash into t r o f f , getting
298
backslash, quoting with 6, 29,
75, 324
backspace 6, 172
backspace convention, \ b 4 3
backspace, ctl-h 2, 36
b a c k u p , file 60
B a c k u s - N a u r Form 234
b a c k w a r d s c o m m a n d 122
b a s c o m m a n d 284
BASIC 233
b e c o m m a n d 39, 284
BEGIN p a t t e r n , a w k 118
Belle chess c o m p u t e r 231
Bentley, Jon x, 287
Berkeley 4 1BSD x
Bianchi, Mike x
Bimmler, Elizabeth x, 34
/ b i n directory 24, 37, 63, 142
b i n directory, personal 81, 90,
134
binary files 47
blank, u n p a d d a b l e 299
blanks in a r g u m e n t s 161
block device 66
block, disc 14, 50, 66, 203
b l t m f u n c t i o n , h o c 4 264
B N F 234
bootstrap 63, 67
Bourne, Steve 100, 200
. b p c o m m a n d , t r o f f 301
. b r c o m m a n d , t r o f f 300
B r a d f o r d , Ed x
B R E A K 3, 7
b r e a k statement, a w k 121
b r e a k statement, shell 160
b u f f e r i n g 45, 180, 201, 203, 223
B U F S I Z 183, 203
bug, d i f f 167
bug, l s 14, 60, 163
bug, n o h u p 151
bug, p 185
bug, p x c k 188
bug, s e d 172
bug, shell 159
bug, s o r t 4 7
bug, s q r t 252
comm c o m m a n d 107
c o m m a n d a r g u m e n t s 14, 74, 178
c o m m a n d interpreter 26
c o m m a n d options 13, 14
c o m m a n d s e p a r a t o r , ; 33, 71
c o m m a n d - l i n e assignment 90
c o m m a n d s , creating shell 80
c o m m a n d s executable, m a k i n g 81
c o m m a n d s , ms 291
c o m m a n d s , p e r m u t e d index to 2,
10
c o m m a n d s , personal 84
c o m m a n d s , table of ed 327
c o m m a n d s , table of file 21
c o m m a n d s , table of s e d 112
c o m m e n t , # shell 7, 77
c o m m e n t , a w k # 117
c o m p a r i n g files 20, 107
compiler-compiler 235
compiling a C p r o g r a m 174
computer-aided instruction 11
c o n c a t e n a t i o n , a w k string 125
C o n d o n , Joe 231
conflict, shift/reduce 253, 268
constants, table of h o c 246, 330
c o n s t p u s h function, h o c 4 263
continuation, shell line 77
CONTROL 2
control character 2
control fiow, a w k 119
convention, \ b backspace 4 3
c o n v e n t i o n , . c filename 4 6
c o n v e n t i o n , filename 26
c o n v e n t i o n , . h 247
c o n v e n t i o n , . 1 filename 257
c o n v e n t i o n , \ n newline 4 3
c o n v e n t i o n , \ r carriage return 4 3
convention, \ t t a b 4 3
convention, . y filename 236
copying a file 17, 61
core d u m p 188, 225, 242
c o r e d u m p , c t l - \ 150, 188
correction, spelling 208, 213
counting files 30
counting users 30
counting w o r d s 18
cp c o m m a n d 17, 61, 206
c r a s h , system 12, 64
c r e a t permissions 205
c r e a t system cali 205
create a p r o g r a m , program to 99,
307
creating a file 202
creating shell c o m m a n d s 80
creation, process 220
C R L F 44, 174
cross-device link 67
c r y p t c o m m a n d 52, 6 8
c s h c o m m a n d 100
c t l - \ core d u m p 150, 188
c t l - \ quit signal 225
ctl-c D E L E T E 3
ctl-d end of file 2, 8, 31, 45
ctl-d to logout 8
ctl-g ring bell 2, 73
ctl-h backspace 2, 36
c t l - i tab 2
ctl-q resuming output 8
ctl-s stopping output 8, 15
ctl-u line kill 6
c t y p e tests, table of 174
c t y p e . h h e a d e r file 173
cu command 39
INDEX
351
e g r e p - h 307
e m a c s screen editor 11
e m a l l o c function 248
e m b e d d e d action 276
e m p t y dependeney rule 255
e m p t y production 237
encryption 52
encryption c o m m a n d , e d 327
encryption, password 53
end of file 44, 202, 203
end of file, ctl-d 2, 8, 31, 45
END p a t t e r n , a w k 118
EOF 173, 204
e q n examples 304
erase character 7, 29
erase character, # 6
erase c h a r a c t e r , setting 35
erasing a backslash 6
e r r c h e c k function 253
e r r n o 206, 228
e r r n o . h header file 228, 252
e r r o r function 207
e r r o r handling 218
e r r o r message 5, 17, 32, 56, 61,
93, 142, 148, 180, 182, 302
error recovery, h o c 2 244, 245
e r r o r recovery, h o c 3 252
e r r o r recovery, h o c 6 276
e r r o r , s t a n d a r d 32, 92, 177, 202
e r r o r status, system cali 206
e r r o r , w r i t e 219
escape character, \ 6
escape to shell, I 9, 35, 92, 184,
194, 228, 254, 321
/ e t c directory 6 3
/ e t c / g r o u p 54
/ e t c / m o u n t command 6 6
/ e t c / p a s s w d password file 53,
103, 115
e v a l c o m m a n d 156
e v a l function, h o c 4 264
evolution of c h e c k m a i l 215
evolution o f d o c t y p e 308
evolution of h o c 233
exception, fioating point 242, 243
e x e c e r r o r function, h o c 2 244
e x e c l p system cali 220
executable, m a k i n g c o m m a n d s 81
e x e c u t e function, h o c 4 263
e x e c u t e function, h o c 6 281
e x e c v p system cali 220
e x i t c o m m a n d 142
e x i t function 174
e x i t s t a t e m e n t , a w k 122
exit status 140, 142, 144, 174,
222
exit status, $? shell 140
exit status of pipeline 145
exit status of shell file 142
E x p function 252
exponentiation o p e r a t o r , ~ 245
e x p o r t c o m m a n d 38, 9 1
expression, assignment 242, 329
expressions, ed line n u m b e r 322
\ f c o m m a n d , t r o f f 291, 299
f a c function 274, 333
f a l s e c o m m a n d 147, 149
f c l o s e 179
. FE c o m m a n d , ms 296
features 185, 316
F e l d m a n , Stu 287
f f l u s h 183
f g e t s 183
352
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
f g r e p c o m m a n d 103
f g r e p -f
103
. f i c o m m a n d , t r o f f 300
f i b f u n c t i o n 274, 284
f i e l d c o m m a n d 126
f i e l d , Sn a w k 115
field s e p a r a t o r , shell 157, 160,
163, 164
field s e p a r a t o r s , a w k 116
f i e l d s , a w k 115
f i e l d s , s o r t i n g on 106
file 11
file a c c e s s , r a n d o m 2 0 7
file a c c e s s , s i m u l t a n e o u s 203
file b a c k u p 6 0
f i l e command 4 6
file c o m m a n d s , t a b l e of 21
file, c o p y i n g a 17, 61
file, c r e a t i n g a 2 0 2
file d a t e s 57
file d e s c r i p t o r 9 2 , 2 0 1 , 2 2 3
file, d e v i c e 4 1 , 6 5
file, m o v i n g a 16
file o p e n 176
file, o p e n i n g a 201
file p e r m i s s i o n s 5 2 , 54, 205
F I L E p o i n t e r 177, 202
file, r e m o v i n g a 17
file, r e n a m i n g a 16
file r e s t o r e 60
file, shell 81
file s t r u c t u r e 4 1 , 47
file s y s t e m 1 1 , 2 1 , 2 0 9
file system hierarchy 24, 63
file s y s t e m m o u n t i n g 6 7
file t i m e s 57
file t y p e s 4 6 , 47
filename convention 26
filename convention, ,c 46
f i l e n a m e c o n v e n t i o n , . 1 257
filename convention, . y 236
f i l e n a m e r u l e s 17
filename search 50
filename shorthand 26
FILENAME v a r i a b l e , a w k 121
f i l e n o m a c r o 202
f i l e s , c o m p a r i n g 2 0 , 107
files, formatless 47
files, text 47
filling, line 291
filters ix, 101
f i n d command 52
f i n d i n g a file 50, 52
finite state m a c h i n e 2 7 7
Flandrena, Bob x
f l e a s 18, 3 2 0
f l o a t i n g point e x c e p t i o n 242, 243
f o d c o m m a n d 125
f o l l o w function 270
font change 299
f o n t c h a n g e s , m s 294
f o p e n 176
f o p e n m o d e s 177
f o r i l o o p , shell 145
f o r l o o p f o r m a t , shell 9 5
f o r s t a t e m e n t , a w k 121, 124
f o r s y n t a x , shell 9 5 , 144
f o r k s y s t e m cali 2 2 2
f o r m a t , directory 51, 59, 209
f o r m a t independence 290
f o r m a t , i n o d e 214
f o r m a t , shell f o r loop 9 5
formatless files 47
formatter, n r o f f 289
formatter, r o f f 289
f o r m a t t e r , Scribe 314
f o r m a t t e r , T E X 314
f o r m a t t e r , t r o f f 289
FORTRAN 47
F O R T R A N 7 7 39, 287
f o r t u n e game 36
f p e c a t c h f u n c t i o n , h o c 2 244
fprintf
179
f p u t s 183
f r e e s p a c e , disc 6 7
f r e x p 241
. FS c o m m a n d , ms 2 9 6
FS v a r i a b l e , a w k 118, 122
f s t a t system cali 2 1 5
. f t c o m m a n d , t r o f f 2 9 1 , 301
full d p l e x 2, 4
f u n c r e t function 279
f u n c t i o n d e f i n i t i o n , h o c 332
f u n c t i o n s , h o c 3 built-in 2 4 5
f u n c t i o n s , table of a w k 123
f u n c t i o n s , table o f h o c 3 3 0
f u n c t i o n s , table of s t a n d a r d I/O
192
f u n c t i o n s , table of s t r i n g 176
F u r u t a , R i c h a r d 314
game, f o r t u n e 36
g a m e , q u i z 327
g a m e s 11, 25
G a y , David x
g e t c o m m a n d 168
g e t a r g f u n c t i o n 281
g e t c 177
g e t c h a r 172
g e t c h a r m a c r o 177
g e t e n v 199
g e t l o g i n 216
g e t n a m e c o m m a n d 109
g e t o p t 179
g e t t i n g b a c k s l a s h into t r o f f 2 9 8
g l o b a l c o m m a n d s , e d 325
G o s l i n g , J a m e s 100
g r a m m a r 234
g r a m m a r , h o c 1 237
g r a m m a r , h o c 2 243
g r a m m a r , h o c 3 250
g r a m m a r , h o c 4 259
g r a m m a r , h o c 5 267
g r a m m a r , h o c 6 275
g r a m m a r production 235
g r e p - b 111
g r e p c o m m a n d 18, 102
g r e p -e 79
g r e p e x a m p l e s 102
g r e p f a m i l y , design o f 105
g r e p - 1 87
g r e p , meaning of 18
g r e p - n 102
g r e p r e g u l a r e x p r e s s i o n s 102
g r e p - v 18, 102, 111
g r e p - y 85, 102
g r o u p - i d 52
. h c o n v e n t i o n 247
h a n g u p signal 150, 225
Hanson, Dave x
Hardin, Ron x
Harris, Marin x
h a s h i n g 124, 314
h e a d e r file 247, 261, 2 8 6
h e a d e r file, c t y p e . h 173
h e a d e r file, d i r . h 2 0 9
h e a d e r file, e r r n o . h 2 2 8
header f i l e , m o . h 219
header f i l e , m a t h . h 252
header f i l e , s e t j m p . h 227
h e a d e r file, s i g n a l . h 191, 225
h e a d e r file, s t a t . h 214
h e a d e r f i l e , s t d i o . h 173
h e a d e r file, t y p e s . h 214
here d o c u m e n t 94, 98
H e w e t t , A l a n 100
hierarchy, directory 63, 208
h i e r a r c h y , file s y s t e m 2 4 , 6 3
hierarchy, process 34, 48
h o c a r g u m e n t s 332
h o c constants, table of 246, 330
h o c , e v o l u t i o n o f 233
h o c function definition 332
h o c f u n c t i o n s , table o f 3 3 0
h o c input f o r m a t 331
h o c m a n u a l 329
h o c , m e a n i n g o f 234
h o c o p e r a t o r s , table o f 3 3 0
h o c p r i n t s t a t e m e n t 331
h o c p r o c e d u r e d e f i n i t i o n 332
h o c r e a d s t a t e m e n t 331
h o c , reliability o f 2 6 5 , 2 7 4
h o c sizes, table o f 283
h o c stages 233
h o c t i m e s , table o f 284
h o c 1 g r a m m a r 237
h o c 1 m a i n function 239
h o c 1 m a k e f i l e 241
h o c 1 unary minus 240
h o c 1 w a r n i n g function 240
h o c 1 y y e r r o r function 240
h o c 1 y y l e x function 239
h o c 2 e r r o r r e c o v e r y 2 4 4 , 245
h o c 2 e x e c e r r o r f u n c t i o n 244
h o c 2 f p e c a t c h f u n c t i o n 244
h o c 2 grammar 243
h o c 2 m a i n f u n c t i o n 244
h o c 2 y y l e x function 245
h o c 3 built-in f u n c t i o n s 245
h o c 3 e r r o r r e c o v e r y 252
h o c 3 g r a m m a r 250
h o c 3 h o c . h 247
h o c 3 m i t function 249
h o c 3 m i t . c f i l e 249
h o c 3 l e x m a k e f i l e 257
h o c 3 l e x versin 256
h o c 3 m a i n function 252
h o c 3 m a k e f i l e 255
h o c 3 m a t h . c file 2 5 2
h o c 3 s o u r c e files 247
h o c 3 y y l e x f u n c t i o n 251
h o c 4 a d d f u n c t i o n 264
h o c 4 a s s i g n f u n c t i o n 264
h o c 4 b l t i n f u n c t i o n 264
h o c 4 c o d e f u n c t i o n 263
h o c 4 code generation 258
h o c 4 c o d e . c file 262
h o c 4 c o n s t p u s h f u n c t i o n 263
h o c 4 data structures 262
h o c 4 e v a l f u n c t i o n 264
h o c 4 e x e c u t e f u n c t i o n 263
h o c 4 g r a m m a r 259
h o c 4 h o c . h 261
h o c 4 m a i n function 260
h o c 4 m a k e f i l e 266
h o c 4 p o p f u n c t i o n 262
h o c 4 p r i n t f u n c t i o n 264
h o c 4 p u s h f u n c t i o n 262
h o c 4 v a r p u s h f u n c t i o n 263
h o c 4 y y l e x f u n c t i o n 261
INDEX
h o c 5 g r a m m a r 267
h o c 5 h o c . h 270
h o c 5 f c o d e f u n c t i o n 272
h o c 5 i n i t . c file 2 7 2
h o c 5 y y l e x function 270
h o c 6 c o d e . c file 2 7 8
h o c 6 data structures 278
h o c 6 error recovery 276
h o c 6 e x e c u t e f u n c t i o n 281
h o c 6 g r a m m a r 275
h o c 6 h o c . h 278
h o c 6 f c o d e f u n c t i o n 281
h o c 6 i n i t c o d e function 278
h o c 6 m a k e f i l e 285
h o c 6 y y l e x function 277
h o c . h , h o c 3 247
h o c . h , h o c 4 261
h o c . h , h o c 5 270
h o c . h , h o c 6 278
Holzmann, Gerard x
home directory 2 1 , 3 6
HOME shell v a r i a b l e 36, 88
H u n t , W a y n e 200
.1 command, ms 292,294
i d e a l c o m m a n d 313
i d i f f c o m m a n d 193
i d i f f , d e s i g n o f 194, 198
d i f f f u n c t i o n 197
i d i f f m a i n f u n c t i o n 195
i f code generation 269
f v s c a s e 141
i f c o d e function, h o c 5 272
i f c o d e f u n c t i o n , h o c 6 281
f - e l s e s t a t e m e n t , a w k 121
f - e l s e s t a t e m e n t , shell 140
I F S shell v a r i a b l e 157, 163, 164
i g n o r i n g i n t e r r u p t s 228
i g n o r i n g signis 1 5 1 , 1 5 3 , 2 2 6
# i n c l u d e 173
i n d c o m m a n d 109, 116
n d e x 218
index to c o m m a n d s , permuted 2,
10
i n h e r i t a n c e , open f i l e 223
i n h e r i t a n c e , shell v a r i a b l e 89, 91
i m t function, h o c 3 249
i n i t . c file, h o c 3 2 4 9
i n i t . c file, h o c 5 272
i n i t c o d e function, h o c 6 278
initialization, a w k v a r i a b l e 118,
119
inode 57
i n o d e f o r m a t 214
i n o d e table 2 0 9
i n o . h h e a d e r file 2 1 9
input f o r m , y a c c 2 3 6
i n p u t f o r m a t , h o c 331
input line, $0 a w k 116
i n p u t r e d i r e c t i o n , < 29
i n p u t , s t a n d a r d 30, 9 2 . 177, 2 0 2
input, t r o f f 290
i n s e r t i n g n e w l i n e , s e d 111
i n s t a l l f u n c t i o n 248
i n s t r u c t i o n , c o m p u t e r - a i d e d 11
i n t e g e r f u n c t i o n 253
i n t e r p r e t e r 258
interpreter, command 26
INTERRUPT 3
i n t e r r u p t signa] 150, 225
i n t e r r u p t e d s y s t e m cali 228
i n t e r r u p t s , c a t c h i n g 150, 198
i n t e r r u p t s , i g n o r i n g 2 2 6 , 228
i - n u m b e r 58
i-number, zero 59
I / O l i b r a r y , s t a n d a r d 171
I / O , low-level 201
I/O r e d i r e c t i o n 29, 30, 4 7 , 74,
8 0 , 9 2 , 180, 183, 202
I/O r e d i r e c t i o n , a w k 130
I/O r e d i r e c t i o n , shell 159
I / O t i m i n g , table of 203
. I P c o m m a n d , m s 296
i s a s c i i 173
isprint
173
J o h n s o n , Steve x, 200, 235, 287,
314
J o y , Bill 100
j u s t i f i c a t i o n , line 291
K a t s e f f , Howard 200
.KE c o m m a n d , ms 296
kernel 1 , 7 , 2 3 , 3 2 , 4 3 , 5 3 , 5 5 ,
9 9 , 201
K e r n i g h a n , Brian 39, 131, 171,
314
.KF command, ms 2%
kill vm
188
k i l l - 9 152
k i l l c o m m a n d 34, 225
K n u t h , D o n 90, 314
. K S c o m m a n d , ms 296
1 c o m m a n d , s e d 172, 174
. 1 filename c o n v e n t i o n 2 5 7
L a m b , D a v i d 231
l a n g u a g e , choice of 170, 171,
181. 258, 277
l a n g u a g e d e v e l o p m e n t 233, 2 8 6
l a n g u a g e , s p e c i a l - p u r p o s e 286,
290
layout, page 289
le command 83
l e f u n c t i o n 271
l e a r n command 11
5 l e f t 238
l e n g t h f u n c t i o n , a w k 117
L e s k , M i k e 200, 2 8 7
l e x library, - 1 1 257
l e x m a k e f i l e , h o c 3 257
l e x regular expressions 256
l e x v e r s i n , h o c 3 256
lexical a n a l y z e r 235
lexical t o k e n 235
/ l i b directory 6 3
library, - 1 1 l e x 257
l i b r a r y , - l m m a t h 255
limit, o p e n file 206
Linderman, John x
line $ , e d 3 2 2
line . , e d 3 2 2
line c o n t i n u a t i o n , shell 77, 108
line filling 291
line j u s t i f i c a t i o n 291
line kill 7
line kill, @> 6
line kill c h a r a c t e r 29
line kill c h a r a c t e r , setting 35
line kill, ctl-u 6
line n u m b e r e x p r e s s i o n s , e d 322
line n u m b e r s , e d 320
line n u m b e r s , table o f e d 3 2 7
line p r i n t e r 16
line spacing 296
l i n e - m o v i n g c o m m a n d s , e d 325
link 59, 85, 96
l i n k , cross-device 67
l i n k , m a k i n g a 59
l i n t c o m m a n d 190
353
L i o n s , J o h n 315
- 1 1 l e x library 2 5 7
- l m math library 255
ln command 59
L o g function 252
L o g 10 function 252
logout 8, 45
l o g o u t , ctl-d to 8
Lomuto, Ann 39
L o m u t o , Nico x, 39
l o n g j m p 2 2 7 , 244
l o o k u p f u n c t i o n 248
l o o p , shell f o r i 145
loops, shell 94
low-level I/O 201
. LP c o m m a n d , ms 296
l p r command 16
l s b u g 14, 6 0 , 163
l s - c 58
ls command 13
l s - d 55
l s - f 51
l s - g 53
l s - i 58
l s - 1 13, 14
l s - r 14
l s - t 13, 5 8
l s - u 58
l s e e k s y s t e m cali 122, 207
m c o m m a n d 83
m a c r o a r g u m e n t s , t r o f f 301
m a c r o , f i l e n o 202
m a c r o , g e t c h a r 177
m a c r o p a c k a g e 289
m a c r o p a c k a g e , m a n 309
m a c r o p a c k a g e , mm 290, 297
macro package, ms 290
macro, p o p 286
macro, p u s h 286
m a c r o , p u t e h a r 177
m a c r o s , d e f i n i n g t r o f f 301
m a c r o s , y a c c 255
m a g i c n u m b e r 4 6 , 191
M a h a n e y , Steve x
m a i l command 8
m a i l , n o t i f i c a t i o n of 8, 36, 147,
215
mail, remote 9, 97
mail, sending 8
MAIL shell v a r i a b l e 3 6 , 147
m a i n function, h o d 239
m a i n f u n c t i o n , h o c 2 244
m a m function, h o c 3 252
m a i n function, h o c 4 260
m a i n function, d i f f
195
m a i n f u n c t i o n , p 182, 184, 199,
213
m a i n f u n c t i o n , p i c k 187
m a i n function, s v 217
m a i n f u n c t i o n , v i s 178
m a i n f u n c t i o n , z a p 191
m a k e $ ? c o m m a n d 266
m a k e - c o m m a n d 266
make
c o m m a n d 255
m a k e c o m m a n d 241
m a k e - n 255
m a k e - t 255
m a k e f i l e , h o c 1 241
m a k e f i l e , h o c 3 255
m a k e f i l e , h o c 3 l e x 257
m a k e f i l e . h o c 4 266
m a k e f i l e , h o c 6 285
m a k i n g a d i r e c t o r y 25
354
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
m a k i n g a link 59
m a k i n g c o m m a n d s executable 81
m a n c o m m a n d 11, 309
m a n m a c r o package 309
m a n - t 309
m a n u a l , h o c 329
m a n u a l organization 10
m a n u a l page 308
M a r a n z a n o , Joe 200
mark c o m m a n d , e d 326
M a r t i n , Bob x
M a s h e y , John 39, 100
math library, - l m 255
m a t h . c file, h o c 3 252
m a t h . h h e a d e r file 252
Mcllroy, D o u g vii, x, 47, 78,
200, 314
M c M a h o n , Lee 131
m e a n i n g of awk 131
meaning of c a t 15
meaning of g r e p 18
m e a n i n g of h o c 234
m e a n i n g of U N I X vii, 1
m e m o r y fault 188
m e s g c o m m a n d 10, 68
message, e r r o r 5, 17, 32, 56, 61,
93, 142, 148, 180, 182, 302
m e t a c h a r a c t e r s 102, 220
m e t a c h a r a c t e r s , shell 74
m e t a c h a r a c t e r s , table of shell 75
m i n d i s t function 211
m k d i r c o m m a n d 25, 4 8
m k t e m p 195
mm c o m m a n d s , table of 297
mm m a c r o package 290, 297
m o d e s , f o p e n 177
modularity 209, 247, 261, 302
n o n . o u t 285
m o r e c o m m a n d 15
Morris, Bob 70
m o u n t i n g , file system 67
m o v i n g a directory 62
m o v i n g a file 16
ms . B c o m m a n d 294
ms c o m m a n d s 291
ms c o m m a n d s , table of 296
ms .DE c o m m a n d 293
ms . D S c o m m a n d 293
m s . F E c o m m a n d 296
ms font changes 294
ms . FS c o m m a n d 296
ms . I c o m m a n d 292, 294
ms . IP c o m m a n d 296
ms . KE c o m m a n d 296
ms . KF c o m m a n d 296
ms . KS c o m m a n d 296
ms . LP c o m m a n d 296
ms m a c r o package 290
ms . PP c o m m a n d 291
ms . R c o m m a n d 294
M U L T I C S vii, 70
multi-line r e c o r d , a w k 130
mltiple assignment 242, 329
mv command 1 6 , 6 1
$n a w k field 115
\ n newline convention 4 3
$n shell a r g u m e n t 82
Sn y a c c valu 237
a m e s , table o f t r o f f 298
a m e s , t r o f f character 297
n a r g s c o m m a n d 158
n c o p y function 198
negated character class 102
INDEX
p u t c h a r m a c r o 177
pwd c o m m a n d 21, 48
q c o m m a n d , s e d 110
quit signal 225
quit signal, c t l A 225
q u i z game 327
quotes 28, 85, 94, 104, 126
quotes, "
" 75, 85
quotes, '
' 75, 85
q u o t e s , V ' 85
q u o t e s , nested 75, 86, 112, 128
q u o t e s , t r o f f 295
quoting with backslash 6, 29, 75,
324
\ r carriage return convention 4 3
.R c o m m a n d , ms 294
r a n d o m file access 207
r a n g e , a w k pattern 130
r a n g e selection, s e d 111
R a t f o r 287
r e a d c o m m a n d 159
r e a d statement, h o c 331
r e a d system cali 44, 202
r e a d s l o w command 204,231
record, a w k multi-line 130
recursion 18, 355
redirection, << 94
redirection, < input 29
redirection, > output 29
redirection, >> output 29
redirection, 1>&2 142
redirection, 2>&1 93, 202
redirection, 2>filename 93
redirection, a w k I/O 130
redirection, I/O 29, 30, 47, 74,
80, 92, 180, 183, 202
redirection, shell I/O 159
redirections, table of shell 94
r e f e r c o m m a n d 313
regular expression 102, 315, 319
regular expression, $ 102, 324
regular expression, (
) 104
regular expression, 103, 324
regular expression, + 104
regular expression, . 103, 324
regular expression, . 109
regular expression, ? 104
regular expression, [
] 102,
324
A
regular expression, [ . ] 102,
324
regular expression, ~ 102, 324
regular expression examples, e d
325
regular expression, tagged 105,
324, 326
regular expressions, g r e p 102
regular expressions, l e x 256
regular expressions, shell vs
editor 138
regular expressions, table of 105
regular expressions, table of ed
324
Reid, Brian 314
relational operators 266
reliability of b u n d l e 99
reliability of h o c 265, 274
reliability of shell p r o g r a m s 133
r e m o t e mail 9, 97
removing a directory 26
removing a file 17
r e n a m i n g a file 16
r e p l a c e c o m m a n d 155
355
356
T H E UNIX P R O G R A M M I N G E N V I R O N M E N T
S e v e n t h E d i t i o n x, 7, 14, 3 9 , 65,
7 5 , 7 7 , 7 8 , 85, 8 7 , 100, 106,
125, 140, 151, 171, 188, 201,
2 9 0 , 3 1 3 , 314
s h - c 221
sh command 80
S h a w , A l a n 314
shell ix, 26
shell, I e s c a p e to 9, 3 5 , 9 2 , 184,
194, 2 2 8 , 254, 321
shell (
) p a r e n t h e s e s 72, 73
shell {
} p a r e n t h e s e s 168
shell * p a t t e r n 27
shell ? p a t t e r n 28
shell [
] p a t t e r n 28
shell ${
} v a r i a b l e s 148
shell ${
} v a r i a b l e s , table of
149
shell A N D , S.& 143
shell a r g u m e n t , $ 0 8 5
shell a r g u m e n t c o u n t , $ # 135
shell a r g u m e n t . Sn 82
shell a r g u m e n t p a r s i n g 161
shell a r g u m e n t s 8 2 , 160
shell a r g u m e n t s , " $ @ " 161
shell a r g u m e n t s , $ 8 3 , 85, 145,
155, 161
shell a r g u m e n t s , $@ 155
shell b r e a k s t a t e m e n t 160
shell b u g 159
shell c a s e s t a t e m e n t 134
shell c o m m a n d s , c r e a t i n g 8 0
shell c o m m e n t , # 7, 77
shell exit s t a t u s , $? 140
shell field s e p a r a t o r 157, 160,
163, 164
shell file 81
shell file, exit s t a t u s of 142
shell f o r i loop 145
shell f o r loop f o r m a t 9 5
shell f o r s y n t a x 9 5 , 144
shell f - e l s e s t a t e m e n t 140
shell I/O r e d i r e c t i o n 159
shell line c o n t i n u a t i o n 7 7 , 108
shell l o o p s 94
shell m e t a c h a r a c t e r s 74
shell m e t a c h a r a c t e r s , table of 75
shell O R , ! ! 1 4 3 , 1 6 9
shell p a r a m e t e r s 8 8
shell p a t t e r n , 7 4 , 162
shell p a t t e r n m a t c h i n g 26, 134,
136, 162
shell p a t t e r n s in p a t h n a m e s 28
shell p a t t e r n s , table of 136
shell p r o c e s s - i d , $$ 146
shell, p r o g r a m m a b l e 99
shell p r o g r a m m i n g 9 9 , 133
shell p r o g r a m s , reliability of 133
shell r e d i r e c t i o n s , t a b l e o f 9 4
shell u n t i l s y n t a x 145
shell v a r i a b l e i n h e r i t a n c e 8 9 , 91
shell v a r i a b l e , TERM 159
shell variable v a l u , $ 3 7 , 88
shell v a r i a b l e s 36, 88
shell v a r i a b l e s , a w k v a r i a b l e s v s
115
shell v a r i a b l e s , t a b l e of 135
shell v s e d i t o r r e g u l a r
e x p r e s s i o n s 138
shell w h i l e s y n t a x 144
shell w o r d 7 1 , 9 5 , 157
shell w o r d s e p a r a t o r s 86
s h i f t c o m m a n d 155, 168
s h i f t / r e d u c e conflict 253, 2 6 8
shorthand, filename 26
signal cali, a l a r m 2 2 9
signal, c t l - \ quit 225
signal h a n d l i n g , d e f a u l t 225, 2 2 7
signal, h a n g u p 150, 225
signal, i n t e r r u p t 150, 225
signal n u m b e r s , table of 150
signal, quit 225
s i g n a l s y s t e m cali 225
signal, t e r m n a t e 225
s i g n a l . h h e a d e r file 191, 225
signis 225
s i g n i s , & a n d 150
signis, c a t c h i n g 153
signis, ignoring 151, 153, 2 2 6
signis, resetting 227
s i m u l t a n e o u s file access 203
S i t a r , Ed x
Sixth E d i t i o n 100, 208, 315
size c h a n g e , point 300
s i z e c o m m a n d 258
size, point 296, 3 0 0
s i z e o f 211
sizes, table o f h o c 283
s l e e p 204
s l e e p command 73
S N O B O L 4 131
s o r t bug 4 7
s o r t c o m m a n d 19, 106
s o r t - d 106
s o r t - f 106
s o r t -n 19
s o r t - n 19, 106
s o r t - o 106, 152
s o r t - r 19, 106
s o r t - u 106, 307
s o r t i n g on fields 106
s o r t i n g , o r d e r of 19, 2 7 , 28
s o u r c e c o d e c o n t r o l 165, 17C
s o u r c e files, h o c 3 247
. s p c o m m a n d , t r o f f 301
s p a c i n g , line 2 9 6
s p d i s t f u n c t i o n 212
s p e c i a l - p u r p o s e l a n g u a g e 286,
290
s p e l l c o m m a n d 313
spelling correction 208, 213
Spencer, H e n r y 200
s p l i t f u n c t i o n , a w k 122
s p n a m e , design o f 2 0 9
s p n a m e function 210
s q r t b u g 252
S q r t f u n c t i o n 252
sscanf
191
stack m a c h i n e 258
stack trace 188
stack, y a c c 238
stages, h o c 233
s t a n d a r d e r r o r 3 2 , 9 2 , 177, 202
s t a n d a r d input 30, 9 2 , 177, 202
s t a n d a r d I/O f u n c t i o n s , table o f
192
s t a n d a r d I/O l i b r a r y 171
s t a n d a r d o u t p u t 3 2 , 9 2 , 177, 2 0 2
s t a r t u p , system 6 3 , 6 7
s t a t s y s t e m cali 2 1 5
s t a t . h h e a d e r file 214
s t a t u s , process 34
s t a t u s r e t u r n , w a i t 222
s t d e r r 177, 180
s t d i n 177
s t d i o . h 173
s t d i o . h d e f i n i t i o n s , table o f
178
s t d i o . h h e a d e r file 173
s t d o u t 177
S t i r l i n g ' s f o r m u l a 333
Stone, Harold 200
s t o p p i n g a p r o g r a m 7, 34
s t o p p i n g o u t p u t , c t l - s 8, 15
s t r c h r 218
s t r c m p 175
s t r e a m e d i t o r , s e d 101
s t r n d e x f u n c t i o n 192
s t r i n g c o n c a t e n a t i o n , a w k 125
s t r i n g f u n c t i o n s , table of 176
s t r i n g s , a w k 119, 125
s t r l e n 183
s t r n c m p 192
structure, directory 48
s t r u c t u r e , file 4 1 , 47
s t t y c o m m a n d 5 , 35, 4 3
s t t y - t a b s 5, 43
s t y l e c o m m a n d 313
su command 52
s u b - s h e l l 81, 8 5 , 8 9 , 9 1 , 151, 169
s u b s t r f u n c t i o n , a w k 117
s u p e r - u s e r 52. 191
s v c o m m a n d 217
s v , d e s i g n o f 217
s v function 218
s v m a i n function 217
syntax e r r o r s , y a c c 240
s y n t a x , shell f o r 9 5 , 144
s y n t a x , shell u n t i l
145
s y n t a x , shell w h i l e 144
s y s _ e r r l i s t 206
s y s . n e r r 206
s y s t e m 184, 2 2 0
s y s t e m b u g 185, 223
system cali e r r o r s t a t u s 206
s y s t e m cali, i n t e r r u p t e d 228
system cali, r e a d 4 4
s y s t e m cali, u n l i n k 195
system c r a s h 12, 64
system d e p e n d e n c y 6
s y s t e m function 224, 229
system startup 63, 67
System V x, 7 8 , 125, 140, 141
Szymanski, T o m 200
\ t tab convention 4 3
. t a c o m m a n d , t r o f f 301
tab convention, \ t
43
tab, ctl-i 2
tab stops 5
t a b s t o p s , s e t t i n g 43
table of a w k f u n c t i o n s 123
table of a w k o p e r a t o r s 119
table of a w k v a r i a b l e s 119
table o f c t y p e tests 174
table of d i r e c t o r i e s 63
t a b l e o f e d c o m m a n d s 327
t a b l e o f e d line n u m b e r s 327
table of ed regular expressions
324
t a b l e of file c o m m a n d s 21
table of h o c constants 246, 330
table of h o c functions 330
table of h o c o p e r a t o r s 330
t a b l e o f h o c sizes 283
t a b l e o f h o c t i m e s 284
t a b l e o f I/O t i m i n g 2 0 3
t a b l e of mm c o m m a n d s 2 9 7
t a b l e o f m s c o m m a n d s 296
t a b l e of r e g u l a r e x p r e s s i o n s 105
INDEX
table of s e d c o m m a n d s 112
table of shell $ { . } variables
149
table of shell m e t a c h a r a c t e r s 75
table of shell p a t t e r n s 136
table of shell redirections 94
table of shell variables 135
table of signal n u m b e r s 150
table of s t a n d a r d I/O functions
192
table o f s t d i o . h definitions 178
table of string functions 176
table o f t r o f f a m e s 298
t a b s command 5
tagged regular expression 105,
324, 326
t a i l command 1 9
t a i l - f 204
t a i l -?n 2 0
t a i l - r 122
t b l e x a m p l e 303
t e e command 7 2
TERM shell variable 37, 159
terminal echo 2, 43
t e r m n a t e signal 225
t e r m i n a t o r , newlne as 44
t e s t 1 negation 143
t e s t c o m m a n d 140
t e s t - f 140
t e s t - r 140
t e s t - t 151
t e s t - w 140
t e s t - x 140
t e s t - z 154
T E X f o r m a t t e r 314
text editor 11
text files 47
T h o m p s o n , Ken vii, x, 39, 70,
204, 219, 231, 315, 319
Tilson, Mike x
t i m e c o m m a n d 69, 9 2
t i m e o u t c o m m a n d 230
t i m e s c o m m a n d 152
times, file 57
times, table of h o c 284
timing, d o c t y p e 307
timing, table of I/O 203
/ t m p directory 63, 146
X t o k e n 238, 243
t o k e n , lexical 235
tools viii, 170, 171, 233, 287
t o u c h c o m m a n d 162
t r c o m m a n d 107
trace, stack 188
t r a p c o m m a n d 150
tree, parse 238, 254
t r o f f \ $ c o m m a n d 301
t r o f f \ & c o m m a n d 298, 304
t r o f f . b p c o m m a n d 301
t r o f f . b r c o m m a n d 300
t r o f f character a m e s 297
t r o f f c o m m a n d 292, 306
t r o f f . d e c o m m a n d 301
t r o f f \ e c o m m a n d 298
t r o f f \ f c o m m a n d 291, 299
t r o f f . f i c o m m a n d 300
t r o f f f o r m a t t e r 289
t r o f f . f t command 291,301
t r o f f , getting backslash into
298
t r o f f input 290
t r o f f - m 292
t r o f f m a c r o a r g u m e n t s 301
357
w a t c h f o r c o m m a n d 145
w a t c h w h o c o m m a n d 147
wc c o m m a n d 18
wc -1 30,80
W e h r , Larry x
W e i n b e r g e r , Peter x, 131, 231
W e y t h m a n , Jim x
w h i c h c o m m a n d 141, 143
w h i l e code generation 268
w h i l e s t a t e m e n t , a w k 121
w h i l e syntax, shell 144
w h i l e c o d e function 271, 281
who am i c o m m a n d 5
who command 5
word separators, shell 86
w o r d , shell 71, 95, 157
w o r d f r e q c o m m a n d 124
w o r d s , counting 18
working directory 21
w r i t e command 9
w r i t e e r r o r 219
w r i t e protocol 9
w r i t e system cali 202
W r i t e r ' s W o r k b e n c h 313
. y f i l e n a m e convention 236
y a c c c o m m a n d 240
y a c c - d 247, 255
y a c c input f o r m 236
y a c c macros 255
y a c c o u t p u t f o r m 236
y a c c overview 235
y a c c parsing process 237
y a c c stack 238
y a c c syntax e r r o r s 240
y a c c - v 254
y a c c valu, $ n 237
^FLAGS 255
y . t a b . c 236
y . t a b . h 247,265
y y e r r o k 244
y y e r r o r function, h o d 240
y y l e x 236
y y l e x function, h o d 239
y y l e x function, h o c 2 245
y y l e x function, h o c 3 251
y y l e x function, h o c 4 261
y y l e x function, h o c 5 270
y y l e x f u n c t i o n , h o c 6 277
y y l v a l 239, 244
y y p a r s e 235, 239
y y t e x t 256
z a p bug 186
z a p c o m m a n d 157, 158, 191
z a p , design of 198
z a p m a i n function 191
zero i-number 59