UNIX Shell programming 3rd Edition Stephen Kochan 2024 scribd download
UNIX Shell programming 3rd Edition Stephen Kochan 2024 scribd download
https://ebookultra.com
https://ebookultra.com/download/unix-shell-
programming-3rd-edition-stephen-kochan/
https://ebookultra.com/download/learning-the-bash-shell-unix-shell-
programming-3rd-edition-cameron-newham/
ebookultra.com
https://ebookultra.com/download/programming-in-objective-c-3rd-
edition-edition-stephen-g-kochan/
ebookultra.com
https://ebookultra.com/download/korn-shell-programming-by-example-1st-
edition-dennis-obrien/
ebookultra.com
https://ebookultra.com/download/the-linux-programming-interface-a-
linux-and-unix-system-programming-handbook-1st-edition-michael-
kerrisk/
ebookultra.com
UNIX Power Tools 3rd Edition Jerry Peek
https://ebookultra.com/download/unix-power-tools-3rd-edition-jerry-
peek/
ebookultra.com
https://ebookultra.com/download/unix-visual-quickstart-guide-3rd-ed-
edition-ray/
ebookultra.com
https://ebookultra.com/download/a-practical-guide-to-linux-commands-
editors-and-shell-programming-2nd-edition-mark-g-sobell/
ebookultra.com
https://ebookultra.com/download/linux-command-line-and-shell-
scripting-bible-3rd-edition-richard-blum/
ebookultra.com
https://ebookultra.com/download/nonlinear-programming-3rd-edition-
dimitri-bertsekas/
ebookultra.com
UNIX Shell programming 3rd Edition Stephen Kochan
Digital Instant Download
Author(s): Stephen Kochan, Patrick Wood
ISBN(s): 9780768663273, 076866327X
Edition: 3
File Details: PDF, 2.87 MB
Year: 2003
Language: english
Stephen G. Kochan
Patrick Wood
Unix Shell
Programming
Third Edition
All rights reserved. No part of this book shall be reproduced, stored in a Development Editor
retrieval system, or transmitted by any means, electronic, mechanical, Scott Meyers
photocopying, recording, or otherwise, without written permission
from the publisher. No patent liability is assumed with respect to the Managing Editor
use of the information contained herein. Although every precaution Charlotte Clapp
has been taken in the preparation of this book, the publisher and
author assume no responsibility for errors or omissions. Nor is any Copy Editor
liability assumed for damages resulting from the use of the information Geneil Breeze
contained herein.
Indexer
International Standard Book Number: 0-672-32490-3 Erika Millen
Library of Congress Catalog Card Number: 2002115932
Proofreader
Printed in the United States of America Jessica McCarty
Interior Designer
Trademarks Gary Adair
All terms mentioned in this book that are known to be trademarks or
service marks have been appropriately capitalized. Sams Publishing Cover Designer
cannot attest to the accuracy of this information. Use of a term in this Gary Adair
book should not be regarded as affecting the validity of any trademark
or service mark. Page Layout
Susan Geiselman
Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered
in quantity for bulk purchases or special sales. For more information,
please contact
International Sales
[email protected]
Contents at a Glance
1 Introduction .................................................................................................1
2 A Quick Review of the Basics .......................................................................5
3 What Is the Shell?.......................................................................................41
4 Tools of the Trade .......................................................................................53
5 And Away We Go........................................................................................99
6 Can I Quote You on That? .......................................................................115
7 Passing Arguments....................................................................................133
8 Decisions, Decisions .................................................................................145
9 ‘Round and ‘Round She Goes...................................................................183
10 Reading and Printing Data .......................................................................209
11 Your Environment ....................................................................................235
12 More on Parameters..................................................................................267
13 Loose Ends ................................................................................................287
14 Rolo Revisited ...........................................................................................307
15 Interactive and Nonstandard Shell Features ............................................325
A Shell Summary..........................................................................................363
B For More Information...............................................................................403
Index .........................................................................................................407
Table of Contents
1 Introduction 1
tr .................................................................................................................78
The -s Option ...................................................................................81
The –d Option ..................................................................................82
grep ............................................................................................................83
Regular Expressions and grep ..........................................................86
The -v Option ...................................................................................87
The -l Option ....................................................................................88
The -n Option ..................................................................................89
sort .............................................................................................................89
The -u Option ...................................................................................90
The -r Option ...................................................................................90
The -o Option ...................................................................................90
The -n Option ..................................................................................91
Skipping Fields .................................................................................92
The -t Option ...................................................................................92
Other Options ..................................................................................93
uniq ............................................................................................................94
The -d Option ...................................................................................95
Other Options ..................................................................................96
Exercises .....................................................................................................97
5 And Away We Go 99
Command Files ..........................................................................................99
Comments ......................................................................................102
Variables ...................................................................................................103
Displaying the Values of Variables .................................................104
The Null Value ................................................................................107
Filename Substitution and Variables .............................................108
The ${variable} Construct ..............................................................110
Built-in Integer Arithmetic ......................................................................110
Exercises ...................................................................................................112
Patrick Wood is the CTO of the New Jersey location of Electronics for Imaging. He
was a member of the technical staff at Bell Laboratories when he met Mr. Kochan in
1985. Together they founded Pipeline Associates, Inc., a Unix consulting firm, where
he was the Vice President. They coauthored Exploring the Unix System, Unix System
Security, Topics in C Programming, and Unix Shell Programming.
Dedication
As the reader of this book, you are our most important critic and commentator. We
value your opinion and want to know what we’re doing right, what we could do
better, what areas you’d like to see us publish in, and any other words of wisdom
you’re willing to pass our way.
You can email or write me directly to let me know what you did or didn’t like about
this book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book,
and that due to the high volume of mail I receive, I might not be able to reply to every
message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or email address. I will carefully review your comments and share
them with the author and editors who worked on the book.
Email: [email protected]
Reader Services
For more information about this book or others from Sams Publishing, visit our Web
site at www.samspublishing.com. Type the ISBN (excluding hyphens) or the title of the
book in the Search box to find the book you’re looking for.
1
Introduction
version of this standard as of this revision is the Shell and Utilities volume of IEEE
Std 1003.1-2001, also known as the POSIX standard. This shell is what we propose to
teach you about in this book.
The examples in this book were tested on both SunOS 5.7 running on a Sparcstation
Ultra-30 and on Silicon Graphics IRIX 6.5 running on an Octane; some examples
were also run on Red Hat Linux 7.1 and Cygwin. All examples, except some Bash
examples in Chapter 15, were run using the Korn shell, although many were also
run with Bash.
Many Unix systems are still around that have Bourne shell derivatives and utilities
not compliant with the POSIX standard. We’ll try to note this throughout the text
wherever possible; however, there are so many different versions of Unix from so
many different vendors that it’s simply not possible to mention every difference. If
you do have an older Unix system that doesn’t supply a POSIX-compliant shell,
there’s still hope. We’ll list resources at the end of this book where you can obtain
free copies of three different POSIX-compliant shells.
Chapter 3, “What Is the Shell?,” reveals what the shell really is. You’ll learn about
what happens every time you log in to the system, how the shell program gets
started, how it parses the command line, and how it executes other programs for
you. A key point made in Chapter 3 is that the shell is just a program; nothing more,
nothing less.
Chapter 4, “Tools of the Trade,” provides tutorials on tools useful in writing shell
programs. Covered in this chapter are cut, paste, sed, grep, sort, tr, and uniq.
Admittedly, the selection is subjective, but it does set the stage for programs that
we’ll develop throughout the remainder of the book. Also in Chapter 4 is a detailed
discussion of regular expressions, which are used by many Unix commands such as
sed, grep, and ed.
Chapters 5 through 10 teach you how to put the shell to work for writing programs.
You’ll learn how to write your own commands; use variables; write programs that
accept arguments; make decisions; use the shell’s for, while, and until looping
Introduction 3
commands; and use the read command to read data from the terminal or from a file.
Chapter 6, “Can I Quote You on That?,” is devoted entirely to a discussion on one of
the most intriguing (and often confusing) aspects of the shell: the way it interprets
quotes.
By this point in the book, all the basic programming constructs in the shell will have
been covered, and you will be able to write shell programs to solve your particular
problems.
Chapter 11, “Your Environment,” covers a topic of great importance for a real under-
standing of the way the shell operates: the environment. You’ll learn about local and
exported variables; subshells; special shell variables such as HOME, PATH, and CDPATH;
and how to set up your .profile file.
Chapter 12, “More on Parameters,” and Chapter 13, “Loose Ends,” tie up some loose
ends, and Chapter 14, “Rolo Revisited,” presents a final version of a phone directory
program called rolo that is developed throughout the book.
Chapter 15, “Interactive and Nonstandard Shell Features,” discusses features of the
shell that either are not formally part of the IEEE POSIX standard shell (but are avail-
able in most Unix and Linux shells) or are mainly used interactively instead of in
programs.
Appendix A, “Shell Summary,” summarizes the features of the IEEE POSIX standard
shell.
Appendix B, “For More Information,” lists references and resources, including the
Web sites where different shells can be downloaded.
The philosophy this book uses is to teach by example. Properly chosen examples do
a far superior job at illustrating how a particular feature is used than ten times as
many words. The old “A picture is worth…” adage seems to apply just as well to
examples. You are encouraged to type in each example and test it on your system,
for only by doing can you become adept at shell programming. You also should not
be afraid to experiment. Try changing commands in the program examples to see the
effect, or add different options or features to make the programs more useful or
robust.
At the end of most chapters you will find exercises. These can be used as assignments
in a classroom environment or by yourself to test your progress.
This book teaches the IEEE POSIX standard shell. Incompatibilities with earlier
Bourne shell versions are noted in the text, and these tend to be minor.
Acknowledgments from the first edition of this book: We’d like to thank Tony
Iannino and Dick Fritz for editing the manuscript. We’d also like to thank Juliann
Colvin for performing her usual wonders copy editing this book. Finally, we’d like to
4 CHAPTER 1 Introduction
thank Teri Zak, our acquisitions editor, and posthumously Maureen Connelly, our
production editor. These two were not only the best at what they did, but they also
made working with them a real pleasure.
For the first revised edition of this book, we’d like to acknowledge the contributions
made by Steven Levy and Ann Baker, and we’d like to also thank the following
people from Sams: Phil Kennedy, Wendy Ford, and Scott Arant.
For the second revised edition of this book, we’d like to thank Kathryn Purdum, our
acquisitions editor, Charlotte Clapp, our project editor, and Geneil Breeze, our copy
editor.
2 IN THIS CHAPTER
• Filename Substitution
• Standard Error
• Command Summary
Displaying the Date and Time:
The date Command • Exercises
The date command tells the system to print the date and
time:
$ date
Sat Jul 20 14:42:56 EDT 2002
$
date prints the day of the week, month, day, time (24-
hour clock, the system’s time zone), and year. Throughout
this book, whenever we use boldface type like this, it’s
to indicate what you, the user, types in. Normal face type
like this is used to indicate what the Unix system prints.
Italic type is used for comments in interactive sequences.
$ who
pat tty29 Jul 19 14:40
ruth tty37 Jul 19 10:54
steve tty25 Jul 19 15:52
$
Here, three users are logged in: pat, ruth, and steve. Along with each user id, the tty
number of that user and the day and time that user logged in is listed. The tty
number is a unique identification number the Unix system gives to each terminal or
network device that a user has logged into.
The who command also can be used to get information about yourself:
$ who am i
pat tty29 Jul 19 14:40
$
who and who am i are actually the same command: who. In the latter case, the am and
i are arguments to the who command.
You will notice from the preceding example that echo squeezes out extra blanks
between words. That’s because on a Unix system, the words are important; the
blanks are merely there to separate the words. Generally, the Unix system ignores
extra blanks (you’ll learn more about this in the next chapter).
contains data, text, program instructions, or just about anything else. Directories are
described later in this chapter. As its name implies, a special file has a special
meaning to the Unix system and is typically associated with some form of I/O.
A filename can be composed of just about any character directly available from the
keyboard (and even some that aren’t) provided that the total number of characters
contained in the name is not greater than 255. If more than 255 characters are speci-
fied, the Unix system simply ignores the extra characters.1
The Unix system provides many tools that make working with files easy. Here we’ll
review many basic file manipulation commands.
This output indicates that three files called READ_ME, names, and tmp are contained in
the current directory. (Note that the output of ls may vary from system to system.
For example, on many Unix systems ls produces multicolumn output when sending
its output to a terminal; on others, different colors may be used for different types of
files. You can always force single-column output with the –l option.)
$ cat names
Susan
Jeff
Henry
Allan
Ken
$
1
Modern Unix and Microsoft Windows systems support long filenames; however, some older Unix and
Windows systems only allow much shorter filenames.
8 CHAPTER 2 A Quick Review of the Basics
$ wc names
5 5 27 names
$
The wc command lists three numbers followed by the filename. The first number
represents the number of lines contained in the file (5), the second the number of
words contained in the file (in this case also 5), and the third the number of charac-
ters contained in the file (27).
Command Options
Most Unix commands allow the specification of options at the time a command is
executed. These options generally follow the same format:
-letter
That is, a command option is a minus sign followed immediately by a single letter.
For example, to count just the number of lines contained in a file, the option -l
(that’s the letter l) is given to the wc command:
$ wc -l names
5 names
$
Finally, the -w option can be used to count the number of words contained in the
file:
$ wc -w names
5 names
$
Some commands require that the options be listed before the filename arguments.
For example, sort names -r is acceptable, whereas wc names -l is not. Let’s general-
ize by saying that command options should precede filenames on the command line.
Working with Files 9
$ cp names saved_names
$
Execution of this command causes the file named names to be copied into a file
named saved_names. As with many Unix commands, the fact that a command
prompt was displayed after the cp command was typed indicates that the command
executed successfully.
$ mv saved_names hold_it
$
When executing an mv or cp command, the Unix system does not care whether the
file specified as the second argument already exists. If it does, the contents of the file
will be lost.2 For example, if a file called old_names exists, executing the command
cp names old_names
would copy the file names to old_names, destroying the previous contents of
old_names in the process. Similarly, the command
mv names old_names
would rename names to old_names, even if the file old_names existed prior to execu-
tion of the command.
2
Assuming that you have the proper permission to write to the file.
10 CHAPTER 2 A Quick Review of the Basics
$ rm hold_it
$
You can remove more than one file at a time with the rm command by simply speci-
fying all such files on the command line. For example, the following would remove
the three files wb, collect, and mon:
$ rm wb collect mon
$
documents programs
The file directory documents contains the files plan, dact, sys.A, new.hire, no.JSK,
and AMG.reply. The directory programs contains the files wb, collect, and mon. At
some point, you may decide to further categorize the files in a directory. This can be
done by creating subdirectories and then placing each file into the appropriate
subdirectory. For example, you might want to create subdirectories called memos,
proposals, and letters inside your documents directory, as shown in Figure 2.2.
documents contains the subdirectories memos, proposals, and letters. Each of these
directories in turn contains two files: memos contains plan and dact; proposals
contains sys.A and new.hire; and letters contains no.JSK and AMG.reply.
Although each file in a given directory must have a unique name, files contained in
different directories do not. So, for example, you could have a file in your programs
directory called dact, even though a file by that name also exists in the memos subdi-
rectory.
Working with Directories 11
documents programs
Although the location of users’ home directories can vary from one Unix version to
the next, and even one user to the next, let’s assume that your home directory is
called steve and that this directory is actually a subdirectory of a directory called
users. Therefore, if you had the directories documents and programs, the overall
directory structure would actually look something like Figure 2.3. A special directory
known as / (pronounced slash) is shown at the top of the directory tree. This direc-
tory is known as the root.
Whenever you are “inside” a particular directory (called your current working direc-
tory), the files contained within that directory are immediately accessible. If you
want to access a file from another directory, you can either first issue a command to
“change” to the appropriate directory and then access the particular file, or you can
specify the particular file by its pathname.
A pathname enables you to uniquely identify a particular file to the Unix system. In
the specification of a pathname, successive directories along the path are separated
by the slash character /. A pathname that begins with a slash character is known as a
full pathname because it specifies a complete path from the root. So, for example,
the pathname /users/steve identifies the directory steve contained under the direc-
tory users. Similarly, the pathname /users/steve/documents references the direc-
tory documents as contained in the directory steve under users. As a final example,
the pathname /users/steve/documents/letters/AMG.reply identifies the file
AMG.reply contained along the appropriate directory path.
To help reduce some of the typing that would otherwise be required, Unix provides
certain notational conveniences. Pathnames that do not begin with a slash character
are known as relative pathnames. The path is relative to your current working direc-
tory. For example, if you just logged in to the system and were placed into your
home directory /users/steve, you could directly reference the directory documents
12 CHAPTER 2 A Quick Review of the Basics
users
É
pat steve ruth
documents programs
By convention, the directory name .. always references the directory that is one
level higher. For example, after logging in and being placed into your home direc-
tory /users/steve, the pathname .. would reference the directory users. And if you
had issued the appropriate command to change your working directory to
documents/letters, the pathname .. would reference the documents directory,
../.. would reference the directory steve, and ../proposals/new.hire would refer-
ence the file new.hire contained in the proposals directory. Note that in this case,
as in most cases, there is usually more than one way to specify a path to a particular
file.
Another notational convention is the single period ., which always refers to the
current directory.
Now it’s time to examine commands designed for working with directories.
Recall the directory structure from Figure 2.3. The directory that you are placed in
after you log in to the system is called your home directory. You can assume from
Figure 2.3 that the home directory for the user steve is /users/steve. Therefore,
whenever steve logs in to the system, he will automatically be placed inside this
directory. To verify that this is the case, the pwd (print working directory) command
can be issued:
$ pwd
/users/steve
$
Working with Directories 13
The output from the command verifies that steve’s current working directory is
/users/steve.
Let’s assume that you just logged in to the system and were placed inside your home
directory, /users/steve. This is depicted by the arrow in Figure 2.4.
You know that two directories are directly “below” steve’s home directory:
documents and programs. In fact, this can be verified at the terminal by issuing the
ls command:
$ ls
documents
programs
$
The ls command lists the two directories documents and programs the same way it
listed other ordinary files in previous examples.
users
É
pat steve ruth
documents programs
To change your current working directory, issue the cd command, followed by the
name of the directory to change to:
$ cd documents
$
After executing this command, you will be placed inside the documents directory, as
depicted in Figure 2.5.
14 CHAPTER 2 A Quick Review of the Basics
users
É
pat steve ruth
documents programs
You can verify at the terminal that the working directory has been changed by
issuing the pwd command:
$ pwd
/users/steve/documents
$
The easiest way to get one level up in a directory is to issue the command
cd ..
because by convention .. always refers to the directory one level up (known as the
parent directory; see Figure 2.6).
$ cd ..
$ pwd
/users/steve
$
If you wanted to change to the letters directory, you could get there with a single
cd command by specifying the relative path documents/letters (see Figure 2.7):
$ cd documents/letters
$ pwd
/users/steve/documents/letters
$
Working with Directories 15
users
É
pat steve ruth
documents programs
FIGURE 2.6 cd ..
users
É
pat steve ruth
documents programs
You can get back up to the home directory by using a single cd command to go up
two directories as shown:
$ cd ../..
$ pwd
/users/steve
$
Or you can get back to the home directory using a full pathname rather than a rela-
tive one:
$ cd /users/steve
$ pwd
/users/steve
$
16 CHAPTER 2 A Quick Review of the Basics
Finally, there is a third way to get back to the home directory that is also the easiest.
Typing the command cd without an argument always places you back into your
home directory, no matter where you are in your directory path:
$ cd
$ pwd
/users/steve
$
$ cd
$ pwd
/users/steve
$
Now let’s take a look at the files in the current working directory:
$ ls
documents
programs
$
If you supply the name of one of these directories to the ls command, you can get a
list of the contents of that directory. So, you can find out what’s contained in the
documents directory simply by typing the command ls documents:
$ ls documents
letters
memos
proposals
$
If you specify a nondirectory file argument to the ls command, you simply get that
filename echoed back at the terminal:
$ ls documents/memos/plan
documents/memos/plan
$
$ ls –l
total 2
drwxr-xr-x 5 steve DP3725 80 Jun 25 13:27 documents
drwxr-xr-x 2 steve DP3725 96 Jun 25 13:31 programs
$
The first line of the display is a count of the total number of blocks (1,024 bytes) of
storage that the listed files use. Each successive line displayed by the ls -l
command contains detailed information about a file in the directory. The first char-
acter on each line tells whether the file is a directory. If the character is d, it is a
directory; if it is -, it is an ordinary file; finally, if it is b, c, l, or p, it is a special file.
The next nine characters on the line tell how every user on the system can access the
particular file. These access modes apply to the file’s owner (the first three characters),
other users in the same group as the file’s owner (the next three characters), and
finally to all other users on the system (the last three characters). They tell whether
the user can read from the file, write to the file, or execute the contents of the file.
The ls -l command lists the link count (see “Linking Files: The ln Command,” later
in this chapter), the owner of the file, the group owner of the file, how large the file
is (that is, how many characters are contained in it), and when the file was last
modified. The information displayed last on the line is the filename itself.
$ ls -l programs
total 4
-rwxr-xr-x 1 steve DP3725 358 Jun 25 13:31 collect
-rwxr-xr-x 1 steve DP3725 1219 Jun 25 13:31 mon
-rwxr-xr-x 1 steve DP3725 89 Jun 25 13:30 wb
$
The dash in the first column of each line indicates that the three files collect, mon,
and wb are ordinary files and not directories.
18 CHAPTER 2 A Quick Review of the Basics
$ mkdir misc
$
Now if you execute an ls command, you should get the new directory listed:
$ ls
documents
misc
programs
$
steve
Because the two files are contained in different directories, it is not even necessary
that they be given different names:
$ cp programs/wb misc/wb
$
Working with Directories 19
When the destination file has the same name as the source file (in a different direc-
tory, of course), it is necessary to specify only the destination directory as the second
argument:
$ cp programs/wb misc
$
When this command gets executed, the Unix system recognizes that the second
argument is the name of a directory and copies the source file into that directory.
The new file is given the same name as the source file. You can copy more than one
file into a directory by listing the files to be copied before the name of the destina-
tion directory. If you were currently in the programs directory, the command
would copy the three files wb, collect, and mon into the misc directory, under the
same names.
To copy a file from another directory into your current one and give it the same
name, use the fact that the current directory can always be referenced as ‘.’:
$ pwd
/users/steve/misc
$ cp ../programs/collect .
$
The preceding command copies the file collect from the directory ../programs into
the current directory (/users/steve/misc).
$ cd documents
$
Suppose that now you decide that the file plan contained in the memos directory is
really a proposal and not a memo. So you want to move it from the memos directory
into the proposals directory. The following would do the trick:
$ mv memos/plan proposals/plan
$
20 CHAPTER 2 A Quick Review of the Basics
As with the cp command, if the source file and destination file have the same name,
only the name of the destination directory need be supplied.
$ mv memos/plan proposals
$
Also like the cp command, a group of files can be simultaneously moved into a
directory by simply listing all files to be moved before the name of the destination
directory:
$ pwd
/users/steve/programs
$ mv wb collect mon ../misc
$
This would move the three files wb, collect, and mon into the directory misc. You
can also use the mv command to change the name of a directory. For example, the
following renames the directory programs to bin.
$ mv programs bin
$
ln from to
$ cp wb writeback
$
The drawback with this approach is that now twice as much disk space is being
consumed by the program. Furthermore, if steve ever changes wb, he may forget to
make a new copy of writeback, resulting in two different copies of what he thinks is
the same program.
Working with Directories 21
By linking the file wb to the new name, these problems are avoided:
$ ln wb writeback
$
Now instead of two copies of the file existing, only one exists with two different
names: wb and writeback. The two files have been logically linked by the Unix
system. As far as you’re concerned, it appears as though you have two different files.
Executing an ls command shows the two files separately:
$ ls
collect
mon
wb
writeback
$
$ ls -l
total 5
-rwxr-xr-x 1 steve DP3725 358 Jun 25 13:31 collect
-rwxr-xr-x 1 steve DP3725 1219 Jun 25 13:31 mon
-rwxr-xr-x 2 steve DP3725 89 Jun 25 13:30 wb
-rwxr-xr-x 2 steve DP3725 89 Jun 25 13:30 writeback
$
The number right before steve is 1 for collect and mon and 2 for wb and writeback.
This number is the number of links to a file, normally 1 for nonlinked, nondirectory
files. Because wb and writeback are linked, this number is 2 for these files. This
implies that you can link to a file more than once.
You can remove either of the two linked files at any time, and the other will not be
removed:
$ rm writeback
$ ls -l
total 4
-rwxr-xr-x 1 steve DP3725 358 Jun 25 13:31 collect
-rwxr-xr-x 1 steve DP3725 1219 Jun 25 13:31 mon
-rwxr-xr-x 1 steve DP3725 89 Jun 25 13:30 wb
$
Note that the number of links on wb went from 2 to 1 because one of its links was
removed.
22 CHAPTER 2 A Quick Review of the Basics
Most often, ln is used to link files between directories. For example, suppose that pat
wanted to have access to steve’s wb program. Instead of making a copy for himself
(subject to the same problems described previously) or including steve’s programs
directory in his PATH (described in detail in Chapter 11, “Your Environment”), he can
simply link to the file from his own program directory; for example:
$ pwd
/users/pat/bin pat’s program directory
$ ls -l
total 4
-rwxr-xr-x 1 pat DP3822 1358 Jan 15 11:01 lcat
-rwxr-xr-x 1 pat DP3822 504 Apr 21 18:30 xtr
$ ln /users/steve/wb . link wb to pat’s bin
$ ls -l
total 5
-rwxr-xr-x 1 pat DP3822 1358 Jan 15 11:01 lcat
-rwxr-xr-x 2 steve DP3725 89 Jun 25 13:30 wb
-rwxr-xr-x 1 pat DP3822 504 Apr 21 18:30 xtr
$
Note that steve is still listed as the owner of wb, even though the listing came from
pat’s directory. This makes sense, because really only one copy of the file exists—and
it’s owned by steve.
The only stipulation on linking files is that for ordinary links, the files to be linked
together must reside on the same file system. If they don’t, you’ll get an error from ln
when you try to link them. (To determine the different file systems on your system,
execute the df command. The first field on each line of output is the name of a file
system.)
To create links to files on different file systems (or perhaps on different networked
systems), you can use the -s option to the ln command. This creates a symbolic link.
Symbolic links behave a lot like regular links, except that the symbolic link points to
the original file; if the original file is removed, the symbolic link no longer works.
Let’s see how symbolic links work with the previous example:
$ rm wb
$ ls -l
total 4
-rwxr-xr-x 1 pat DP3822 1358 Jan 15 11:01 lcat
-rwxr-xr-x 1 pat DP3822 504 Apr 21 18:30 xtr
$ ln -s /users/steve/wb ./symwb Symbolic link to wb
$ ls -l
Working with Directories 23
total 5
-rwxr-xr-x 1 pat DP3822 1358 Jan 15 11:01 lcat
lrwxr-xr-x 1 pat DP3822 15 Jul 20 15:22 symwb -> /users/steve/wb
-rwxr-xr-x 1 pat DP3822 504 Apr 21 18:30 xtr
$
Note that pat is listed as the owner of symwb, and the file type is l, which indicates a
symbolic link. The size of the symbolic link is 15 (the file actually contains the string
/users/steve/wb), but if we attempt to access the contents of the file, we are
presented with the contents of its symbolic link, /users/steve/wb:
$ wc symwb
5 9 89 symwb
$
The -L option to the ls command can be used with the -l option to get a detailed
list of information on the file the symbolic link points to:
$ ls -Ll
total 5
-rwxr-xr-x 1 pat DP3822 1358 Jan 15 11:01 lcat
-rwxr-xr-x 2 steve DP3725 89 Jun 25 13:30 wb
-rwxr-xr-x 1 pat DP3822 504 Apr 21 18:30 xtr
$
Removing the file that a symbolic link points to invalidates the symbolic link
(because symbolic links are maintained as filenames), although the symbolic link
continues to stick around:
This type of file is called a dangling symbolic link and should be removed unless you
have a specific reason to keep it around (for example, if you intend to replace the
removed file).
24 CHAPTER 2 A Quick Review of the Basics
One last note before leaving this discussion: The ln command follows the same
general format as cp and mv, meaning that you can link a bunch of files at once into
a directory using the format
ln files directory
$ rmdir /users/steve/misc
$
Once again, the preceding command works only if no files are contained in the misc
directory; otherwise, the following happens:
$ rmdir /users/steve/misc
rmdir: /users/steve/misc not empty
$
If this happens and you still want to remove the misc directory, you would first have
to remove all the files contained in that directory before reissuing the rmdir
command.
As an alternate method for removing a directory and the files contained in it, you
can use the -r option to the rm command. The format is simple:
rm -r dir
where dir is the name of the directory that you want to remove. rm removes the indi-
cated directory and all files (including directories) in it.
Filename Substitution
The Asterisk
One powerful feature of the Unix system that is actually handled by the shell is file-
name substitution. Let’s say that your current directory has these files in it:
$ ls
chapt1
chapt2
Filename Substitution 25
chapt3
chapt4
$
Suppose that you want to print their contents at the terminal. Well, you could take
advantage of the fact that the cat command allows you to specify more than one
filename at a time. When this is done, the contents of the files are displayed one
after the other:
$ cat *
...
$
and get the same results. The shell automatically substitutes the names of all the files
in the current directory for the *. The same substitution occurs if you use * with the
echo command:
$ echo *
chapt1 chapt2 chapt3 chapt4
$
Here the * is again replaced with the names of all the files contained in the current
directory, and the echo command simply displays them at the terminal.
Any place that * appears on the command line, the shell performs its substitution:
$ echo * : *
chapt1 chapt2 chapt3 chapt4 : chapt1 chapt2 chapt3 chapt4
$
The * can also be used in combination with other characters to limit the filenames
that are substituted. For example, let’s say that in your current directory you have
not only chapt1 through chapt4 but also files a, b, and c:
$ ls
a
b
c
chapt1
chapt2
26 CHAPTER 2 A Quick Review of the Basics
chapt3
chapt4
$
To display the contents of just the files beginning with chapt, you can type in
$ cat chapt*
.
.
.
$
The chapt* matches any filename that begins with chapt. All such filenames
matched are substituted on the command line.
The * is not limited to the end of a filename; it can be used at the beginning or in
the middle as well:
$ echo *t1
chapt1
$ echo *t*
chapt1 chapt2 chapt3 chapt4
$ echo *x
*x
$
In the first echo, the *t1 specifies all filenames that end in the characters t1. In the
second echo, the first * matches everything up to a t and the second everything
after; thus, all filenames containing a t are printed. Because there are no files ending
with x, no substitution occurs in the last case. Therefore, the echo command simply
displays *x.
$ ls
a
aa
aax
alice
Filename Substitution 27
b
bb
c
cc
report1
report2
report3
$ echo ?
a b c
$ echo a?
aa
$ echo ??
aa bb cc
$ echo ??*
aa aax alice bb cc report1 report2 report3
$
In the preceding example, the ?? matches two characters, and the * matches zero or
more up to the end. The net effect is to match all filenames of two or more charac-
ters.
Another way to match a single character is to give a list of the characters to use in
the match inside square brackets [ ]. For example, [abc] matches one letter a, b, or
c. It’s similar to the ?, but it allows you to choose the characters that will be
matched. The specification [0-9] matches the characters 0 through 9. The only
restriction in specifying a range of characters is that the first character must be alpha-
betically less than the last character, so that [z-f] is not a valid range specification.
By mixing and matching ranges and characters in the list, you can perform some
complicated substitutions. For example, [a-np-z]* matches all files that start with
the letters a through n or p through z (or more simply stated, any lowercase letter
but o).
If the first character following the [ is a !, the sense of the match is inverted. That is,
any character is matched except those enclosed in the brackets. So
[!a-z]
matches any file that doesn’t end with the lowercase letter o.
Recall that executing the who command results in the display of the currently logged-
in users. More formally, the who command writes a list of the logged-in users to stan-
dard output. This is depicted in Figure 2.10.
If a sort command is executed without a filename argument, the command takes its
input from standard input. As with standard output, this is your terminal by default.
When entering data to a command from the terminal, the Ctrl and d keys (denoted
Ctrl+d in this text) must be simultaneously pressed after the last data item has been
entered. This tells the command that you have finished entering data. As an
example, let’s use the sort command to sort the following four names: Tony,
Exploring the Variety of Random
Documents with Different Content
wasps, whining for this, sticking their fingers into that, and thinking
they were helping with the jam-making. And suddenly my stepmother
turned round and caught little Polly with her mouth all black with
mulberry juice. And oh, the taking she was in! She caught her and
shook her, and ordered her to spit out anything she might have in her
mouth; and then, when she found out it was mulberries, she cooled
down all of a sudden and told Polly she must be a good girl and
never put anything in her mouth without asking first.
"Now, the jam was boiled in great copper cauldrons, and I noticed a
little pipkin simmering on the hearth, and I asked my stepmother
what it was. And she answered carelessly, 'Oh, it's some mulberry
jelly, sweetened with honey instead of sugar, for my old grandfather
at home.' And at the time I didn't give the matter another thought. But
the evening before my father died ... and I've never mentioned this to
a soul except my poor Peppercorn ... after supper he went and sat
out in the porch to smoke his pipe, leaving her and him to their own
doings in the kitchen; for she'd been brazen-faced enough, and my
father weak enough, actually to have the fellow living there in the
house. And my father was a queer man in that way—too proud to sit
where he wasn't wanted, even in his own kitchen. And I'd come out,
too, but I was hid from him by the corner of the house, for I had been
waiting for the sun to go down to pick flowers, to take to a sick
neighbour the next day. But I could hear him talking to his spaniel,
Ginger, who was like his shadow and followed him wherever he
went. I remember his words as clearly as if it had been yesterday:
'Poor old Ginger!' he said, 'I thought it would be me who would dig
your grave. But it seems not, Ginger, it seems not. Poor old lady, by
this time tomorrow I'll be as dumb as you are ... and you'll miss our
talks, poor Ginger.' And then Ginger gave a howl that made my
blood curdle, and I came running round the corner of the house and
asked father if he was ailing, and if I could fetch him anything. And
he laughed, but it was as different as chalk from cheese from the
way he laughed as a rule. For poor father was a frank-hearted, open-
handed man, and not one to hoard up bitterness any more than he
would hoard up money; but that laugh—the last I heard him give—
was as bitter as gall. And he said, 'Well, Ivy, my girl, would you like to
fetch me some peonies and marigolds and shepherd's thyme from a
hill where the Silent People have danced, and make me a salad from
them?' And seeing me looking surprised, he laughed again, and
said, 'No, no. I doubt there are no flowers growing this side of the
hills that could help your poor father. Come, give me a kiss—you've
always been a good girl.' Now, these are flowers that old wives use
in love potions, as I knew from my granny, who was very wise about
herbs and charms, but father had always laughed at her for it, and I
supposed he was fretting over my stepmother and Pugwalker, and
wondering if he could win her heart back to him.
"But that night he died, and it was then that I started wondering
about that jelly in the pipkin, for him, liking scum as he did, and
always having a saucer of it set aside for him, it wouldn't have been
difficult to have boiled up some poison for him without any danger of
other folks touching it. And Pugwalker knew all about herbs and such
like, and could have told her what to use. For it was as plain as print
that poor father knew he was going to die, and peonies make a good
purge; and I've often wondered since if it was as a purge that he
wanted these flowers. And that's all I know, and perhaps it isn't
much, but it's been enough to keep me awake many a night of my
life wondering what I should have done if I'd been older. For I was
only a little maid of ten at the time, with no one I could talk to, and as
frightened of my stepmother as a bird of a snake. If I'd been one of
the witnesses, I dare say it would have come out in court, but I was
too young for that."
"Perhaps we could get hold of Diggory Carp?"
"Diggory Carp?" she repeated in surprise. "But surely you heard
what happened to him? Ah, that was a sad story! You see, after he
was sent to gaol, there came three or four terrible lean years, one
after the other. And food was so dear, no one, of course, had any
money for buying fancy goods like baskets ... and the long and the
short of it was that when Diggory came out of gaol he found that his
wife and children had died of starvation. And it seemed to turn his
wits, and he came up to our farm, raging against my stepmother, and
vowing that someday he'd get his own back on her. And that night he
hanged himself from one of the trees in our orchard, and he was
found there dead the next morning."
"A sad story," said Master Nathaniel. "Well, we must leave him out of
our calculations. All you've told me is very interesting—very
interesting indeed. But there's still a great deal to be unravelled
before we get to the rope I'm looking for. One thing I don't
understand is Diggory Carp's story about the osiers. Was it a pure
fabrication of his?"
"Poor Diggory! He wasn't, of course, the sort of man whose word
one would be very ready to take, for he did deserve his ten years—
he was a born thief. But I don't think he would have had the wits to
invent all that. I expect the story he told was true enough about his
daughter selling the osiers, but that it was only for basket-making
that she wanted them. Guilt's a funny thing—like a smell, and one
often doesn't quite know where it comes from. I think Diggory's nose
was not mistaken when it smelt out guilt, but it led him to the wrong
clue. My father wasn't poisoned by osiers."
"Can you think what it was, then?"
She shook her head. "I've told you everything I know."
"I wish you knew something more definite," said Master Nathaniel a
little fretfully. "The Law dearly loves something it can touch—a blood-
stained knife and that sort of thing. And there's another matter that
puzzles me. Your father seems, on your showing, to have been a
very indulgent sort of husband, and to have kept his jealousy to
himself. What cause was there for the murder?"
"Ah! that I think I can explain to you," she cried. "You see, our farm
was very conveniently situated for ... well, for smuggling a certain
thing that we don't mention. It stands in a sort of hollow between the
marches and the west road, and smugglers like a friendly, quiet
place where they can run their goods. And my poor father, though he
may have sat like a dumb animal in pain when his young wife was
gallivanting with her lover, all the same, if he had found out what was
being stored in the granary, Pugwalker would have been kicked out
of the house, and she could have whistled for him till she was black
in the face. My father was easy-going enough in some ways, but
there were places in him as hard as nails, and no woman, be she
never so much of a fool (and, fair play to my stepmother, she was no
fool), can live with a man without finding out where these places
are."
"Oh, ho! So what Diggory Carp said about the contents of that sack
was true, was it?" And Master Nathaniel inwardly thanked his stars
that no harm had come to Ranulph during his stay in such a
dangerous place.
"Oh, it was true, and no mistake; and, child though I was at the time,
I cried through half one night with rage when they told me what the
hussy had said in court about my father using the stuff as manure
and her begging him not to! Begging him not to, indeed! I could have
told them a very different story. And it was Pugwalker that was at the
back of that business, and got the granary key from her, so they
could run their goods there. And shortly before my father died he got
wind of it—I know that from something I overheard. The room I
shared with my little brother Robin opened into theirs, and we always
kept the door ajar, because Robin was a timid child, and fancied he
couldn't go to sleep unless he heard my father snoring. Well, about a
week before my father died I heard him talking to her in a voice I'd
never known him to use to her before. He said he'd warned her twice
already that year, and that this was the last time. Up to that time he'd
held his head high, he said, because his hands were clean and all
his doings straight and fair, and now he warned her for the last time
that unless this business was put a stop to once and for all, he'd
have Pugwalker tarred and feathered, and make the neighbourhood
too hot for him to stay in it. And, I remember, I heard him hawking
and spitting, as if he'd rid himself of something foul. And he said that
the Gibbertys had always been respected, and that the farm, ever
since they had owned it, had helped to make the people of Dorimare
straight-limbed and clean-blooded, for it had sent fresh meat and
milk to market, and good grain to the miller, and sweet grapes to the
vintner, and that he would rather sell the farm than that poison and
filth should be sent out of his granary, to turn honest lads into idiots
gibbering at the moon. And then she started coaxing him, but she
spoke too low for me to catch the words. But she must have been
making him some promise, for he said gruffly, 'Well, see that it's
done, then, for I'm a man of my word.'
"And in not much more than a week after that he was dead—poor
father. And I count it a miracle that I ever grew up and am sitting here
now telling you all this. And a still greater one that little Robin grew
up to be a man, for he inherited the farm. But it was her own little girl
that died, and Robin grew up and married, and though he died in his
prime it was through a quinsy in his throat, and he always got on with
our stepmother, and wouldn't hear a word against her. And she has
brought up his little girl, for her mother died when she was born. But
I've never seen the lass, for there was never any love lost between
me and my stepmother, and I never went back to the old house after
I married."
She paused, and in her eyes was that wistful, tranced look that
always comes when one has been gazing at things that happened to
one long ago.
"I see, I see," said Master Nathaniel meditatively. "And Pugwalker?
Did you ever see him again till you recognized him in the streets of
Lud the other day?"
She shook her head. "No, he disappeared, as I told you, just before
the trial. Though I don't doubt that she knew his whereabouts and
heard from him—met him even; for she was always going out by
herself after nightfall. Well, well, I've told you everything I know—
though perhaps I'd have better held my tongue, for little good comes
of digging up the past."
Master Nathaniel said nothing; he was evidently pondering her story.
"Well," he said finally, "everything you have told me has been very
interesting—very interesting indeed. But whether it will lead to
anything definite is another matter. All the evidence is purely
circumstantial. However, I'm very grateful to you for having spoken to
me as freely as you've done. And if I find out anything further I'll let
you know. I shall be leaving Lud shortly, but I shall keep in touch with
you. And, under the circumstances, perhaps it would be prudent to
agree on some word or token by which you would recognize a
messenger as really coming from me, for the fellow you knew as
Pugwalker has not grown less cunning with advancing years—he's
full of guile, and let him once get wind of what we're after, he'd be up
to all sorts of tricks to make our plans miscarry. What shall the token
be?"
Then his eyes began to twinkle: "I've got it!" he cried. "Just to give
you a little lesson in swearing, which you say you dislike so much,
we'll make it a good round oath. You'll know a messenger comes
from me if he greets you with the words, By the Sun, Moon and Stars
and the Golden Apples of the West!"
And he rubbed his hands in delight, and shouted with laughter.
Master Nathaniel was a born tease.
"For shame, you saucy fellow!" dimpled Mistress Ivy. "You're as bad
as my poor Peppercorn. He used always...."
But even Master Nathaniel had had his fill of reminiscences. So he
cut her short with a hearty good-bye, and renewed thanks for all she
had told him.
But he turned back from the door to hold up his finger and say with
mock solemnity, "Remember, it's to be By the Sun, Moon and Stars
and the Golden Apples of the West!"
CHAPTER XIX
THE BERRIES OF MERCIFUL DEATH
Late into that night Master Nathaniel paced the floor of his pipe-
room, trying to pierce through the intervening medium of the dry
words of the Law and the vivider though less reliable one of Mistress
Ivy's memory, and reach that old rustic tragedy, as it had been before
the vultures of Time had left nothing of it but dry bones.
He felt convinced that Mistress Ivy's reconstruction was correct—as
far as it went. The farmer had been poisoned, though not by osiers.
But by what? And what had been the part played by Pugwalker, alias
Endymion Leer? It was, of course, gratifying to his vanity that his
instinctive identification of the two had been correct. But how
tantalizing it would be if this dead man's tale was to remain but a
vague whisper, too low to be heard by the ear of the Law!
On his table was the slipper that Master Ambrose had facetiously
suggested might be of use to him. He picked it up, and stared at it
absently. Ambrose had said the sight of it had made Endymion Leer
jump out of his skin, and that the reason was obvious. And yet those
purple strawberries did not look like fairy fruit. Master Nathaniel had
recently become but too familiar with the aspect of that fruit not to
recognize it instantly, whatever its variety. Though he had never seen
berries exactly like these, he was certain that they did not grow in
Fairyland.
He walked across to his bookcase and took out a big volume bound
in vellum. It was a very ancient illustrated herbal of the plants of
Dorimare.
At first he turned its pages somewhat listlessly, as if he did not really
expect to find anything of interest. Then suddenly he came on an
illustration, underneath which was written THE BERRIES OF
MERCIFUL DEATH. He gave a low whistle, and fetching the slipper
laid it beside the picture. The painted berries and the embroidered
ones were identical.
On the opposite page the berries were described in a style that a
literary expert would have recognized as belonging to the Duke
Aubrey period. The passage ran thus:—
THE BERRIES OF MERCIFUL DEATH
These berries are wine-coloured, and crawl along the
ground, and have the leaves of wild strawberries. They
ripen during the first quarter of the harvest moon, and are
only to be found in certain valleys of the West, and even
there they grow but sparsely; and, for the sake of birds
and children and other indiscreet lovers of fruit, it is well
that such is the case, for they are a deadly and insidious
poison, though very tardy in their action, often lying
dormant in the blood for many days. Then the poison
begins to speak in itchings of the skin, while the tongue,
as though in punishment for the lies it may have told,
becomes covered with black spots, so that it has the
appearance of the shards of a ladybird, and this is the only
warning to the victim that his end is approaching. For, if
evil things ever partake of the blessed virtues, then we
may say that this malign berry is mercifully cruel, in that it
spares its victims belchings and retchings and fiery
humours and racking colics. And, shortly before his end,
he is overtaken by a pleasant drowsiness, yielding to
which he falls into a peaceful sleep, which is his last. And
now I will give you a receipt, which, if you have no sin
upon your conscience, and are at peace with the living
and the dead, and have never killed a robin, nor robbed
an orphan, nor destroyed the nest of a dream, it may be
will prove an antidote to that poison—and may be it will
not. This, then, is the receipt: Take one pint of salad oil
and put it into a vial glass, but first wash it with rose-water,
and marygold flower water, the flowers being gathered
towards the West. Wash it till the oil comes white; then put
it into the glass, and then put thereto the buds of Peonies,
the flowers of Marygold and the flowers and tops of
Shepherd's Thyme. The Thyme must be gathered near
the side of a hill where the Fairies are said to dance.
Master Nathaniel laid down the book, and his eyes were more
frightened than triumphant. There was something sinister in the
silent language in which dead men told their tales—with sly malice
embroidering them on old maids' canvas work, hiding them away in
ancient books, written long before they were born; and why were his
ears so attuned to this dumb speech?
For him the old herbalist had been describing a murderer, subtle,
sinister, mitigating dark deeds with mercy—a murderer, the touch of
whose bloody hands was balm to the sick in body, and whose voice
could rock haunted minds to sleep. And, as well, in the light of what
he already knew, the old herbalist had told a story. A violent, cruel,
reckless woman had wished to rid herself of her enemy by the first
means that came to her hand—osiers, the sap of which produced an
agonizing, cruel death. But her discreet though murderous lover took
the osiers from her, and gave her instead the berries of merciful
death.
The herbalist had proved beyond the shadow of a doubt that the
villain of the story was Endymion Leer.
Yes, but how should he make the dead tell their tale loud enough to
reach the ear of the Law?
In any case, he must leave Lud, and that quickly.
Why should he not visit the scene of this old drama, the widow
Gibberty's farm? Perhaps he might there find witnesses who spoke a
language understood by all.