100% found this document useful (5 votes)
72 views

UNIX Shell programming 3rd Edition Stephen Kochan 2024 scribd download

programming

Uploaded by

sifayaalanya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
72 views

UNIX Shell programming 3rd Edition Stephen Kochan 2024 scribd download

programming

Uploaded by

sifayaalanya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Download the full version of the ebook at

https://ebookultra.com

UNIX Shell programming 3rd Edition Stephen


Kochan

https://ebookultra.com/download/unix-shell-
programming-3rd-edition-stephen-kochan/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Learning the bash Shell Unix Shell Programming 3rd Edition


Cameron Newham

https://ebookultra.com/download/learning-the-bash-shell-unix-shell-
programming-3rd-edition-cameron-newham/

ebookultra.com

Programming in Objective C 3rd Edition Edition Stephen G.


Kochan

https://ebookultra.com/download/programming-in-objective-c-3rd-
edition-edition-stephen-g-kochan/

ebookultra.com

Korn shell programming by example 1st Edition Dennis


O'Brien

https://ebookultra.com/download/korn-shell-programming-by-example-1st-
edition-dennis-obrien/

ebookultra.com

The Linux programming interface a Linux and UNIX system


programming handbook 1st Edition Michael Kerrisk

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

Unix Visual QuickStart Guide 3rd ed Edition Ray

https://ebookultra.com/download/unix-visual-quickstart-guide-3rd-ed-
edition-ray/

ebookultra.com

A Practical Guide to Linux Commands Editors and Shell


Programming 2nd Edition Mark G. Sobell

https://ebookultra.com/download/a-practical-guide-to-linux-commands-
editors-and-shell-programming-2nd-edition-mark-g-sobell/

ebookultra.com

Linux Command Line and Shell Scripting Bible 3rd Edition


Richard Blum

https://ebookultra.com/download/linux-command-line-and-shell-
scripting-bible-3rd-edition-richard-blum/

ebookultra.com

Nonlinear Programming 3rd Edition Dimitri Bertsekas

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

800 East 96th Street, Indianapolis, Indiana 46240


Unix Shell Programming, Third Edition Acquisitions Editor
Katie Purdum
Copyright © 2003 by Sams Publishing

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

First Printing: March 2003


Technical Editor
06 05 4 Michael Watson

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

Warning and Disclaimer


Every effort has been made to make this book as complete and as accu-
rate as possible, but no warranty or fitness is implied. The information
provided is on an “as is” basis. The authors and the publisher shall
have neither liability nor responsibility to any person or entity with
respect to any loss or damages arising from the information contained
in this book.

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

U.S. Corporate and Government Sales


1-800-382-3419
[email protected]

For sales outside of the U.S., 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

2 A Quick Review of the Basics 5


Some Basic Commands ...............................................................................5
Displaying the Date and Time:
The date Command .........................................................................5
Finding Out Who’s Logged In: The who Command ........................5
Echoing Characters: The echo Command .........................................6
Working with Files .......................................................................................6
Listing Files: The ls Command ..........................................................7
Displaying the Contents of a File: The cat Command .....................7
Counting the Number of Words in a File: The wc Command .........8
Command Options ............................................................................8
Making a Copy of a File: The cp Command .....................................9
Renaming a File: The mv Command .................................................9
Removing a File: The rm Command ...............................................10
Working with Directories ..........................................................................10
The Home Directory and Pathnames ..............................................11
Displaying Your Working Directory: The pwd Command ..............12
Changing Directories: The cd Command ........................................13
More on the ls Command ...............................................................16
Creating a Directory: The mkdir Command ...................................18
Copying a File from One Directory to Another ..............................18
Moving Files Between Directories ....................................................19
Linking Files: The ln Command ......................................................20
Removing a Directory: The rmdir Command .................................24
Filename Substitution ................................................................................24
The Asterisk ......................................................................................24
Matching Single Characters .............................................................26
Standard Input/Output and I/O Redirection ............................................28
Standard Input and Standard Output ..............................................28
Output Redirection ..........................................................................30
Input Redirection .............................................................................32
Pipes ...........................................................................................................33
Filters ................................................................................................35
Standard Error ............................................................................................35
More on Commands .................................................................................36
Typing More Than One Command on a Line ................................36
Sending a Command to the Background ........................................36
The ps Command .............................................................................37
Command Summary .................................................................................38
Exercises .....................................................................................................38

3 What Is the Shell? 41


The Kernel and the Utilities ......................................................................41
The Login Shell ..........................................................................................42
Typing Commands to the Shell ................................................................45
The Shell’s Responsibilities ........................................................................46
Program Execution ...........................................................................46
Variable and Filename Substitution .................................................48
I/O Redirection .................................................................................49
Pipeline Hookup ...............................................................................51
Environment Control .......................................................................51
Interpreted Programming Language ................................................52

4 Tools of the Trade 53


Regular Expressions ...................................................................................53
Matching Any Character: The Period (.) .........................................54
Matching the Beginning of the Line: The Caret (^) ........................55
Matching the End of the Line: The Dollar Sign ($) ........................55
Matching a Choice of Characters: The [...] Construct ....................57
Matching Zero or More Characters: The Asterisk (*) .......................59
Matching a Precise Number of Characters: \{...\} ...........................62
Saving Matched Characters: \(...\) ..................................................64
cut ..............................................................................................................67
The -d and -f Options ......................................................................69
paste ...........................................................................................................72
The -d Option ...................................................................................73
The -s Option ...................................................................................74
sed ..............................................................................................................74
The -n Option ..................................................................................76
Deleting Lines ...................................................................................77
vi UNIX SHELL PROGRAMMING

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

6 Can I Quote You on That? 115


The Single Quote .....................................................................................115
The Double Quote ...................................................................................119
The Backslash ..........................................................................................121
Using the Backslash for Continuing Lines ....................................122
The Backslash Inside Double Quotes .............................................123
Contents vii

Command Substitution ...........................................................................124


The Back Quote ..............................................................................124
The $(...) Construct ........................................................................125
The expr Command .......................................................................129
Exercises ...................................................................................................131

7 Passing Arguments 133


The $# Variable ..............................................................................134
The $* Variable ...............................................................................135
A Program to Look Up Someone in the Phone Book ....................136
A Program to Add Someone to the Phone Book ...........................138
A Program to Remove Someone from the Phone Book ................139
${n} .................................................................................................141
The shift Command ................................................................................141
Exercises ...................................................................................................143

8 Decisions, Decisions 145


Exit Status ................................................................................................145
The $? Variable ...............................................................................146
The test Command ..................................................................................149
String Operators .............................................................................150
An Alternative Format for test .......................................................154
Integer Operators ...........................................................................155
File Operators .................................................................................157
The Logical Negation Operator ! ...................................................158
The Logical AND Operator –a ........................................................158
Parentheses .....................................................................................159
The Logical OR Operator –o ...........................................................159
The else Construct ...................................................................................160
The exit Command .................................................................................162
A Second Look at the rem Program ...............................................163
The elif Construct ....................................................................................164
Yet Another Version of rem ...........................................................167
The case Command .................................................................................169
Special Pattern Matching Characters .............................................171
The -x Option for Debugging Programs ........................................173
Back to the case ..............................................................................175
The Null Command : ..............................................................................177
The && and || Constructs ........................................................................177
Exercises ...................................................................................................180
viii UNIX SHELL PROGRAMMING

9 ’Round and ’Round She Goes 183


The for Command ...................................................................................183
The $@ Variable ..............................................................................187
The for Without the List ................................................................188
The while Command .....................................................................189
The until Command ................................................................................191
More on Loops .........................................................................................196
Breaking Out of a Loop ..................................................................196
Skipping the Remaining Commands in a Loop ............................198
Executing a Loop in the Background ............................................199
I/O Redirection on a Loop .............................................................199
Piping Data Into and Out of a Loop ..............................................200
Typing a Loop on One Line ...........................................................200
The getopts Command ............................................................................201
Exercises ...................................................................................................205

10 Reading and Printing Data 209


The read Command .................................................................................209
A Program to Copy Files ................................................................209
Special echo Escape Characters ......................................................212
An Improved Version of mycp .......................................................212
A Final Version of mycp .................................................................214
A Menu-Driven Phone Program ....................................................219
The $$ Variable and Temporary Files ............................................224
The Exit Status from read ...............................................................225
The printf Command ..............................................................................228
Exercises ...................................................................................................233

11 Your Environment 235


Local Variables .........................................................................................235
Subshells .........................................................................................236
Exported Variables ...................................................................................237
export -p .........................................................................................241
PS1 and PS2 .............................................................................................241
HOME, James ...........................................................................................242
Your PATH ................................................................................................243
Your Current Directory ............................................................................251
CDPATH ..........................................................................................252
Contents ix

More on Subshells ...................................................................................253


The . Command .............................................................................254
The exec Command .......................................................................257
The (...) and { ...; } Constructs ........................................................258
Another Way to Pass Variables to a Subshell .................................262
Your .profile File ......................................................................................262
The TERM Variable ..................................................................................264
The TZ Variable ........................................................................................264
Exercises ...................................................................................................265

12 More on Parameters 267


Parameter Substitution ............................................................................267
${parameter} ...................................................................................268
${parameter:-value} ........................................................................268
${parameter:=value} ........................................................................269
${parameter:?value} ........................................................................270
${parameter:+value} ........................................................................270
Pattern Matching Constructs .........................................................270
${#variable} .....................................................................................273
The $0 Variable ........................................................................................273
The set Command ...................................................................................274
The -x Option .................................................................................274
set with No Arguments ..................................................................275
Using set to Reassign Positional Parameters ..................................276
The -- Option ..................................................................................277
Other Options to set ......................................................................280
The IFS Variable .......................................................................................280
The readonly Command .........................................................................283
The unset Command ...............................................................................284
Exercises ...................................................................................................284

13 Loose Ends 287


The eval Command .................................................................................287
The wait Command .................................................................................289
The $! Variable ...............................................................................290
The trap Command .................................................................................290
trap with No Arguments ................................................................292
Ignoring Signals ..............................................................................292
Resetting Traps ...............................................................................293
x UNIX SHELL PROGRAMMING

More on I/O .............................................................................................293


<&- and >&- ....................................................................................295
Inline Input Redirection ................................................................295
Shell Archives .................................................................................297
Functions .................................................................................................301
Removing a Function Definition ...................................................304
The return Command ....................................................................304
The type Command ................................................................................305
Exercises ...................................................................................................305

14 Rolo Revisited 307


Design Considerations ............................................................................307
rolo ...........................................................................................................308
add ...........................................................................................................311
lu ...............................................................................................................312
display ......................................................................................................313
rem ...........................................................................................................314
change ......................................................................................................316
listall ........................................................................................................318
Sample Output .........................................................................................319
Exercises ...................................................................................................323

15 Interactive and Nonstandard Shell Features 325


Getting the Right Shell ............................................................................326
The ENV File ............................................................................................326
Command-Line Editing ...........................................................................327
Command History ...................................................................................327
The vi Line Edit Mode .............................................................................328
Accessing Commands from Your History ......................................330
The Line Edit Mode .................................................................................332
Accessing Commands from Your History ......................................334
Other Ways to Access Your History .........................................................336
The history Command ...................................................................336
The fc Command ...........................................................................337
The r Command .............................................................................338
Functions .................................................................................................339
Local Variables ................................................................................339
Automatically Loaded Functions ...................................................340
Contents xi

Integer Arithmetic ...................................................................................340


Integer Types ..................................................................................341
Numbers in Different Bases ...........................................................342
The alias Command ................................................................................343
Removing Aliases ...........................................................................346
Arrays .......................................................................................................346
Job Control ..............................................................................................352
Stopped Jobs and the fg and bg Commands .................................353
The Restricted Shell rsh ...........................................................................355
Miscellaneous Features ............................................................................357
Other Features of the cd Command ..............................................357
Tilde Substitution ...........................................................................357
Order of Search ...............................................................................359
Compatibility Summary ..........................................................................359
Exercises ...................................................................................................360

A Shell Summary 363


Startup ......................................................................................................363
Commands ..............................................................................................363
Comments ...............................................................................................364
Parameters and Variables .........................................................................364
Shell Variables ................................................................................364
Positional Parameters .....................................................................365
Special Parameters ..........................................................................365
Parameter Substitution ...................................................................366
Command Re-entry .................................................................................367
The fc Command ...........................................................................368
vi Line Edit Mode ...........................................................................368
Quoting ....................................................................................................370
Tilde Substitution ...........................................................................371
Arithmetic Expressions ...................................................................371
Filename Substitution ..............................................................................372
I/O Redirection ........................................................................................373
Exported Variables and Subshell Execution ............................................373
The (...) Construct ..........................................................................374
The { ...; } Construct .......................................................................374
More on Shell Variables .................................................................374
Functions .................................................................................................374
xii UNIX SHELL PROGRAMMING

Job Control ..............................................................................................375


Shell Jobs ........................................................................................375
Stopping Jobs ..................................................................................375
Command Summary ...............................................................................376
The : Command ............................................................................376
The . Command ............................................................................376
The alias Command .....................................................................377
The bg Command ..........................................................................377
The break Command .....................................................................377
The case Command .......................................................................378
The cd Command ..........................................................................379
The continue command ................................................................380
The echo Command .......................................................................380
The eval Command .......................................................................381
The exec Command .......................................................................381
The exit Command .......................................................................382
The export Command ...................................................................382
The false Command .....................................................................383
The fc Command ..........................................................................383
The fg Command ..........................................................................384
The for Command .........................................................................384
The getopts Command .................................................................385
The hash Command .......................................................................387
The if Command ..........................................................................387
The jobs Command .......................................................................390
The kill Command .......................................................................390
The newgrp Command ...................................................................391
The pwd Command .........................................................................391
The read Command .......................................................................392
The readonly Command ...............................................................392
The return Command ...................................................................393
The set Command .........................................................................393
The shift Command .....................................................................395
The test Command .......................................................................396
The times Command .....................................................................398
The trap Command .......................................................................398
The true Command .......................................................................399
The type Command .......................................................................399
The umask Command .....................................................................400
Contents xiii

The unalias Command .................................................................400


The unset Command .....................................................................400
The until Command .....................................................................400
The wait Command .......................................................................401
The while Command .....................................................................402

B For More Information 403


Online Documentation ...........................................................................403
Documentation on the Web ...................................................................403
Books ........................................................................................................404
O’Reilly & Associates ......................................................................404
Sams and Que .................................................................................405
Other Publishers .............................................................................406
About the Authors

Stephen G. Kochan is the owner of TechFitness, a technology-based fitness


company. Prior to that, he was president and CEO of Pipeline Associates, a company
specializing in color printing software. Mr. Kochan is the author of several best-
selling books on Unix and C programming, including the best-selling Programming in
C. He also acted as Series Editor for the Hayden Unix System Library.

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

To my father, Harry Wood


—Patrick Wood

To Gregory, Linda, and Julia for giving meaning to my life


—Stephen G. Kochan
We Want to Hear from You!

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]

Mail: Mark Taber


Associate Publisher
Sams Publishing
800 East 96th Street
Indianapolis, IN 46240 USA

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

It’s no secret that the Unix operating system has emerged


as a standard operating system. For programmers who have
been using Unix for many years now, this came as no
surprise: The Unix system provides an elegant and efficient
environment for program development. After all, this is
what Dennis Ritchie and Ken Thompson strived for when
they developed Unix at Bell Laboratories in the late 1960s.
One of the strongest features of the Unix system is its wide
collection of programs. More than 200 basic commands
are distributed with the standard operating system. These
commands (also known as tools) do everything from
counting the number of lines in a file, to sending elec-
tronic mail, to displaying a calendar for any desired year.

But the real strength of the Unix system comes not


entirely from this large collection of commands but also
from the elegance and ease with which these commands
can be combined to perform far more sophisticated func-
tions.
To further this end, and also to provide a consistent buffer
between the user and the guts of the Unix system (the
kernel), the shell was developed. The shell is simply a
program that reads in the commands you type and
converts them into a form more readily understood by the
Unix system. It also includes some fundamental program-
ming constructs that let you make decisions, loop, and
store values in variables.
The standard shell distributed with Unix and Linux
systems derives from AT&T’s distribution, which evolved
from a version originally written by Stephen Bourne at Bell
Labs. Since then, the IEEE created standards based on the
Bourne shell and the other more recent shells. The current
2 CHAPTER 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.

Because the shell offers an interpreted programming language, programs can be


written, modified, and debugged quickly and easily. We turn to the shell as our first
choice of programming language. After you become adept at programming in the
shell, you too may turn to it first.
This book assumes that you are familiar with the fundamentals of the Unix system;
that is, that you know how to log in; how to create files, edit them, and remove
them; and how to work with directories. But in case you haven’t used the Unix
system for a while, we’ll examine the basics in Chapter 2, “A Quick Review of the
Basics.” Besides the basic file commands, filename substitution, I/O redirection, and
pipes are also reviewed in Chapter 2.

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

• Some Basic Commands


A Quick Review of the • Working with Files

Basics • Working with Directories

• Filename Substitution

• Standard Input/Output and


This chapter provides a review of the Unix system, I/O Redirection
including the file system, basic commands, filename
substitution, I/O redirection, and pipes. • Pipes

• Standard Error

Some Basic Commands • More on Commands

• 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.

Every Unix command is ended with the pressing of the


Enter key. Enter says that you are finished typing things in
and are ready for the Unix system to do its thing.

Finding Out Who’s Logged In: The who


Command
The who command can be used to get information about
all users currently logged in to the system:
6 CHAPTER 2 A Quick Review of the Basics

$ 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.

Echoing Characters: The echo Command


The echo command prints (or echoes) at the terminal whatever else you happen to
type on the line (there are some exceptions to this that you’ll learn about later):

$ echo this is a test


this is a test
$ echo why not print out a longer line with echo?
why not print out a longer line with echo?
$ echo
A blank line is displayed
$ echo one two three four five
one two three four five
$

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).

Working with Files


The Unix system recognizes only three basic types of files: ordinary files, directory
files, and special files. An ordinary file is just that: any file on the system that
Working with Files 7

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.

Listing Files: The ls Command


To see what files you have stored in your directory, you can type the ls command:
$ ls
READ_ME
names
tmp
$

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.)

Displaying the Contents of a File: The cat Command


You can examine the contents of a file by using the cat command. The argument to
cat is the name of the file whose contents you want to examine.

$ 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

Counting the Number of Words in a File: The wc Command


With the wc command, you can get a count of the total number of lines, words, and
characters of information contained in a file. Once again, the name of the file is
needed as the argument to this command:

$ 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
$

To count just the number of characters in a file, the -c option is specified:


$ wc -c names
27 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

Making a Copy of a File: The cp Command


To make a copy of a file, the cp command is used. The first argument to the
command is the name of the file to be copied (known as the source file), and
the second argument is the name of the file to place the copy into (known as the
destination file). You can make a copy of the file names and call it saved_names as
follows:

$ 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.

Renaming a File: The mv Command


A file can be renamed with the mv command. The arguments to the mv command
follow the same format as the cp command. The first argument is the name of the
file to be renamed, and the second argument is the new name. So, to change the
name of the file saved_names to hold_it, for example, the following command
would do the trick:

$ 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

Removing a File: The rm Command


To remove a file from the system, you use the rm command. The argument to rm is
simply the name of the file to be removed:

$ 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
$

Working with Directories


Suppose that you had a set of files consisting of various memos, proposals, and
letters. Further suppose that you had a set of files that were computer programs. It
would seem logical to group this first set of files into a directory called documents,
for example, and the latter set of files into a directory called programs. Figure 2.1
illustrates such a directory organization.

documents programs

plan dact sys.A new.hire no.JSK AMG.reply wb collect mon

FIGURE 2.1 Example directory structure.

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

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.2 Directories containing subdirectories.

The Home Directory and Pathnames


The Unix system always associates each user of the system with a particular direc-
tory. When you log in to the system, you are placed automatically into a directory
called your home directory.

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

simply by typing documents. Similarly, the relative pathname programs/mon could be


typed to access the file mon contained inside your programs directory.

users

É
pat steve ruth

documents programs

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.3 Hierarchical directory structure.

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.

Displaying Your Working Directory: The pwd Command


The pwd command is used to help you “get your bearings” by telling you the name
of your current working directory.

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.

Changing Directories: The cd Command


You can change your current working directory by using the cd command. This
command takes as its argument the name of the directory you want to change to.

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

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.4 Current working directory is steve.

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

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.5 cd documents.

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

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.6 cd ..

users

É
pat steve ruth

documents programs

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.7 cd documents/letters.

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
$

More on the ls Command


When you type the ls command, the files contained in the current working direc-
tory are listed. But you can also use ls to obtain a list of files in other directories by
supplying an argument to the command. First let’s get back to your home directory:

$ 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
$

To take a look at the subdirectory memos, you follow a similar procedure:


$ ls documents/memos
dact
plan
$
Working with Directories 17

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
$

An option to the ls command enables you to determine whether a particular file is a


directory, among other things. The -l option (the letter l) provides a more detailed
description of the files in a directory. If you were currently in steve’s home directory
as indicated in Figure 2.6, the following would illustrate the effect of supplying the
-l option to the ls command:

$ 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

Creating a Directory: The mkdir Command


To create a directory, the mkdir command must be used. The argument to this
command is simply the name of the directory you want to make. For example,
assume that you are still working with the directory structure depicted in Figure 2.7
and that you want to create a new directory called misc on the same level as the direc-
tories documents and programs. If you were currently in your home directory, typing
the command mkdir misc would achieve the desired effect:

$ mkdir misc
$

Now if you execute an ls command, you should get the new directory listed:

$ ls
documents
misc
programs
$

The directory structure now appears as shown in Figure 2.8.

steve

documents programs misc

memos proposals letters wb collect mon

plan dact sys.A new.hire no.JSK AMG.reply

FIGURE 2.8 Directory structure with newly created misc directory.

Copying a File from One Directory to Another


The cp command can be used to copy a file from one directory into another. For
example, you can copy the file wb from the programs directory into a file called wbx
in the misc directory as follows:
$ cp programs/wb misc/wbx
$

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

$ cp wb collect mon ../misc


$

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).

Moving Files Between Directories


You recall that the mv command can be used to rename a file. However, when the
two arguments to this command reference different directories, the file is actually
moved from the first directory into the second directory. For example, first change
from the home directory to the documents directory:

$ 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
$

Linking Files: The ln Command


In simplest terms, the ln command provides an easy way for you to give more than
one name to a file. The general form of the command is

ln from to

This links the file from to the file to.


Recall the structure of steve’s programs directory from Figure 2.8. In that directory,
he has stored a program called wb. Suppose that he decides that he’d also like to call
the program writeback. The most obvious thing to do would be to simply create a
copy of wb called writeback:

$ 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
$

Look what happens when you execute an ls -l:

$ 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:

$ rm /users/steve/wb Assume pat can remove this file


$ ls -l
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 wb -> /users/steve/wb
-rwxr-xr-x 1 pat DP3822 504 Apr 21 18:30 xtr
$ wc wb
Cannot open wb: No such file or directory
$

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

Removing a Directory: The rmdir Command


You can remove a directory with the rmdir command. The stipulation involved in
removing a directory is that no files be contained in the directory. If there are files in
the directory when rmdir is executed, you will not be allowed to remove the direc-
tory. To remove the directory misc that you created earlier, the following could be
used:

$ 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 chapt1 chapt2 chapt3 chapt4


...
$

But you can also type in

$ 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.

Matching Single Characters


The asterisk (*) matches zero or more characters, meaning that x* matches the file x
as well as x1, x2, xabc, and so on. The question mark (?) matches exactly one charac-
ter. So cat ? prints all files with one-character names, just as cat x? prints all files
with two-character names beginning with 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 character except a lowercase letter, and


*[!o]

matches any file that doesn’t end with the lowercase letter o.

Table 2.1 gives a few more examples of filename substitution.


28 CHAPTER 2 A Quick Review of the Basics

TABLE 2.1 Filename Substitution Examples


Command Description
echo a* Print the names of the files beginning with a
cat *.c Print all files ending in .c
rm *.* Remove all files containing a period
ls x* List the names of all files beginning with x
rm * Remove all files in the current directory (Note: Be careful when you use this.)
echo a*b Print the names of all files beginning with a and ending with b
cp ../programs/* . Copy all files from ../programs into the current directory
ls [a-z]*[!0-9] List files that begin with a lowercase letter and don’t end with a digit

Standard Input/Output and I/O Redirection


Standard Input and Standard Output
Most Unix system commands take input from your terminal and send the resulting
output back to your terminal. A command normally reads its input from a place
called standard input, which happens to be your terminal by default. Similarly, a
command normally writes its output to standard output, which is also your terminal
by default. This concept is depicted in Figure 2.9.

standard input standard output


command

FIGURE 2.9 Typical Unix command.

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.

The next morning he ordered a horse to be saddled, packed a few


necessaries in a knapsack, and then he told Dame Marigold that, for
the present, he could not stay in Lud. "As for you," he said, "you had
better move to Polydore's. For the moment I'm the most unpopular
man in town, and it would be just as well that they should think of
you as Vigil's sister rather than as Chanticleer's wife."
Dame Marigold's face was very pale that morning and her eyes were
very bright. "Nothing would induce me," she said in a low voice,
"ever again to cross the threshold of Polydore's house. I shall never
forgive him for the way he has treated you. No, I shall stay here—in
your house. And," she added, with a little scornful laugh, "you
needn't be anxious about me. I've never yet met a member of the
lower classes that was a match for one of ourselves—they fall to
heel as readily as a dog. I'm not a bit afraid of the mob, or anything
they could do to me."
Master Nathaniel chuckled. "By the Sun, Moon and Stars!" he cried
proudly, "you're a chip off the old block, Marigold!"
"Well, don't stay too long away, Nat," she said, "or else when you
come back you'll find that I've gone mad like everybody else, and am
dancing as wildly as Mother Tibbs, and singing songs about Duke
Aubrey!" and she smiled her charming crooked smile.
Then he went up to say good-bye to old Hempie.
"Well, Hempie," he cried gaily. "Lud's getting too hot for me. So I'm
off with a knapsack on my back to seek my fortune, like the youngest
son in your old stories. Will you wish me luck?"
There were tears in the old woman's eyes as she looked at him, and
then she smiled.
"Why, Master Nat," she cried, "I don't believe you've felt so light-
hearted since you were a boy! But these are strange times when a
Chanticleer is chased out of Lud-in-the-Mist! And wouldn't I just like
to give those Vigils and the rest of them a bit of my mind!" and her
old eyes flashed. "But don't you ever get downhearted, Master Nat,
and don't ever forget that there have always been Chanticleers in
Lud-in-the-Mist, and that there always will be! But it beats me how
you're to manage with only three pairs of stockings, and no one to
mend them."
"Well, Hempie," he laughed, "they say the Fairies are wonderfully
neat-fingered, and, who knows, perhaps in my wanderings I may fall
in with a fairy housewife who will darn my stockings for me," and he
brought out the forbidden word as lightly and easily as if it had been
one in daily use.
About an hour after Master Nathaniel had ridden away Luke Hempen
arrived at the house, wild-eyed, dishevelled, and with very startling
news. But it was impossible to communicate it to Master Nathaniel,
as he had left without telling anyone his destination.
CHAPTER XX
WATCHING THE COWS
In the interval between his two letters—the one to Hempie, and the
one to Master Nathaniel—Luke decided that his suspicions had been
groundless, for the days at the farm were buzzing by with a soothing
hum like that of summer insects, and Ranulph was growing gay and
sunburned.
Then towards autumn Ranulph had begun to wilt, and finally Luke
overheard the strange conversation he had reported in his letter to
Master Nathaniel, and once again the farm grew hateful to him, and
he followed Ranulph as if he were his shadow and counted the hours
for the order to come from Master Nathaniel bidding them return to
Lud.
Perhaps you may remember that on his first evening at the farm
Ranulph had wanted to join the children who watched the widow's
cows at night, but it had evidently been nothing but a passing whim,
for he did not express the wish again.
And then at the end of June—as a matter of fact it was Midsummer
day—the widow had asked him if he would not like that night to join
the little herdsmen. But towards evening had come a steady downfall
of rain, and the plan had fallen through.
It was not alluded to again till the end of October, three or four days
before Master Nathaniel left Lud-in-the-Mist. It had been a very mild
autumn in the West and the nights were fresh rather than cold, and
when, that evening, the little boys came knocking at the door for their
bread and cheese, the widow began to jeer at Ranulph, in a hearty
jovial way, for being town-bred and never having spent a night under
the sky.
"Why don't you go tonight with the little herdsmen? You wanted to
when you first came here, and the Doctor said it would do you no
harm."
Now Luke was feeling particularly downcast that night; no answer
had come from Master Nathaniel to his letter, though it was well over
a week since he had written. He felt forlorn and abandoned, with a
weight of responsibility too heavy for his shoulders, and he was
certainly not going to add to that weight by allowing Ranulph to run
the risk of catching a bad chill. And as well, any suggestion that
came from the widow was greeted by him with suspicion.
"Master Ranulph," he cried excitedly, "I can't let you go. His Worship
and my old auntie wouldn't like it, what with the nights getting damp
and all. No, Master Ranulph, be a good little chap and go to your bed
as usual."
As he was speaking he caught Hazel's eye, and she gave him an
almost imperceptible nod of approval.
But the widow cried, with a loud scornful laugh, in which Ranulph
shrilly joined: "Too damp, indeed! When we haven't had so much as
a drop of rain these four weeks! Don't let yourself be coddled, Master
Ranulph. Young Hempen's nothing but an old maid in breeches. He's
as bad as my Hazel. I've always said that if she doesn't die an old
maid, it isn't that she wasn't born one!"
Hazel said nothing, but she fixed her eyes beseechingly on Luke.
But Ranulph, I fear, was a very spoiled little boy, and, into the
bargain, he dearly loved annoying Luke; so he jumped up and down,
shouting, "Old maid Hempen! Old maid Hempen! I'm going—so
there!"
"That's right, little master!" laughed the widow. "You'll be a man
before I am."
And the three little herdsmen, who had been watching this scene
with shy amusement, grinned from ear to ear.
"Do as you like, then," said Luke sullenly, "but I'm coming too. And,
anyway, you must wrap up as warmly as you can."
So they went upstairs to put on their boots and mufflers.
When they came down Hazel, with compressed lips and a little frown
knitting her brows, gave them their rations of cheese and bread and
honey, and then, with a furtive glance in the direction of the widow,
who was standing with her back turned, talking to the little herdsmen,
she slipped two sprigs of fennel into Luke's button-hole. "Try and get
Master Ranulph to wear one of them," she whispered.
This was not reassuring. But how is an undergardener, not yet
turned eighteen, to curb the spoiled son of his master—especially
when a strong-willed, elderly woman throws her weight into the other
scale?
"Well, well," said the widow, bustling up, "it's high time you were off.
You have a full three miles walk before you."
"Yes, yes, let's be off!" cried Ranulph excitedly; Luke felt it would be
useless to protest further, so the little cavalcade dived into the
moonlit night.
The world was looking very beautiful. At one end of the scale of
darkness stood the pines, like rich black shadows; at the other end
of the scale were the farm buildings, like white glimmering human
masks. And in between these two extremes were all the various
degrees of greyness—the shimmer of the Dapple that was more
white than grey, and all the different trees—plane-trees, liege-oaks,
olives—and one could almost recognize their foliage by their lesser
or greater degree of density.
On they trudged in silence, up the course of the Dapple—Luke too
anxious and aggrieved to talk, Ranulph buried too deep in dreams,
and the little herdsmen far too shy. There were nothing but rough
cattle paths in the valley—heavy enough going by day, and doubly
so by night, and before they had yet gone half the way Ranulph's
feet began to lag.
"Would you like to rest a bit and then go back?" said Luke eagerly.
But Ranulph shook his head scornfully and mended his pace.
Nor did he allow himself to lag again till they reached their
destination—a little oasis of rich pasturage, already on rising ground
though still a mile or two away from the hills.
Once here—in their own kingdom, as it were—the little herdsmen
became lively and natural; laughing and chatting with Ranulph, as
they set about repairing such breaches as had been made in the
huts by the rough and tumble of twelve odd hours. Then there was
wood to be collected, and a fire to be lit—and into these tasks
Ranulph threw himself with a gay, though rather feverish, vigour.
At last they settled down to their long watch—squatting round the
fire, and laughing for sheer love of adventure as good campaigners
should; for were there not marching towards them some eight dark
hours equipped with who could say what curious weapons from the
rich arsenal of night and day?
The cattle crouched round them in soft shadowy clumps, placidly
munching, and dreaming with wide-open eyes. The narrow zone of
colour created by the fire-light was like the planet Earth—a little freak
of brightness in a universe of impenetrable shadows.
Suddenly Luke noticed that each of the three little herdsmen was,
like himself, wearing a sprig of fennel.
"I say! why are all you little chaps wearing fennel?" he blurted out.
They stared at him in amazement.
"But you be wearing a bit yourself, Master Hempen," said Toby, the
eldest.
"I know"—and he could not resist adding in an offhand tone—"it was
a present from a young lady. But do you always wear a bit in these
parts?" he added.
"Always on this night of the year," said the children. And as Luke
looked puzzled, Toby cried in surprise, "Don't you wear fennel in Lud
on the last night of October?"
"No, we don't," answered Luke, a little crossly, "and why should we, I
should like to know?"
"Why," cried Toby in a shocked voice, "because this is the night
when the Silent People—the dead, you know—come back to
Dorimare."
Ranulph looked up quickly. But Luke scowled; he was sick to death
of western superstitions, and into the bargain he was feeling
frightened. He removed the second sprig of fennel given him by
Hazel from his button-hole, and holding it out to Ranulph, said,
"Here, Master Ranulph! Stick that in your hatband or somewhere."
But Ranulph shook his head. "I don't want any fennel, thank you,
Luke," he said. "I'm not frightened."
The children gazed at him in half-shocked admiration, and Luke
sighed gloomily.
"Not frightened of ... the Silent People?" queried Toby.
"No," answered Ranulph curtly. And then he added, "At least not
tonight."
"I'll wager the widow Gibberty, at any rate, isn't wearing any fennel,"
said Luke, with a harsh laugh.
The children exchanged queer little glances and began to snigger.
This aroused Luke's curiosity: "Now then, out with it, youngsters!
Why doesn't the widow Gibberty wear fennel?"
But their only answer was to nudge each other, and snigger behind
their fingers.
This put Luke on his mettle. "Look here, you bantams," he cried,
"don't you forget that you've got the High Seneschal's son here, and
if you know anything about the widow that's ... well, that's a bit fishy,
it's your duty to let me know. If you don't, you may find yourselves in
gaol some day. So you just spit it out!" and he glared at them as
fiercely as his kindly china-blue eyes would allow.
They began to look scared. "But the widow doesn't know we've seen
anything ... and if she found out, and that we'd been blabbing, oh
my! wouldn't we catch it!" cried Toby, and his eyes grew round with
terror at the mere thought.
"No, you won't catch it. I'll give you my word," said Luke. "And if
you've really anything worth telling, the Seneschal will be very
grateful, and each of you may find yourselves with more money in
your pockets than your three fathers put together have ever had in
all their lives. And, anyhow, to begin with, if you'll tell me what you
know, you can toss up for this knife, and there's not a finer one to be
found in all Lud," and he waved before their dazzled eyes his
greatest treasure, a magnificent six-bladed knife, given him one
Yule-tide by Master Nathaniel, with whom he had always been a
favourite. At the sight of this marvel of cutlery, the little boys proved
venal, and in voices scarcely above a whisper and with frequent
frightened glances over their shoulders, as if the widow might be
lurking in the shadows listening to them, they told their story.
One night, just before dawn, a cow called Cornflower, from the
unusually blue colour of her hide, who had recently been added to
the herd, suddenly grew restless and began to moo, the strange moo
of blue cows that was like the cooing of doves, and then rose to her
feet and trotted away into the darkness. Now Cornflower was a very
valuable cow and the widow had given them special injunctions to
look after her, so Toby, leaving the other two to mind the rest of the
herd, dashed after her into the thinning darkness and though she
had got a good start of him was able to keep in her track by the
tinkling of her bell. Finally he came on her standing at the brink of the
Dapple and nozzling the water. He went close up to her and found
that she had got her teeth into something beneath the surface of the
stream and was tearing at it in intense excitement. Just then who
should drive up in a cart but the widow and Doctor Endymion Leer.
They appeared much annoyed at finding Toby, but they helped him
get Cornflower away from the water. Bits of straw were hanging from
her mouth and it was stained with juices of a colour he had never
seen before. The widow then told him to go back to his companions,
and said she would herself take Cornflower back to the herd in the
morning. And, to account for her sudden appearance on the scene,
she said she had come with the doctor to try and catch a very rare
fish that only rose to the surface an hour before sunrise. "But you
see," went on Toby, "my dad's a great fisherman, and often takes me
out with him, but he never told me about this fish in the Dapple that
can only be caught before sunrise, and I thought I'd just like to have
a peep at it. So instead of going back to the others right away, I hid, I
did, behind some trees. And they took some nets, they did, out of the
cart, but it wasn't fish they drew up in them ... no it wasn't." He was
suddenly seized with embarrassment, and he and his two little
friends again began to snigger.
"Out with it!" cried Luke impatiently. "What was in their nets? You'll
not get the knife for only half a story, you know."
"You say, Dorian," said Toby bashfully, nudging the second eldest
boy; but Dorian, too, would only giggle and hang his head.
"I don't mind saying!" cried Peter, the youngest, valiantly. "It was fairy
fruit—that's what it was!"
Luke sprang to his feet. "Busty Bridget!" he exclaimed in a horrified
voice. Ranulph began to chuckle. "Didn't you guess right away what
it was, Luke?" he asked.
"Yes," went on Peter, much elated by the effect his words had
produced, "it was wicker baskets all full of fairy fruit, I know, because
Cornflower had torn off the top of one of them."
"Yes," interrupted Toby, beginning to think that little Peter had stolen
enough of his thunder, "she had torn off the top of one of the
baskets, and I've never seen fruit like it; it was as if coloured stars
had fallen from the sky into the grass, and were making all of the
valley bright, and Cornflower, she was eating as if she would never
stop ... more like a bee among flowers, she was, than a common
cow. And the widow and the doctor, though of course they were put
out, they couldn't help laughing to see her. And her milk the next
morning—oh my! It tasted of roses and shepherd's thyme, but she
never came back to the herd, for the widow sold her to a farmer who
lived twenty miles away, and...."
But Luke could contain himself no longer. "You little rascals!" he
cried, "to think of all the trouble there is in Lud just now, and the
magistrates and the town guard racking their brains to find out how
the stuff gets across the border, and three little bantams like you
knowing all about it, and not telling a soul! Why did you keep it to
yourselves like that?"
"We were frightened of the widow," said Toby sheepishly. "You won't
tell that we've blabbed," he added in an imploring voice.
"No, I'll see that you don't get into trouble," said Luke. "Here's the
knife, and a coin to toss up for it with ... toasted Cheese! A nice
place this, we've come to! Are you sure, young Toby, it was Dr. Leer
you saw?" Toby nodded his head emphatically. "Aye, it was Dr. Leer
and no mistake—here's my hand on it." And he stuck out a brown
little paw.
"Well, I'm blessed! Dr. Leer!" exclaimed Luke; and Ranulph gave a
little mocking laugh.
Luke fell into a brown study; surprise, indignation, and pleasant
visions of himself swaggering in Lud, praised and flattered by all as
the man who had run the smugglers to earth, chasing each other
across the surface of his brain. And, in the light of Toby's story, could
it be that the stranger whose mysterious conversation with the widow
he had overheard was none other than the popular, kindly doctor,
Endymion Leer? It seemed almost incredible.
But on one thing he was resolved—for once he would assert himself,
and Ranulph should not spend another night at the widow Gibberty's
farm.
Toby won the toss and pocketed the knife with a grin of satisfaction,
and by degrees the talk became as flickering and intermittent as the
light of the dying fire, which they were too idle to feed with sticks;
and finally it was quenched to silence, and they yielded to the
curious drugged sensation that comes from being out of doors and
wide awake at night.
It was as if the earth had been transported to the sky, and they had
been left behind in chaos, and were gazing up at its towns and
beasts and heroes flattened out in constellations and looking like the
stippled pictures in a neolithic cave. And the Milky Way was the only
road visible in the universe.
Now and then a toad harped on its one silvery note, and from time to
time a little breeze would spring up and then die down.
Suddenly Ranulph broke the silence with the startling question, "How
far is it from here to Fairyland?"
The little boys nudged one another and again began to snigger
behind their hands.
"For shame, Master Ranulph!" cried Luke indignantly, "talking like
that before youngsters!"
"But I want to know!" said Ranulph petulantly.
"Tell what your old granny used to say, Dorian," giggled Toby.
And Dorian was finally persuaded to repeat the old saying: "A
thousand leagues by the great West Road and ten by the Milky
Way."
Ranulph sprang to his feet, and with rather a wild laugh, he cried,
"Let's have a race to Fairyland. I bet it will be me that gets there first.
One, two, three—and away!"
And he would actually have plunged off into the darkness, had not
the little boys, half shocked, half admiring, flung themselves on him
and dragged him back.
"There's an imp of mischief got into you tonight, Master Ranulph,"
growled Luke.
"You shouldn't joke about things like that ... specially tonight, Master
Chanticleer," said Toby gravely.
"You're right there, young Toby," said Luke, "I only wish he had half
your sense."
"It was just a bit of fun, wasn't it, Master Chanticleer? You didn't
really want us to race to ... yonder?" asked little Peter, peering
through the darkness at Ranulph with scared eyes.
"Of course it was only fun," said Luke.
But Ranulph said nothing.

You might also like