100% found this document useful (1 vote)
4 views

Unix Shell Programming 3rd Edition Stephen Kochan Patrick Wood instant download

The document provides information about the book 'Unix Shell Programming, Third Edition' by Stephen Kochan and Patrick Wood, including its contents and structure. It contains a detailed table of contents covering various aspects of Unix shell programming, including commands, tools, and programming techniques. Additionally, it offers links to download the book and other related resources.

Uploaded by

aaizakenar66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4 views

Unix Shell Programming 3rd Edition Stephen Kochan Patrick Wood instant download

The document provides information about the book 'Unix Shell Programming, Third Edition' by Stephen Kochan and Patrick Wood, including its contents and structure. It contains a detailed table of contents covering various aspects of Unix shell programming, including commands, tools, and programming techniques. Additionally, it offers links to download the book and other related resources.

Uploaded by

aaizakenar66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Unix Shell Programming 3rd Edition Stephen

Kochan Patrick Wood download

https://ebookbell.com/product/unix-shell-programming-3rd-edition-
stephen-kochan-patrick-wood-21983808

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Learning The Bash Shell Unix Shell Programming In A Nutshell Oreilly


Third Newham

https://ebookbell.com/product/learning-the-bash-shell-unix-shell-
programming-in-a-nutshell-oreilly-third-newham-34488464

Learning The Bash Shell Unix Shell Programming 3rd Edition Cameron
Newham

https://ebookbell.com/product/learning-the-bash-shell-unix-shell-
programming-3rd-edition-cameron-newham-11483542

Unix And Shell Programming 1st Edition Harwani B M

https://ebookbell.com/product/unix-and-shell-programming-1st-edition-
harwani-b-m-5673262

Unix And Shell Programming Anoop Chaturvedi Bl Rai

https://ebookbell.com/product/unix-and-shell-programming-anoop-
chaturvedi-bl-rai-6719026
Introduction To Unix And Shell Programming 1st Edition M G
Venkateshmurthy

https://ebookbell.com/product/introduction-to-unix-and-shell-
programming-1st-edition-m-g-venkateshmurthy-32722142

Shell Programming In Unix Linux And Os X 4th Edition Stephen G Kochan

https://ebookbell.com/product/shell-programming-in-unix-linux-and-
os-x-4th-edition-stephen-g-kochan-5731674

Shell Programming In Unix Linux And Os X 4th Edition Patrick Wood

https://ebookbell.com/product/shell-programming-in-unix-linux-and-
os-x-4th-edition-patrick-wood-5903540

Unix Programming Unix Processes Memory Management Process


Communication Networking And Shell Scripting Dr Vineeta Khemchandani

https://ebookbell.com/product/unix-programming-unix-processes-memory-
management-process-communication-networking-and-shell-scripting-dr-
vineeta-khemchandani-43688982

Mastering Unix Shell Scripting Bash Bourne And Korn Shell Scripting
For Programmers System Administrators And Unix Gurus Second Edition
2nd Edition Randal K Michael

https://ebookbell.com/product/mastering-unix-shell-scripting-bash-
bourne-and-korn-shell-scripting-for-programmers-system-administrators-
and-unix-gurus-second-edition-2nd-edition-randal-k-michael-2245602
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
corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact

International Sales
international@pearsoned.com
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: feedback@samspublishing.com

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,
Standard Input/Output and I/O Redirection 29

Barbara, Harry, Dick. Instead of first entering the names into a file, we’ll enter them
directly from the terminal:

$ sort
Tony
Barbara
Harry
Dick
Ctrl+d
Barbara
Dick
Harry
Tony
$

ai tty01 Sep 12 07:30


oko tty36 Sep 12 13:32
who pat tty21 Sep 12 10:10
ruth tty24 Sep 12 13:07
steve tty25 Sep 12 13:03

FIGURE 2.10 who command.

Because no filename was specified to the sort command, the input was taken from
standard input, the terminal. After the fourth name was typed in, the Ctrl and d keys
were pressed to signal the end of the data. At that point, the sort command sorted
the four names and displayed the results on the standard output device, which is
also the terminal. This is depicted in Figure 2.11.
The wc command is another example of a command that takes its input from stan-
dard input if no filename is specified on the command line. So the following shows
an example of this command used to count the number of lines of text entered from
the terminal:

$ wc -l
This is text that
is typed on the
30 CHAPTER 2 A Quick Review of the Basics

standard input device.


Ctrl+d
3
$

Tony Barbara
Barbara Dick
sort
Harry Harry
Dick Tony

FIGURE 2.11 sort command.

Note that the Ctrl+d that is used to terminate the input is not counted as a separate
line by the wc command. Furthermore, because no filename was specified to the wc
command, only the count of the number of lines (3) is listed as the output of the
command. (Recall that this command normally prints the name of the file directly
after the count.)

Output Redirection
The output from a command normally intended for standard output can be easily
diverted to a file instead. This capability is known as output redirection.

If the notation > file is appended to any command that normally writes its output to
standard output, the output of that command will be written to file instead of your
terminal:

$ who > users


$

This command line causes the who command to be executed and its output to be
written into the file users. Notice that no output appears at the terminal. This is
because the output has been redirected from the default standard output device (the
terminal) into the specified file:

$ cat users
oko tty01 Sep 12 07:30
ai tty15 Sep 12 13:32
ruth tty21 Sep 12 10:10
pat tty24 Sep 12 13:07
Standard Input/Output and I/O Redirection 31

steve tty25 Sep 12 13:03


$

If a command has its output redirected to a file and the file already contains some
data, that data will be lost. Consider this example:

$ echo line 1 > users


$ cat users
line 1
$ echo line 2 >> users
$ cat users
line 1
line 2
$

The second echo command uses a different type of output redirection indicated by
the characters >>. This character pair causes the standard output from the command
to be appended to the specified file. Therefore, the previous contents of the file are
not lost, and the new output simply gets added onto the end.

By using the redirection append characters >>, you can use cat to append the
contents of one file onto the end of another:

$ cat file1
This is in file1.
$ cat file2
This is in file2.
$ cat file1 >> file2 Append file1 to file2
$ cat file2
This is in file2.
This is in file1.
$

Recall that specifying more than one filename to cat results in the display of the
first file followed immediately by the second file, and so on:

$ cat file1
This is in file1.
$ cat file2
This is in file2.
$ cat file1 file2
This is in file1.
This is in file2.
$ cat file1 file2 > file3 Redirect it instead
32 CHAPTER 2 A Quick Review of the Basics

$ cat file3
This is in file1.
This is in file2.
$

Now you can see where the cat command gets its name: When used with more than
one file, its effect is to catenate the files together.

Incidentally, the shell recognizes a special format of output redirection. If you type

> file

not preceded by a command, the shell creates an empty (that is, zero character
length) file for you. If file previously exists, its contents will be lost.

Input Redirection
Just as the output of a command can be redirected to a file, so can the input of a
command be redirected from a file. And as the greater-than character > is used for
output redirection, the less-than character < is used to redirect the input of a
command. Of course, only commands that normally take their input from standard
input can have their input redirected from a file in this manner.
To redirect the input of a command, you type the < character followed by the name
of the file that the input is to be read from. So, for example, to count the number of
lines in the file users, you know that you can execute the command wc -l users:

$ wc -l users
2 users
$

Or, you can count the number of lines in the file by redirecting the standard input
of the wc command from the file users:

$ wc -l < users
2
$

Note that there is a difference in the output produced by the two forms of the wc
command. In the first case, the name of the file users is listed with the line count;
in the second case, it is not. This points out the subtle distinction between the
execution of the two commands. In the first case, wc knows that it is reading its
input from the file users. In the second case, it only knows that it is reading its
Pipes 33

input from standard input. The shell redirects the input so that it comes from the
file users and not the terminal (more about this in the next chapter). As far as wc is
concerned, it doesn’t know whether its input is coming from the terminal or from a
file!

Pipes
As you will recall, the file users that was created previously contains a list of all the
users currently logged in to the system. Because you know that there will be one line
in the file for each user logged in to the system, you can easily determine the number
of users logged in by simply counting the number of lines in the users file:

$ who > users


$ wc -l < users
5
$

This output would indicate that currently five users were logged in. Now you have a
command sequence you can use whenever you want to know how many users are
logged in.
Another approach to determine the number of logged-in users bypasses the use of a
file. The Unix system allows you to effectively connect two commands together. This
connection is known as a pipe, and it enables you to take the output from one
command and feed it directly into the input of another command. A pipe is effected
by the character |, which is placed between the two commands. So to make a pipe
between the who and wc -l commands, you simply type who | wc -l:

$ who | wc -l
5
$

The pipe that is effected between these two commands is depicted in Figure 2.12.

When a pipe is set up between two commands, the standard output from the first
command is connected directly to the standard input of the second command. You
know that the who command writes its list of logged-in users to standard output.
Furthermore, you know that if no filename argument is specified to the wc
command, it takes its input from standard input. Therefore, the list of logged-in
users that is output from the who command automatically becomes the input to the
wc command. Note that you never see the output of the who command at the termi-
nal because it is piped directly into the wc command. This is depicted in Figure 2.13.
Exploring the Variety of Random
Documents with Different Content
WILLIAM COBBETT
Advice to Young Men
William Cobbett, the celebrated English political writer,
was born in March, 1762, at Farnham in Surrey. He took a
dislike to rural occupations, and at an early age went to
London, where he was employed for a few months as a
copying clerk. This work was distasteful to him, and he
enlisted in the army, and went with his regiment to Nova
Scotia. On returning to England in 1791, he obtained his
discharge, married, and went to America. In Philadelphia he
commenced his career as a political writer. Cobbett's "Advice
to Young Men" was published in 1830. It has always been the
most popular of his books, partly because of its subject, and
partly because it illustrates so well the bold and forceful
directness of his style. An intensely egotistical and confident
man, Cobbett believed that his own strangely inconsistent life
was a model for all men. Yet, contrary to what might have
been expected, he was a delightful man in the domestic
circle, and the story of his marriage—which has been
narrated in his "Rural Rides"—is one of the romances of
literary life. The original introduction to the "Advice"
contained personal reference incredible in anyone except
Cobbett. Said he, "Few will be disposed to question my fitness
for the task. If such a man be not qualified to give advice, no
man is qualified." And he went on to claim for himself "genius
and something more." He certainly had a remarkable fund of
commonsense, except when his subject was himself. Cobbett
died June 18, 1835.

I.—To a Youth

You are arrived, let us suppose, at the age of from fourteen to


nearly twenty, and I here offer you my advice towards making you a
happy man, useful to all about you, and an honour to those from
whom you sprang. Start, I beseech you, with a conviction firmly
fixed in your mind that you have no right to live in this world without
doing work of some sort or other. To wish to live on the labour of
others is to contemplate a fraud.
Happiness ought to be your great object, and it is to be found
only in independence. Turn your back on what is called interest.
Write it on your heart that you will depend solely on your own merit
and your own exertions, for that which a man owes to favour or to
partiality, that same favour or partiality is constantly liable to take
from him.
The great source of independence the French express in three
words, "Vivre de peu." "To live upon little" is the great security
against slavery; and this precept extends to dress and other things
besides food and drink. Extravagance in dress arises from the notion
that all the people in the street will be looking at you as you walk
out; but all the sensible people that happen to see you will think
nothing at all about you. Natural beauty of person always will and
must have some weight, even with men, and great weight with
women; but this does not want to be set off by expensive clothes.
A love of what is called "good eating and drinking," if very
unamiable in a grown-up person, is perfectly hateful in a youth. I
have never known such a man worthy of respect.
Next, as to amusements. Dancing is at once rational and
healthful; it is the natural amusement of young people, and none
but the most grovelling and hateful tyranny, or the most stupid and
despicable fanaticism, ever raised its voice against it. As to gaming,
it is always criminal, either in itself or in its tendency. The basis of it
is covetousness; a desire to take from others something for which
you have given, and intend to give, no equivalent.
Be careful in choosing your companions; and lay down as a rule
never to be departed from that no youth or man ought to be called
your friend who is addicted to indecent talk.
In your manners be neither boorish nor blunt, but even these
are preferable to simpering and crawling. Be obedient where
obedience is due; for it is no act of meanness to yield implicit and
ready obedience to those who have a right to demand it at your
hands. None are so saucy and disobedient as slaves; and, when you
come to read history, you will find that in proportion as nations have
been free has been their reverence for the laws.
Let me now turn to the things which you ought to do. And, first
of all, the husbanding of your time. Young people require more sleep
than those that are grown up, and the number of hours cannot well
be, on an average, less than eight. An hour in bed is better than an
hours spent over the fire in an idle gossip.
Money is said to be power; but superior sobriety, industry, and
activity are still a more certain source of power. Booklearning is not
only proper, but highly commendable; and portions of it are
absolutely necessary in every case of trade or profession. One of
these portions is distinct reading, plain and neat writing, and
arithmetic. The next thing is the grammar of your own language, for
grammar is the foundation of all literature. Excellence in your own
calling is the first thing to be aimed at. After this may come general
knowledge. Geography naturally follows grammar; and you should
begin with that of this kingdom. When you come to history, begin
also with that of your own country; and here it is my bounded duty
to put you well on your guard. The works of our historians are, as
far as they relate to former times, masses of lies unmatched by any
others that the world has ever seen.

II.—To a Young Man


To be poor and independent is very nearly an impossibility;
though poverty is, except where there is an actual want of food and
raiment, a thing much more imaginary than real. Resolve to set this
false shame of being poor at defiance. Nevertheless, men ought to
take care of their names, ought to use them prudently and sparingly,
and to keep their expenses always within the bounds of their
income, be it what it may.
One of the effectual means of doing this is to purchase with
ready money. Innumerable things are not bought at all with ready
money which would be bought in case of trust; it is so much easier
to order a thing than to pay for it. I believe that, generally speaking,
you pay for the same article a fourth part more in the case of trust
than you do in the case of ready money. The purchasing with ready
money really means that you have more money to purchase with.
A great evil arising from the desire not to be thought poor is the
destructive thing honoured by the name of "speculation," but which
ought to be called gambling. It is a purchasing of something to be
sold again with a great profit at a considerable hazard. Your life,
while you are thus engaged, is the life of a gamester: a life of
general gloom, enlivened now and then by a gleam of hope or of
success.
In all situations of life avoid the trammels of the law. If you win
your suit and are poorer than you were before, what do you
accomplish? Better to put up with the loss of one pound than with
two, with all the loss of time and all the mortification and anxiety
attending a law suit.
Unless your business or your profession be duly attended to
there can be no real pleasure in any other employment of a portion
of your time. Men, however, must have some leisure, some
relaxation from business; and in the choice of this relaxation much
of your happiness will depend.
Where fields and gardens are at hand, they present the most
rational scenes for leisure. Nothing can be more stupid than sitting,
sotting over a pot and a glass, sending out smoke from the head,
and articulating, at intervals, nonsense about all sorts of things.
Another mode of spending the leisure time is that of books. To
come at the true history of a country you must read its laws; you
must read books treating of its usages and customs in former times;
and you must particularly inform yourselves as to prices of labour
and of food. But there is one thing always to be guarded against,
and that is not to admire and applaud anything you read merely
because it is the fashion to admire and applaud it. Read, consider
well what you read, form your own judgments, and stand by that
judgment until fact or argument be offered to convince you of your
error.

III.—To a Lover

There are two descriptions of lovers on whom all advice would


be wasted, namely, those in whose minds passion so wholly
overpowers reason as to deprive the party of his sober senses, and
those who love according to the rules of arithmetic, or measure their
matrimonial expectations by the claim of the land-surveyor.
I address myself to the reader whom I suppose to be a real
lover, but not so smitten as to be bereft of reason. You should never
forget that marriage is a thing to last for life, and that, generally
speaking, it is to make life happy or miserable.
The things which you ought to desire in a wife are chastity,
sobriety, industry, frugality, cleanliness, knowledge of domestic
affairs, good temper and beauty.
Chastity, perfect modesty, in word, deed, and even thought, is so
essential that without it no female is fit to be a wife. If prudery
mean false modesty, it is to be despised; but if it mean modesty
pushed to the utmost extent, I confess that I like it. The very
elements of jealousy ought to be avoided, and the only safeguard is
to begin well and so render infidelity and jealousy next to
impossible.
By sobriety I mean sobriety of conduct. When girls arrive at that
age which turns their thoughts towards the command of a house it is
time for them to cast away the levity of a child. Sobriety is a title to
trustworthiness, and that is a treasure to prize above all others. But
in order to possess this precious trustworthiness you must exercise
your reason in the choice of a partner. If she be vain, fond of
flattery, given to gadding about, coquettish, she will never be
trustworthy, and you will be unjust if you expect it at her hands. But
if you find in her that innate sobriety of which I have been speaking,
there requires on your part confidence and trust without any limit.
An ardent-minded young man may fear that sobriety of conduct
in a young woman argues a want of warmth; but my observation
and experience tell me that levity, not sobriety, is, ninety-nine times
out of a hundred, the companion of a want of ardent feeling.
There is no state in life in which industry in the wife is not
necessary to the happiness and prosperity of the family. If she be
lazy there will always be a heavy arrear of things unperformed, and
this, even among the wealthy, is a great curse. But who is to tell
whether a girl will make an industrious woman? There are certain
outward signs, which, if attended to with care, will serve as pretty
sure guides.
If you find the tongue lazy you may be nearly certain that the
hands and feet are the same. The pronunciation of an industrious
person is generally quick, distinct, and firm. Another mark of
industry is a quick step and a tread showing that the foot comes
down with a hearty good will.
Early rising is another mark of industry. It is, I should imagine,
pretty difficult to keep love alive towards a woman who never sees
the dew, never beholds the rising sun.
Frugality. This means the contrary of extravagance. It does not
mean stinginess; it means an abstaining from all unnecessary
expenditure. The outward and vulgar signs of extravagance are all
the hardware which women put upon their persons. The girl who
has not the sense to perceive that her person is disfigured, and not
beautified by parcels of brass, tin, and other hardware stuck about
her body, is too great a fool to be trusted with the purse of any man.
Cleanliness is a capital ingredient. Occasional cleanliness is not
the thing that an English or American husband wants; he wants it
always. A sloven in one thing is a sloven in all things. Make up your
mind to a rope rather than to live with a slip-shod wife.
Knowledge of domestic affairs is so necessary in every wife that
the lover ought to have it continually in his eye. A wife must not only
know how things ought to be done, but how to do them. I cannot
form an idea of a more unfortunate being than a girl with a mere
boarding-school education and without a future to enable her to
keep a servant when married. Of what use are her
accomplishments?
Good temper is a very difficult thing to ascertain beforehand—
smiles are so cheap. By "good temper" I do not mean easy temper—
a serenity which nothing disturbs is a mark of laziness. Sulkiness,
querulousness, cold indifference, pertinacity in having the last word,
are bad things in a young woman, but of all the faults of temper
your melancholy ladies are the worst. Most wives are at times
misery-makers, but the melancholy carry it on as a regular trade.
The great use of female beauty is that it naturally tends to keep
the husband in good humour with himself, to make him pleased with
his bargain.
As to constancy in lovers, even when marriage has been
promised, and that, too, in the most solemn manner, it is better for
both parties to break off than to be coupled together with the
reluctant assent of either.

IV.—To a Husband

It is as a husband that your conduct will have the greatest effect


on your happiness. All in a wife, beyond her own natural disposition
and education, is, nine times out of ten, the work of her husband.
First convince her of the necessity of moderation in expense;
make her clearly see the justice of beginning to act upon the
presumption that there are children coming. The great danger of all
is beginning with a servant. The wife is young, and why is she not to
work as well as her husband? If the wife be not able to do all the
work to be done in the house, she ought not to have been able to
marry.
The next thing to be attended to is your demeanour towards a
young wife. The first frown that she receives from you is a dagger to
her heart. Let nothing put you out of humour with her.
Every husband who spends his leisure time in company other
than that of his wife and family tells her and them that he takes
more delight in other company than in theirs. Resolve from the very
first never to spend an hour from home unless business or some
necessary and rational purpose demand it. If you are called away
your wife ought to be fully apprised of the probable duration of the
absence and of the time of return. When we consider what a young
woman gives up on her wedding day, how can a just man think
anything a trifle that affects her happiness?
Though these considerations may demand from us the kindest
possible treatment of a wife, the husband is to expect dutiful
deportment at her hands. A husband under command is the most
contemptible of God's creatures. Am I recommending tyranny? Am I
recommending disregard of the wife's opinions and wishes? By no
means. But the very nature of things prescribes that there must be a
head of every house, and an undivided authority. The wife ought to
be heard, and patiently heard; she ought to be reasoned with, and,
if possible, convinced; but if she remain opposed to the husband's
opinion, his will must be obeyed.
I now come to that great bane of families—jealousy. One thing
every husband can do in the way of prevention, and that is to give
no ground for it. Few characters are more despicable than that of a
jealous-headed husband, and that, not because he has grounds, but
because he has not grounds.
If to be happy in the married state requires these precautions,
you may ask: Is it not better to remain single? The cares and
troubles of the married life are many, but are those of the single life
few? Without wives men are poor, helpless mortals.
As to the expense, I firmly believe that a farmer married at
twenty-five, and having ten children during the first ten years, would
be able to save more money during these years than a bachelor of
the same age would be able to save, on the same farm, in a like
space of time. The bachelor has no one on whom he can in all cases
rely. To me, no being in this world appears so wretched as he.

V.—To a Father

It is yourself that you see in your children. They are the great
and unspeakable delight of your youth, the pride of your prime of
life, and the props of your old age. From the very beginning ensure
in them, if possible, an ardent love for their mother. Your first duty
towards them is resolutely to prevent their drawing the means of life
from any breast but hers. That is their own; it is their birthright.
The man who is to gain a living by his labour must be drawn
away from home; but this will not, if he be made of good stuff,
prevent him from doing his share of the duty due to his children.
There ought to be no toils, no watchings, no breakings of rest,
imposed by this duty, of which he ought not to perform his full
share, and that, too, without grudging. The working man, in
whatever line, and whether in town or country, who spends his day
of rest away from his wife and children is not worthy of the name of
father.
The first thing in the rearing of children who have passed from
the baby state is, as to the body, plenty of good food; and, as to the
mind, constant good example in the parents. There is no other
reason for the people in the American states being generally so
much taller and stronger than the people in England are, but that,
from their birth, they have an abundance of good food; not only of
food, but of rich food. Nor is this, in any point of view, an
unimportant matter, for a tall man is worth more than a short man.
Good food, and plenty of it, is not more necessary to the forming of
a stout and able body than to the forming of an active and
enterprising spirit. Children should eat often, and as much as they
like at a time. They will never take, of plain food, more than it is
good for them to take.
The next thing after good and plentiful and plain food is good
air. Besides sweet air, children want exercise. Even when they are
babies in arms they want tossing and pulling about, and talking and
singing to. They will, when they begin, take, if you let them alone,
just as much exercise as nature bids them, and no more.
I am of opinion that it is injurious to the mind to press book-
learning upon a child at an early age. I must impress my opinion
upon every father that his children's happiness ought to be his first
object; that book-learning, if it tend to militate against this, ought to
be disregarded. A man may read books for ever and be an ignorant
creature at last, and even the more ignorant for his reading.
And with regard to young women, everlasting book-reading is
absolutely a vice. When they once get into the habit they neglect all
other matters, and, in some cases, even their very dress. Attending
to the affairs of the house—to the washing, the baking, the brewing,
the cooking of victuals, the management of the poultry and the
garden, these are their proper occupations.

VI.—To the Citizen

Having now given my advice to the youth, the man, the lover,
the husband, and the father, I shall tender it to the citizen. To act
well our part as citizens we ought clearly to understand what our
rights are; for on our enjoyment of these depend our duties, rights
going before duties, as value received goes before payments. The
great right of all is the right of taking a part in the making of the
laws by which we are governed.
It is the duty of every man to defend his country against an
enemy, a duty imposed by the law of nature as well as by that of
civil society. Yet how are you to maintain that this is the duty of
every man if you deny to some men the enjoyment of a share in
making the laws? The poor man has a body and a soul as well as the
rich man; like the latter, he has parents, wife, and children; a bullet
or a sword is as deadly to him as to the rich man; yet,
notwithstanding this equality, he is to risk all, and, if he escape, he is
still to be denied an equality of rights! Why are the poor to risk their
lives? To uphold the laws and to protect property—property of which
they are said to possess none? What! compel men to come forth and
risk their lives for the protection of property, and then in the same
breath tell them that they are not allowed to share in the making of
the laws, because, and only because, they have no property!
Here, young man of sense and of spirit, here is the point on
which you are to take your stand. There are always men enough to
plead the cause of the rich, and to echo the woes of the fallen great;
but be it your part to show compassion for those who labour, and to
maintain their rights.
If the right to have a share in making the laws were merely a
feather, if it were a fanciful thing, if it were only a speculative theory,
if it were but an abstract principle, it might be considered as of little
importance. But it is none of these; it is a practical matter. Who lets
another man put his hand into his purse when he pleases? It is the
first duty of every man to do all in his power to maintain this right of
self-government where it exists, and to restore it where it has been
lost. Men are in such a case labouring, not for the present day only,
but for ages to come. If life should not allow them time to see their
endeavours crowned, their children will see it.
DANIEL DEFOE
A Journal of the Plague Year
"A Journal of the Plague Year" appeared in 1722. In its
second edition it received the title of "A History of the
Plague." This book was suggested by the public anxiety
caused by a fearful visitation of the plague at Marseilles in the
two preceding years. As an account of the epidemic in
London, it has all the vividness of Defoe's fiction, while it is
acknowledged to be historically accurate. (Defoe biography,
see Vol. III, p. 26.)

I.—A Stricken City

It was about the beginning of September, 1664, that I, among


the rest of my neighbours, heard that the plague was returned again
in Holland. We had no such thing as printed newspapers in those
days to spread rumours and reports of things; but such things as
these were gathered from the letters of merchants, and from them
were handed about by word of mouth only. In December, two
Frenchmen died of the plague in Long Acre, or, rather, at the upper
end of Drury Lane. The secretaries of state got knowledge of it, and
two physicians and a surgeon were ordered to go to the house and
make inspection. This they did, and, finding evident tokens of the
sickness upon both the bodies, they gave their opinions publicly, that
they died of the plague; whereupon it was given in to the parish
clerk, and he also returned them to the Hall; and it was printed in
the weekly bill of mortality in the usual manner, thus:
Plague, 2; Parishes infected, 1.
The distemper spread slowly, and in the beginning of May, the
city being healthy, we began to hope that as the infection was
chiefly among the people at the other end of the town, it might go
no further. We continued in these hopes for a few days, but it was
only for a few, for the people were no more to be deceived thus;
they searched the houses, and found that the plague was really
spread every way, and that many died of it every day; and
accordingly, in the weekly bill for the next week, the thing began to
show itself. There was, indeed, but fourteen set down of the plague,
but this was all knavery and collusion.
Now the weather set in hot, and from the first week in June the
infection spread in a dreadful manner, and the bills rose high. Yet all
that could conceal their distempers did it to prevent their neighbours
shunning them, and also to prevent authority shutting up their
houses.
I lived without Aldgate, midway between Aldgate church and
Whitechapel Bars, and our neighbourhood continued very easy. But
at the other end of the town their consternation was very great, and
the richer sort of people, especially the nobility and gentry, from the
west part of the city, thronged out of town with their families and
servants. In Whitechapel, where I lived, nothing was to be seen but
waggons and carts, with goods, women, servants, children, etc., all
hurrying away. This was a very terrible and melancholy thing to see,
and it filled me with very serious thoughts of the misery that was
coming upon the city.
I now began to consider seriously how I should dispose of
myself, whether I should resolve to stay in London, or shut up my
house and flee. I had two important things before me: the carrying
on of my business and shop, and the preservation of my life in so
dismal a calamity. My trade was a saddler, and though a single man,
I had a family of servants and a house and warehouses filled with
goods, and to leave them all without any overseer had been to
hazard the loss of all I had in the world.
I had resolved to go; but, one way or other, I always found that
to appoint to go away was always crossed by some accident or
other, so as to disappoint and put it off again; and I advise every
person, in such a case, to keep his eye upon the particular
providences which occur at that time, and take them as intimations
from Heaven of what is his unquestioned duty to do in such a case.
Add to this, that, turning over the Bible which lay before me, I cried
out, "Well, I know not what to do; Lord, direct me!" and at that
juncture, casting my eye down, I read: "Thou shalt not be afraid for
the pestilence that walketh in darkness.... A thousand shall fall at thy
side, and ten thousand at thy right hand; but it shall not come nigh
thee." I scarce need tell the reader that from that moment I resolved
that I would stay in the town, casting myself entirely upon the
protection of the Almighty.
The court removed in the month of June, and went to Oxford,
where it pleased God to preserve them; for which I cannot say they
showed any great token of thankfulness, and hardly anything of
reformation, though they did not want being told that their crying
voices might, without breach of charity, have gone far in bringing
that terrible judgment upon the whole nation.
A blazing star or comet had appeared for several months before
the plague, and there had been universal melancholy apprehensions
of some dreadful calamity. The people were at this time more
addicted to prophecies, dreams, and old wives' fables, than ever
they were before or since. Some ran about the streets with oral
predictions, one crying, "Yet forty days, and London shall be
destroyed!" Another poor naked creature cried, "Oh, the great and
dreadful God!" repeating these words continually, with voice and
countenance full of horror, and a swift pace, and nobody could ever
find him to stop. Some saw a flaming sword in a hand coming out of
a cloud; others, hearses and coffins in the air; others, heaps of dead
bodies unburied. But those who were really serious and religious
applied themselves in a truly Christian manner to the proper work of
repentance and humiliation. Many consciences were awakened,
many hard hearts melted into tears. People might be heard in the
streets as we passed along, calling upon God for mercy, and saying,
"I have been a thief," or "a murderer," and the like; and none dared
stop to make the least inquiry into such things, or to comfort the
poor creatures that thus cried out. The face of London was now
strangely altered; it was all in tears; the shrieks of women and
children at the windows and doors, where their dearest relations
were dead, were enough to pierce the stoutest heart.
About June, the lord mayor and aldermen began more
particularly to concern themselves for the regulation of the city, by
the shutting up of houses. Examiners were appointed in every parish
to order the house to be shut up wherever any person sick of the
infection was found. A night watchman and a day watchman were
appointed to each infected house to prevent any person from
coming out or going into the same. Women searchers were
appointed in each parish to examine the bodies of such as were
dead, to see if they had died of the infection, and over these were
appointed physicians and chirurgeons. Other orders were made with
regard to giving notice of sickness, sequestration of the sick, airing
the goods and bedding of the infected, burial of the dead, cleansing
of the streets, forbidding wandering beggars, loose persons, and idle
assemblages, and the like. One of these orders was—"That every
house visited be marked with a red cross of a foot long, in the
middle of the door, with these words, 'Lord have mercy upon us,' to be
set close over the same cross." Many got out of their houses by
stratagem after they were shut up, and thus spread the plague; in
one place they blowed up their watchman with gunpowder and
burnt the poor fellow dreadfully, and while he made hideous cries,
the whole family got out at the windows; others got out by bribing
the watchman, and I have seen three watchmen publicly whipped
through the streets for suffering people to go out.

II.—How the Dead Were Buried

I went all the first part of the time freely about the streets, and
when they dug the great pit in the churchyard of Aldgate I could not
resist going to see it. A terrible pit it was, forty feet long, about
sixteen wide, and in one part they dug it to near twenty feet deep,
until they could go no deeper for the water. It was filled in just two
weeks, when they had thrown into it 1,114 bodies from our own
parish.
I got admittance into the churchyard by the sexton, who at first
refused me, but at last said: "Name of God, go in; depend upon it,
'twill be a sermon to you, it may be the best that ever you heard. It
is a speaking sight," says he; and with that he opened the door and
said, "Go, if you will." I stood wavering for a good while, but just at
that interval I saw two links come over from the end of the Minories,
and heard the bellman, and then appeared a dead-cart coming over
the streets, so I went in.
The scene was awful and full of terror. The cart had in it sixteen
or seventeen bodies; some were wrapped in sheets or rugs, some
little other than naked, or so loose that what covering they had fell
from them in the shooting out of the cart, and they fell quite naked
among the rest. But the matter was not much to them, seeing they
were all dead, and were to be huddled together into the common
grave of mankind, as we may call it; for here was no difference
made, but poor and rich went together. The cart was turned round,
and the bodies shot into the pit promiscuously.
There was following the cart a poor unhappy gentleman who fell
down in a swoon when the bodies were shot into the pit. The buriers
ran to him and took him up, and after he had come to himself, they
led him away to the Pye tavern, over against the end of
Houndsditch. His case lay so heavy on my mind that after I had
gone home I must go out again into the street and go to the Pye
tavern, to inquire what became of him.
It was by this time one in the morning, and yet the poor
gentleman was there. The people of the house were civil and
obliging, but there was a dreadful set of fellows that used their
house, and who, in the middle of all this horror, met there every
night, and behaved with revelling and roaring extravagances, so that
the master and mistress of the house were terrified at them. They
sat in a room next the street, and as often as the dead-cart came
along, they would open the windows and make impudent mocks and
jeers at the sad lamentations of the people, especially if they heard
the poor people call upon God to have mercy upon them.
They were at this vile work when I came to the house, ridiculing
the unfortunate man, and his sorrow for his wife and children,
taunting him with want of courage to leap into the pit and go to
Heaven with them, and adding profane and blasphemous
expressions.
I gently reproved them, being not unknown to two of them. But
I cannot call to mind the abominable raillery which they returned to
me, making a jest of my calling the plague the Hand of God. They
continued this wretched course three or four days; but they were,
every one of them, carried into the great pit before it was quite filled
up.
In my walks I had daily many dismal scenes before my eyes, as
of persons falling dead in the streets, terrible shrieks and
screechings of women, and the like. Passing through Tokenhouse
Yard, in Lothbury, of a sudden a casement violently opened just over
my head, and a woman gave three frightful screeches, and then
cried: "Oh Death! Death! Death!" in a most inimitable tone, which
struck me with horror and a chillness in my very blood. There was
nobody to be seen in the whole street, neither did any other window
open; for people had no curiosity now, nor could anybody help
another. I went on into Bell Alley.
Just in Bell Alley, at the right hand of the passage, there was a
more terrible cry than that, and I could hear women and children
run screaming about the rooms distracted. A garret window opened,
and somebody from a window on the other side of the alley called
and asked, "What is the matter?" upon which, from the first window
it was answered: "O Lord, my old master has hanged himself!" The
other asked again: "Is he quite dead?" And the first answered, "Ay,
ay, quite dead—quite dead and cold."
It is scarce credible what dreadful things happened every day,
people in the rage of the distemper, or in the torment of their
swellings, which was indeed intolerable, oftentimes laying violent
hands on themselves, throwing themselves out at their windows,
etc.; mothers murdering their own children in their lunacy; some
dying of mere fright, without any infection; others frightened into
despair, idiocy, or madness.
There were a great many robberies and wicked practices
committed even in this dreadful time. The power of avarice was so
strong in some that they would run any hazard to steal and to
plunder; and in houses where all the inhabitants had died and been
carried out, they would break in without regard to the danger of
infection, and take even the bedclothes.

III.—Universal Desolation

For about a month together, I believe there did not die less than
1,500 or 1,700 a day, one day with another; and in the beginning of
September good people began to think that God was resolved to
make a full end of the people in this miserable city. Whole families,
and, indeed, whole streets of families were swept away together,
and the infection was so increased that at length they shut up no
houses at all. People gave themselves up to their fears, and thought
that nothing was to be hoped for but an universal desolation. It was
even in the height of this despair that it pleased God to stay His
hand, and to slacken the fury of the contagion.
When the people despaired of life and abandoned themselves, it
had a very strange effect for three or four weeks; it made them bold
and venturous; they were no more shy of one another, nor
restrained within doors, but went anywhere and everywhere, and
ran desperately into any company. It brought them to crowd into the
churches; looking on themselves as all so many dead corpses, they
behaved as if their lives were of no consequence, compared to the
work which they came about there.
The conduct of the lord mayor and magistrates was all the time
admirable, so that bread was always to be had in plenty, and cheap
as usual; provisions were never wanting in the markets; the streets
were kept free from all manner of frightful objects—dead bodies, or
anything unpleasant; and for a time fires were kept burning in the
streets to cleanse the air of infection.
Many remedies were tried; but it is my opinion, and I must leave
it as a prescription, that the best physic against the plague is to run
away from it. I know people encourage themselves by saying, "God
is able to keep us in the midst of danger," and this kept thousands in
the town, whose carcasses went into the great pits by cart-loads. Yet
of the pious ladies who went about distributing alms to the poor, and
visiting infected families, though I will not undertake to say that
none of those charitable people were suffered to fall under the
calamity, yet I may say this, that I never knew any of them to fall
under it.
Such is the precipitant disposition of our people, that no sooner
had they observed that the distemper was not so catching as
formerly, and that if it was catched it was not so mortal, and that
abundance of people who really fell sick recovered again daily, than
they made no more of the plague than of an ordinary fever, nor
indeed so much. They went into the very chambers where others lay
sick. This rash conduct cost a great many their lives, who had been
preserved all through the heat of the infection, and the bills of
mortality increased again four hundred in the first week of
November.
But it pleased God, by the continuing of wintry weather, so to
restore the health of the city that by February following we reckoned
the distemper quite ceased. The time was not far off when the city
was to be purged with fire, for within nine months more I saw it all
lying in ashes.
I shall conclude the account of this calamitous year with a
stanza of my own:
A dreadful plague in London was
In the year sixty-five,
Which swept an hundred thousand souls
Away; yet I alive!
DEMOSTHENES
The Philippics
Demosthenes, by universal consensus of opinion the
greatest orator the world has known, was born at Athens 385
B.C. and died 322 B.C. His birth took place just nineteen years
after the conclusion of the Peloponnesian War. Losing his
father when he was yet a child, his wealth was frittered away
by three faithless guardians, whom he prosecuted when he
came of age. This dispute, and some other struggles, led him
into public life, and by indomitable perseverance he overcame
the difficulty constituted by certain physical disqualifications.
Identifying himself for life entirely with the interests of
Athens, he became the foremost administrator in the state, as
well as its most eloquent orator. His stainless character, his
matchless powers of advocacy, his fervent patriotism, and his
fine diplomacy, render him altogether one of the noblest
figures of antiquity. His fame rests mainly on "The Philippics";
those magnificent orations delivered during a series of several
years against the aggressions of Philip of Macedon; though
the three "Olynthiacs," and the oration "De Coronâ," and
several other speeches are monumental of the genius of
Demosthenes, more especially the "De Coronâ." He continued
to resist the Macedonian domination during the career of
Alexander the Great, and was exiled, dying, it is supposed, by
poison administered by himself, at Calauria. (Cf. also p. 273 of
this volume.) This epitome has been prepared from the
original Greek.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like