The Linux Cookbook, Second Edition
The Linux Cookbook, Second Edition
Michael Stutz
2nd Edition
San Francisco
The Linux Cookbook. Copyright
c 2001, 2002, 2003, 2004 by Michael Stutz
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information storage
or retrieval system, without the prior written permission of the copyright owner and the publisher.
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10–04 03 02 01
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press. Linux
is a registered trademark of Linus Torvalds. Trademarked names are used throughout this book.
Rather than use a trademark symbol with every occurrence of a trademarked name, we are using
the names only in an editorial fashion and to the benefit of the trademark owner, with no intention
of infringement of the trademark.
Publisher: William Pollock
Managing Editor: Karol Jurado
Cover Design: Octopod Studios
Book Design: Michael Stutz
Technical Reviewer: John Mark Walker
Copyeditor: Andy Carroll
Proofreader: Mary Johnson
For information on book distribution or translations, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
555 De Haro Street, Suite 250, San Francisco, CA 94107
phone: 415-863-9900; fax: 415-863-9950; [email protected]; www.nostarch.com
The information in this book is distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of this work, neither the author nor No Starch Press,
Inc. shall have any liability to any person or entity with respect to any loss or damage caused or
alleged to be caused directly or indirectly by the information contained in it. Every effort has been
made to include only the best free software recipes for accomplishing tasks in the easiest and most
efficient manner, and they are believed to be correct. Suggestions, comments, and field reports are
always welcome; the author may be contacted by electronic mail at [email protected].
Library of Congress Cataloging-in-Publication Data
Stutz, Michael.
Linux cookbook : tips and techniques for everyday use / Michael
Stutz.-- 2nd ed.
p. cm.
Includes index.
ISBN 1-59327-031-3
1. Linux. 2. Operating systems (Computers) I. Title.
QA76.76.O63 S788 2004
005.4'32--dc22
2003021940
A note on the type
in which this book is set
The name of the font family used in this book is Computer Modern. These are
free fonts designed by Donald E. Knuth for his TEX typesetting system, and
are described in Volume E of the Computers & Typesetting series, Computer
Modern Typefaces (Addison–Wesley, 1986).
This book was written and produced using the free software tools it describes.
It was prepared with Texinfo, a documentation system that uses TEX to gener-
ate typeset output. The Texinfo input files were composed in gnu Emacs, and
the screen shots were taken and processed with the ImageMagick suite of tools.
The dvi output was converted to PostScript for printing using Tomas Rokicki’s
Dvips, gnu Ghostscript, and Angus Duggan’s PostScript Utilities. The sys-
tem was a 1,000 MHz 686 personal computer running Debian gnu/Linux 3.0.
Updates
Visit http://www.nostarch.com/lcbk2.htm for updates, errata, and other
information.
Contents at a Glance
Preface to the Second, Revised Edition . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
I. WORKING WITH LINUX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 What Every Linux User Knows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3 The Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4 The X Window System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
II. FILES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5 Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
6 Sharing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
7 Finding Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
8 Managing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
III. TEXT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
9 Viewing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
10 Editing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
11 Grammar and Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
12 Analyzing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
13 Formatting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
14 Searching Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
15 Typesetting and Word Processing . . . . . . . . . . . . . . . . . . . . . . . . . . 357
16 Using Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
IV. IMAGES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
17 Viewing Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
18 Editing Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
19 Importing Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
20 PostScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
V. SOUND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
21 Playing and Recording Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
22 Audio Compact Discs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
23 Editing Sound Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
VI. PRODUCTIVITY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
24 Disk Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
25 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
26 Cross-Platform Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
27 Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
28 Scheduling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
vi The Linux Cookbook, 2nd Edition
29 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
30 Amusements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
VII. NETWORKING. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
31 Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
32 Email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
33 The World Wide Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
34 Other Internet Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
APPENDICES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
Appendix A Administrative Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
Appendix B Conventional File Name Extensions . . . . . . . . . . . . . 723
Appendix C Setting Up Your Home Directory . . . . . . . . . . . . . . . 727
Appendix D References for Further Interest . . . . . . . . . . . . . . . . . . 731
Program Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Concept Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
vii
Table of Contents
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Recipe Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Preparation of Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 Format of Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Who This Book Assumes You Are . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 What This Book Won’t Show You . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 What to Try First . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.6 If You Need More Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Background and History of Linux . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7.1 Early Days of unix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7.2 Genesis of the Free Software Movement . . . . . . . . . . . 16
1.7.3 The Arrival of Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.7.4 Debian, Red Hat, and Other Linux Distributions . . 19
1.7.5 The Penguin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.7.6 Open Source, Free Content, and the Future . . . . . . . 20
1.7.7 unix and the Tools Philosophy . . . . . . . . . . . . . . . . . . . 22
3. The Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.1 Typing at the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.1.1 Using Basic Command Line Editing Keys . . . . . . . . . 54
3.1.2 Typing a Control Character. . . . . . . . . . . . . . . . . . . . . . 55
3.1.3 Quoting Reserved Characters . . . . . . . . . . . . . . . . . . . . 56
3.1.4 Letting the Shell Complete What You Type . . . . . . . 61
3.1.5 Undoing a Mistake at the Command Line . . . . . . . . . 62
3.1.6 Repeating the Last Command You Typed. . . . . . . . . 62
3.1.7 Running a List of Commands . . . . . . . . . . . . . . . . . . . . 63
3.1.8 Running One Command and Then Another . . . . . . . 64
3.1.9 Running One Command or Another . . . . . . . . . . . . . . 64
3.1.10 Automatically Answering a Command Prompt . . . 65
3.1.11 Specifying the Output of a Command as an
Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3.1.12 Typing a Long Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
ix
V. SOUND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
APPENDICES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
The core melds, picks up new features, refines or discards others, but some-
how it lingers and remains. In that sense it is the only part worth dwelling
on. In the 1970s, typing ls from a hardware terminal to list the files in a
directory worked much the same as it does today on Linux. This inner core is
the language of unix, and it is the foundation upon which the entire system
is laid.
It has always been my desire to clearly and completely teach that founda-
tion in the Cookbook, and I hope that the product you now hold may be of
more worth, and resonate longer, than something that only chases after the
sleek contours and momentary luster of the latest and already fading outer
shell, while leaving so much of the inner magic still a mystery.
And so here it is: A new edition that gives, to the reader, a book whose
substance was improved, its horizons broadened—and to the author, a chance
to do a second take, to trim and burnish, to attempt refinement of a work
once labored on. I hope you likewise find the journey sufficiently rewarding.
Michael Stutz
June, 2004
I. WORKING WITH LINUX 1
1. Introduction
Before we start “cooking,” we’ll get some preliminaries out of the way in this
chapter, which explains both how the book is organized and the conventions
that are used throughout it. It also shows you where to begin if you’re new
to Linux, and how to get more help, should you need it. It concludes with a
short background history of the software that is the subject of the book.
The rest of the book is all recipes, which are categorized by the tasks they
perform or the objects they work on—such as text, files, images, and so forth.
This first part of the book explains the general techniques and methods for
working with Linux—including how to get the system ready for use, how to
run commands on the system, which commands every Linux user knows, and
how to use the interfaces that come with Linux.
1.1 Recipes
Recipes are methods for accomplishing a particular task on Linux. Recipes
are organized into chapters, which deal with one specific kind of task, such as
Viewing Text or Editing Images. Chapters are often concluded with a table
of hints identifying more applications or tools pertinent to the subject of that
chapter.
You might not have all of these programs installed on your system and
ready for use, so recipes commence with a listing of the programs it uses and
the packages or urls where you can find them.
Ingredients that most everyone is sure to have on hand are omitted from
this listing. For example, the ls command for listing files in a directory will
be available on all systems, so its listing is always omitted.
The rule of measure for determining whether an ingredient is listed or not
comes from the Debian distribution, which classifies packages in varying levels
of importance, from the “Required” packages that all systems absolutely must
have in order to run, to “Optional” and “Extra” packages that you only install
if you want them. If it’s “Required” or “Important” to Debian, then it’s a
very common program no matter what your distribution, and I don’t need to
list it.
$
A border is also drawn around shell scripts and other program listings that
are to be typed in.
In examples where a shell prompt is displayed, the default current working
directory is omitted in the prompt, and a “$” is used on its own; when a
command outputs text and then exits, the last line of an example contains
a “$” character to denote the return to a shell prompt. Don’t worry if this
sounds strange to you now; all of this “shell” business is explained in Chapter 3
[The Shell], page 53.
Borders are not drawn around “one-liner” examples showing commands
that return to the shell prompt without giving any output, or commands
Chapter 1: Introduction 7
whose output is not particularly relevant to the example. The returning shell
prompt is omitted here, too.
The names of files or directories appear in the text as file; commands
appear as command, and strings of text are typeset like “some text”; options,
application modes and menu items, function names, and variable names are
all set in this same typewriter font.
Text you are intended to type is written like this, just as in the examples.
When you are meant to press a specific key on the keyboard, its conventional
name is given displayed in a key box. For example, Q represents the Q key
on the keyboard, and RET denotes the Return key on the keyboard for typing
a newline.1
So where I say, “To do this, type:” and then give a sample command line,
the text you actually type is presented like this and the text that is output
by the system is presented like this. Keys you are to press, as opposed to
characters you literally type, are given as a key box.
⇒ For example, pressing the F key is denoted by F, while just typing an
uppercase “F” is denoted by F, and typing a lowercase “f” by f.
In examples where keys are meant to be pressed and held down together,
the keys are connected together with hyphens; the hyphens are not meant to
be literally pressed. For example, pressing the CTRL, ALT, and DEL keys,
and holding them down at the same time, is a combination that has meaning
in some operating systems (including Linux, where this keystroke shuts down
the system and reboots the computer); it is represented like this:
CTRL- ALT- DEL
In the same way, keys that are meant to be pressed one after another are
separated by a space; the space is not to be literally typed. So for a keystrokes
such as this:
RET RET
you would press the carriage return key, and then press the carriage return
key again, but do not type a space between them. The same goes for text
followed by a key—for example, a physical space appears in the book between
commands and the final RET that ends a command line, and it should not
be literally typed (although there is often no consequence for actually typing
this space). Where explicitly pressing the space bar is called for, that key is
represented in examples as SPACEBAR.
1
This key is labeled “Enter” on some keyboards, while still others have only an arrow
going downward and then pointing to the left like the old carriage return of typewriters.
8 The Linux Cookbook, 2nd Edition
In some applications, the META key is used in the same way as CTRL.
gnu Project programs and documentation denote META key combinations
by M-x, where x is the second key in the combination. Most keyboards today
don’t have a META key, of course; where you see reference to this key, just
use the ALT key. Throughout this book, I’ll write these combinations in key
notation with ALT instead of META, since the former key is most often the
actual key in use.
⇒ So to type M-c, press and hold ALT, press the C key, and then release
both keys.
Chapter 1: Introduction 9
You can often get the same effect by pressing and releasing ESC, and then
pressing the second key. Do this if your keyboard doesn’t have an ALT key,
or if your ALT isn’t set up as the META key.2
⇒ To type M-c without using ALT, press and release ESC, and then press
and release the C key.
Both CTRL and ALT sequences are not case-sensitive; that is, pressing a
capital C to make the last example is the same as pressing the lowercase c
(although c is certainly easier to type, if Caps Lock is off). In gnu notation,
the C- or M- prefix is always given as an uppercase letter, and the key that
follows is always given as a lowercase letter. The convention for hat notation
is to always use an uppercase letter for the control key.
Furthermore, some programs take commands that are a combination of key
combinations and sequences, and so the hyphen and space representations can
be combined. For instance, if a command is to press and hold CTRL, press
X and release both keys, and then type a lowercase letter “q,” this will be
denoted in the text as:
CTRL- X q
And finally, a remark on quoted punctuation. In the Internet age it has
become a trend, away from the American printing convention, to place trailing
punctuation outside of the quotation. The argument is that computers cannot
recognize the punctuation for what it is, and assume it is part of the literal
characters being quoted. We operators don’t want to confuse the machine, so
we keep this trailing punctuation outside the quotes. First it was adopted in
the computer programming languages (not a one, to my knowledge, accepts
text written in the American convention), and then in the technical manuals
and computer books, and it is now becoming widespread throughout other
literature, especially in online publications.
But we human beings understand punctuation, and it is for us that it
exists. We should make systems that work for us, and print words the way
we intend to write them—not bend our own expressions to fit the tooth of a
sprocket.
2. Use proprietary software. The very reason I use Linux and recommend
it to others is because it is not proprietary, but is published in such a way
so that anyone can examine the software, share it with others, and adapt
it to his needs. I don’t use proprietary software at all and don’t know
the first thing about it. Therefore, there will be no proprietary software
in this book.
3. Use experimental software. There are thousands of software programs
available for Linux, and I cover a good deal of the most popular and
important ones. What I omit are the software packages that are currently
in a “beta” or some other unstable release not yet intended for the general
public.
4. Secure your system. The specialized topic of security is sufficiently large
to warrant its own book.
5. Become a system administrator. The basic tasks of system administration
for the home user are described in Appendix A [Administrative Issues],
page 699, which is enough to get you going successfully; for more detail
than this, you will need a specialized book on the subject. I recommend
the Linux System Administrators’ Guide, which should be available right
on your system (for how to access it, see Recipe 2.8.6 [Reading System
Documentation and Help Files], page 50).
6. Administrate a network. There are too many kinds of networks, and
this is most often a technical and not user-based application. The Linux
Network Administrators Guide is recommended for this purpose (see Ap-
pendix D [References For Further Interest], page 731).
7. Use Linux in software development. Program development, compilation,
and software project management are out of this book’s scope. However,
12 The Linux Cookbook, 2nd Edition
the programmer will find much of the material in this book useful for his
task.
8. Use Linux in other specialized fields. Everything in this book should
be useful to you, whether you are a music composer, biochemist,
schoolteacher, secretary, or whatever. However, this book will have no
specific sections for “Using Linux for Music Composition,” “Using Linux
in Biochemistry Research,” “Using Linux in the Classroom,” or “A
Secretary’s Guide to Linux,” although Linux is used in such fields of
endeavor to great success. Reports, papers, Web sites and even books
have been written on the use of Linux in innumerable special fields, and
its applications are growing. In the Cookbook, I cover the basics of
using Linux as a general tool, regardless of your specific field or interest.
9. Use a non-Linux system. Most of the free software described in this
book has been ported to other systems, particularly to other flavors of
unix. The recipes in this book should more or less work on these systems.
However, this isn’t The UNIX Cookbook, and so any peculiarities of non-
Linux usage are not addresssed—Linux is always the assumed platform.
1. Chances are good that you are not alone in your question, and that some-
one else has asked it before; therefore, the compendiums of “Frequently
Asked Questions” may have the answer you need. What follows are some
of the more popular faqs for Linux.
4. Find the Linux User Group (lug) nearest you—people involved with lugs
can be great sources of hands-on help, and it can be fun and rewarding to
get involved with other Linux and free-software enthusiasts in your local
area.
3
The set of basic software tools that a computer needs so that you can operate it to any
success, including a means to run other programs.
4
While the term hacker has come to refer to a computer vandal or intruder, the original
computer meaning concerned a computer programmer or technician who finds obsessive
joy in programming and consequently is adept or inventive at it.
5
The name unix was first written as unics, which stood for “Uniplex Information and
Computing System.”
16 The Linux Cookbook, 2nd Edition
6
For a computer to make use of these written works, the source code must be run through
a compiler, which is a program that uses these writings to output a new file of machine
instructions. A software program in compiled form, not readable by man, is called a
binary or executable file. Binaries are the files you use when you run a program on the
system.
7
But today, when people say “unix,” they usually mean “a unix-like operating system,”
a generalization that includes Linux.
Chapter 1: Introduction 17
8
No such “official gnu” operating system has yet been released in its entirety, but most
people today consider Linux-based free software systems to be the effective realization
of Stallman’s goals—hence his famous request for people to call the Linux-based system
“gnu/Linux” instead.
9
Originally the “Emacs Public License” when first published in 1985; the current gnu
gpl is on the Web at http://www.gnu.org/copyleft/gpl.txt.
18 The Linux Cookbook, 2nd Edition
for copies of a free software work, but there are never any secret writings—with
free software, anyone can read the source code.
characteristics and features that a basic unix operating system should have.
When Linux began to meet these technical specifications, and then when it
finally became posix compliant, the efficacy of Linux as a viable flavor of unix
could not be denied, and it received acceptance in areas where there had been
marked resistance in the past.
Through these relatively few years of development, the Linux software has
been immensely extended and improved, so that the Linux-based system of
today is a complete, modern operating system that rivals anything else that
is currently available.
from any of it. This kind of closed-source software is presented to the world
as a kind of magic trick: If you buy a copy of the program, you may use it,
but you can never learn how the program actually works.16
The result of this is that the code to handle essentially the same function
inside all of these different applications must be developed by programmers
from scratch, separately and independently of the others each time—so the
progress of society as a whole is set back by the countless man-hours of time
and energy programmers must waste by inefficiently reinventing all the same
software functions to perform the same tasks, over and over again.
Just as the tensile strength of chrome-nickel steel is greater than the added
strength of its components, multiple tools could then be combined to perform
16
In fact, under the Digital Millennium Copyright Act (dmca), signed into law by President
Clinton on October 28, 1998, it is a federal crime for you to even try.
24 The Linux Cookbook, 2nd Edition
a task unpredicted by the function of the individual tools. This is the concept
of synergy, and it forms the basis of the unix tools philosophy.17
Here’s an example, using two tools. The first tool, called who, outputs a
list of all the users who are currently logged on to the system (see Recipe 2.6.2
[Listing Who Is on the System], page 39). The second tool is called wc, which
stands for “word count”; it outputs a count of the number of words (or lines or
characters) of the input you give it (see Recipe 12.1 [Counting Text], page 293).
By combining these two tools, giving the output of who to the wc command,
you can build a new command to list the number of users currently on the
system, as in Figure 1-2.
$ who | wc -l RET
4
$
Figure 1-2. Listing the number of users on the system.
The output of who, a list of all the users who are on the system right now,
is piped—via a “pipeline,” specified by the vertical bar—to the input of wc,
which through use of the -l option outputs the number of lines of its input.
In this example, the numeral 4 is output, indicating that four users are
currently logged on to the system.18
Another famous pipeline from the days before spell-check tools goes some-
thing like Figure 1-3.
while ferreting out all duplicates, and the resultant list is then compared with
/usr/dict/words, which is the system “dictionary,” a list of properly spelled
words kept in alphabetical order (see Recipe 11.1 [Spell Checking], page 275).
The great bulk of this book details various combinations of tools you can
use to obtain the desired results for various common tasks. Some tasks will
require more than one command sequence; others need the fine, complex mo-
tions exercised through the large application programs. You’ll find that there’s
usually one tool or command sequence that works perfectly for a given task,
but sometimes a satisfactory or even identical result can be had from different
combinations of different tools—especially at the hands of a unix expert.19
This way of formulating commands to accomplish tasks, so different from
the wysiwyg20 systems where you “point and click” at graphic icons, is the
language of unix. In most everyday use, you’ll rarely use more than a vocab-
ulary of twenty words (tools) and a few inflections each (their options)—but
what can you express with them, and how quickly, in contrast to merely point-
ing at pictures!
19
Such an expert used to be called a wizard; a more colloquial expression is guru, and
then there’s the more generalized (and downright awful) computer geek of today.
20
“What You See Is What You Get.”
26 The Linux Cookbook, 2nd Edition
Chapter 2: What Every Linux User Knows 27
turning off the power could result in the loss or corruption of some of your
work.
There is a special shutdown tool the system administrator can use to shut
down the computer, as described in Recipe A.2 [Shutting Down the System],
page 703. But you can always shut down your system from the console,
whether you are logged in or not, by using the special CTRL- ALT- DEL
keystroke (also known as the “three-finger salute,” a carry-over from the dos
days). This keystroke immediately begins the shutdown process, and then
reboots the system. If you cut power to the system before it reboots, you can
shut it down in this way.
⇒ To turn off a single user system even when you are not logged in as the
administrator, type CTRL- ALT- DEL (press and hold these three keys
at once).1
When you do this, the system will display some messages to the screen as
it shuts down; when you see the line, “Rebooting...,” it’s safe to flip the
power switch.
NOTES: You don’t want to wait too long after you see this message; if left
untouched, the system will reboot and you’ll be back to the beginning!
whose username is root; this account has total access to the entire system, so
it is often called the superuser.)
Until the mid-1990s, it was common for usernames to be the first letter of
your first name followed by your entire surname, up to 12 characters total. So,
for example, user George Washington would have a username of gwashington
by this convention; this, however, is not a hard and fast rule, especially on
home systems where you may be the only user. Sometimes, a middle ini-
tial is added (“usgrant”), or sometimes even nicknames or initials are used
(“gipper,” “jfk”). But whatever username you pick for yourself, make sure
it’s one you can live with, and one you can stand being called by both the sys-
tem and other users (your username also becomes part of your email address,
as you’ll see in Chapter 32 [Email], page 611).
In addition to your username, you should also have a password that you
can keep secret so that only you can use your account. Good passwords are
strings of text that nobody else is likely to guess, (i.e., not obvious words like
“secret,” or identifying names like “Ruski,” if that happens to be your pet
cat). A good password is one that is so memorable to you that you don’t
ever have to write it down, but complex enough in construction so that no
one else could ever guess it. For example, ‘t39sAH’ might be a fine password
for someone whose first date was to see the movie The 39 Steps, directed by
Alfred Hitchcock.
NOTES: While usernames are always in lowercase, passwords are case sen-
sitive; the passwords “Secret,” “secret,” “SECReT,” and “SECRET” are all
considered different.
bardo login:
Figure 2-1. Typical Linux login: prompt.
30 The Linux Cookbook, 2nd Edition
The login: prompt appears on the terminal after the system boots. If
your system is configured to start the X Window System at boot time, you’ll
be presented with an X login screen instead of the standard login prompt. If
that happens, press CTRL- ALT- F1 to switch to the text login screen; this is
explained further in Recipe 2.3 [Using Consoles and Terminals], page 32.
To log in to the system, type your username (followed by RET) at the
login: prompt, and then type your password when asked (also followed by
RET). For security purposes, nothing is displayed on the screen when you
type your password; if you make a mistake while typing it in, type CTRL- U
to erase the line of input and start over.
⇒ To log in to the system with a username of “kurt” and a password of
“empathy,” type:
Most of the programs included with the Debian Linux system are freely
redistributable; the exact distribution terms for each program are
described in the individual files in /usr/doc/*/copyright
As soon as you log in, the system displays the contents of /etc/motd, the
“Message of the Day” file. The system then displays the time and date of
your last login, and reports whether or not you have mail waiting for you (see
Chapter 32 [Email], page 611). Finally, the system puts you in a shell—the
environment in which you interact with the system and give it commands. The
default shell on most Linux systems is Bash, and how you use it is discussed
in Chapter 3 [The Shell], page 53.
Chapter 2: What Every Linux User Knows 31
The dollar sign ($) displayed to the left of the cursor is called the shell
prompt; it means that the system is ready and waiting for input. (You can
change this prompt to any text of your liking; to learn how, see Recipe 3.5.6
[Changing the Shell Prompt], page 80.) Many distributions are set up so that
the shell prompt includes the name of the current directory by default, which
it places to the left of the dollar sign. When you log in, you are in your home
directory, which the shell represents as the the tilde character (~). Directories
are explained in Chapter 5 [Files and Directories], page 125.
NOTES: Every Linux system has its own name, called the system’s hostname;
a Linux system is sometimes called a host, and it identifies itself with its
hostname at the login: prompt. It’s important to name your system; like
a username for a user account, a hostname gives a name to the system you
are using (and it becomes especially important when putting the system on
a network). The system administrator usually names the system when it is
being initially configured (the hostname can always be changed later; its name
is kept in the file /etc/hostname).
Like usernames, hostnames are single words in all lowercase letters. People
usually give their systems a name they like, such as darkstar or shiva. In the
preceding examples, “bardo” is the hostname of this particular Linux system,
which happens to be running the Debian distribution.
The name of the terminal you are connecting from is displayed just after
the hostname. In this example, the terminal is tty1, which means that this is
the first terminal on this particular system. (Incidentally, “tty” is short for
“teletype,” which historically was the kind of terminal hardware that most
unix-based systems used by default.)
$ logout RET
bardo login:
NOTES: If you are the only person using your system and have just ended
a session by logging out, you might want to power down the system. See
Recipe 2.1.2 [Turning Off the System], page 27, earlier in this chapter.
2
Hardware built especially for this function are called dumb terminals because they have
no computing power of their own, but are just input and output facilities for interacting
with the actual computer they are connected to.
Chapter 2: What Every Linux User Knows 33
$ fgconsole RET
3
$
METHOD #1
To switch to a different virtual console, press and hold ALT plus the function
key whose number corresponds to the number of the console you would like
to switch to.
⇒ To switch to the fourth virtual console, press ALT- F4.
This command switches to the fourth virtual console, denoted by “tty4”:
bardo login:
You can also cycle through the different virtual consoles with the left and
right arrow keys. To switch to the next-lowest virtual console (or wrap around
34 The Linux Cookbook, 2nd Edition
to the highest virtual console, if you’re at the first virtual console), press ALT-
. To switch to the next-highest virtual console, press ALT- .
⇒ To switch from the fourth to the third virtual console, press:
ALT-
bardo login:
To switch back to the console you were last at, press ALT- PrtScrn.
METHOD #2
Use chvt to change to a different virtual console. It takes as an argument the
number to change to.
⇒ To change to the seventh virtual console, type:
$ chvt 7 RET
• Once you have scrolled back, press SHIFT- PgDn to scroll forward
through the text toward the more recent text.
The amount of text you can scroll back through depends on system
memory.
NOTES: This technique is for scrolling through text displayed in your shell
session (see Chapter 3 [The Shell], page 53). It does not work for scrolling
through text in a tool or application in the console. In other words, you can’t
use this technique to scroll through text that is displayed by a tool for perusing
text files. To scroll through text in an application, use its own facilities for
scrolling, if it has any.
METHOD #1
Type clear to clear the screen of the terminal you are working in. The
screen will be redrawn with a new command line on the top line, and all other
contents on the screen will be erased.
⇒ To clear the terminal screen, type:
$ clear RET
METHOD #2
To clear the terminal screen and redraw the current command line at the top,
type CTRL- L.
Unlike clear, which is a complete command you input at the command
line, you can type CTRL- L anywhere on a command line that contains some-
thing else you’re typing—it redraws the current command line you are at,
complete with everything on it, at the top of the screen.
⇒ To clear the terminal screen and redraw the current command line at the
top of the screen, type:
CTRL- L
36 The Linux Cookbook, 2nd Edition
NOTES: This keystroke works in the Bash shell, which is the subject of the
next chapter.
NOTES: You can practice this so you know what it looks like when it really
happens. Do this by sending the output of a binary file to the terminal
screen—type cat /bin/ls and see what it does to the terminal; then type
reset to reset it.
$ hostname RET
camelot
$
Sometimes the list of available options fills much more than a screen, so
you may want to pipe the output through less for perusal (see Recipe 9.1
[Perusing Text], page 211). Press Q to stop perusal.
⇒ To peruse the available options for the lynx tool, type:
$ lynx -? | less RET
3
Some tools have neither option, in which case you should try the -? option.
38 The Linux Cookbook, 2nd Edition
This command outputs the text “hostname 2.10,” indicating that this is
version 2.10 of the hostname tool.
$ passwd RET
Changing password for kurt
Old password: your current password RET
Enter the new password (minimum of 5, maximum of 8 characters)
Please use a combination of upper and lower case letters and numbers.
New password: your new password RET
Re-enter new password: your new password RET
Password changed.
$
NOTES: Passwords can contain uppercase and lowercase letters, the digits
0 through 9, and punctuation marks; they should be between five and eight
Chapter 2: What Every Linux User Knows 39
characters long. See Recipe 2.2 [Using Your Account], page 28, for suggestions
on choosing a good password.
$ whoami RET
will
$
In this example, the username of the user logged in at this terminal is
“will.”
$ who RET
murky tty1 Oct 20 20:09
dave tty2 Oct 21 14:37
kurt tty3 Oct 21 15:04
kurt ttyp1 Oct 21 15:04 (:0.0)
$
40 The Linux Cookbook, 2nd Edition
The output in this example shows that the user murky is logged in on tty1
(the first virtual console on the system), and has been on since 20:09 on 20
October. The user dave is logged in on tty2 (the second virtual console), and
has been on since 14:37 on 21 October. The user kurt is logged in twice—on
tty3 (the third virtual console), and on ttyp1, which is an X session with a
window location of (:0.0).
NOTES: This command is for listing the users on the local system; to list the
users connected to a different system on the network, or to see more detailed
personal information that a user may have made public, see Recipe 34.5.1
[Checking Whether a User Is Online], page 683.
$ w RET
5:27pm up 17:53, 4 users, load average: 0.12, 0.06, 0.01
USER TTY FROM LOGIN IDLE JCPU PCPU WHAT
murky tty1 Oct 20 20:09 17:22m 0.32s 0.32s -bash
dave tty2 14:37 13.00s 2:35 0.07s less foo
kurt tty3 15:04 1:00m 0.41s 0.09s startx
kurt ttyp1 :0.0 15:04 0:00s 21.65s 20.96s emacs
$
In this example, the command’s output shows that the current system time
is 5:27 p.m., the system has been up for 17 hours and 53 minutes, and there
are four users currently logged in: murky is logged in at tty1, has been idle
for 17 hours and 22 minutes, and is at a Bash shell prompt; dave is logged
in at tty2, has been idle for 13 seconds, and is using less to peruse a file
Chapter 2: What Every Linux User Knows 41
named foo (see Recipe 9.1 [Perusing Text], page 211); and kurt is logged
in at two terminals—tty3 and ttyp1, which is an X session. He ran the
startx command on tty3 to start his X session, and within his X session, he
is currently using Emacs.
To find out when a particular user last logged in to the system, give the
username as an argument.
⇒ To find out when user james last logged in, type:
$ last james RET
NOTES: The last tool gets its data from the system file /var/log/wtmp; the
last line of output tells how far this file goes back. Sometimes, the output will
go back for several weeks or more.
$ ps RET
PID TTY STAT TIME COMMAND
193 1 S 0:01 -bash
204 1 S 0:00 ps
$
In this example, ps shows that two processes are running: the bash and
ps commands.
NOTES: This command is useful for listing all of your own processes, running
across all terminals and shell sessions; give your own username as an argument.
METHOD #1
To get a list of all processes being run by all users on the system, use ps with
the aux options.
⇒ To list all of the processes and give their usernames, type:
$ ps aux RET
pipe the output of this command through less for perusal (see Recipe 9.1
[Perusing Text], page 211).
METHOD #2
Use top to show a chart of all processes on the system, sorted by their demands
on the system resources. The display is continually updated with current
process information; press Q to stop the display and exit the program. This
tool also displays the information about system runtime and memory that can
be output with the uptime and free commands.
⇒ To see a continually updated display of the current system processes,
type:
$ top RET
METHOD #1
When you know what a particular tool or application does but you can’t
remember its name, the first thing to do is use apropos. This tool takes a
keyword as an argument, and it outputs a list of installed software whose
one-line descriptions contain that keyword. It searches for the given text in
the names and short descriptions in the system manual, and it outputs a
list of the tools that match. This is also useful for finding software on your
system related to, say, “audio” or “sound” or “sort” or some other such general
concepts.
⇒ To output a list of programs that pertain to consoles, type:
$ apropos console RET
NOTES: The apropos tool matches lines that contain the keyword you give
exactly as typed, anywhere in the line. A search for the keyword “consoles”
might not list all the programs that a search for the keyword “console”
would yield; a search on “con” matches even more. Therefore, it’s better to
try singular forms, and then refine your terms if you need to. The trick to
getting good results from apropos is to know just which keywords are apt to
be used in the descriptions of the thing you’re looking for.
The apropos tool is an alias for man with the -k option (see Recipe 2.8.4
[Reading a Page from the System Manual], page 46).
METHOD #2
Dpkg
DEB: dpkg
NOTES: For more information on using dpkg, see Recipe A.4 [Managing deb
Packages], page 709.
METHOD #3
On rpm-based systems such as Fedora and Red Hat Enterprise Linux, you
can find installed software by keyword using rpm, the package management
tool. Give the -qa option to output the names of all packages installed on
the system. To find specific packages, pipe the output to grep with the -i
option and a pattern to match (see Recipe 14.1 [Searching Text for a Word],
page 333). Pipe this to less for perusal.
⇒ Here are some ways to use this.
• To peruse a list of all rpm packages installed on the system, type:
$ rpm -qa | less RET
• To list all packages whose name or description includes the word
“edit,” regardless of case, type:
$ rpm -qa | grep -i edit RET
• To list all of the rpm packages installed on the system whose name
contains the text “1.2,” type:
$ rpm -qa | grep "1\.2" RET
NOTES: For more information on using rpm, see Recipe A.5 [Managing rpm
Packages], page 714.
46 The Linux Cookbook, 2nd Edition
NOTES: The whatis tool gets its descriptions from the manual page of a given
program; manual pages are described later in this section, in Recipe 2.8.4
[Reading a Page from the System Manual], page 46.
This command outputs some usage information about the whoami tool,
including a short description and a list of possible options.
NOTES: Not all tools take the --help option; some tools take a -h or -?
option instead, which performs the same function.
Use the man tool to view a page in the system manual. As an argument to
man, give the name of the program whose manual page you want to view (so
to view the manual page for man, you would type man man).
⇒ To view the manual page for w, type:
$ man w RET
Figure 2-2. Reading a man page.
Use the up and down arrow keys to move through the text. Press Q to
stop viewing the manual page and exit man. Since man uses less to display the
text, you can use any of the less keyboard commands to peruse the manual
page (see Recipe 9.1 [Perusing Text], page 211).
NOTES: Despite its name, a manual page does not always contain the com-
plete documentation for a program; it’s more like a quick reference card. It
usually has a short description of the program, and lists the options and argu-
ments it takes; some manual pages also include an example or a list of related
commands. (Sometimes, commands have very complete, extensive manual
pages, but more often, their complete documentation is found either in other
help files that come with it or in its Info documentation; these are the subjects
of the following two recipes.)
48 The Linux Cookbook, 2nd Edition
To prepare a man page for printing, see Recipe 25.3.4 [Preparing a Manual
Page for Printing], page 522.
This command starts info at the system’s “Top” menu, which shows some
of the info key commands and displays a list of available manuals, as in Figure
2-3.
Use the arrow keys to move through each “page” of information, called
an Info node. Nodes are arranged hierarchically. Every Info document has a
“Top” node, which is like the frontmatter and table of contents of a printed
book; it usually contains the name of the document and an Info menu with
links to its various chapters. A chapter node will contain a menu with links
for its sections and so on. Links to other nodes may also appear in the text
of any node, as cross references.
Links look the same in both menu items and cross references: an asterisk
(*), the name of the node it links to, and either one or two colon characters
(: or ::). To follow a link to the node it points to, move the cursor over any
part of the node name in the link and press RET.
Chapter 2: What Every Linux User Knows 49
Figure 2-3. Reading an Info node.
Press H to run a tutorial that describes how to use info. Press Q to
stop reading the documentation and exit the program. You can press these
buttons at any time you are in info.
To read Info documentation for a particular tool or application, give its
name as an argument to info; if no Info manual exists for that tool, info
displays the man page for that tool instead.
⇒ To read the Info documentation for the tar tool, type:
$ info tar RET
This command starts info and opens the Info file faq.info, beginning at
the top node in the file.
50 The Linux Cookbook, 2nd Edition
To read a specific node in an Info file, give the name of the node to display
in quotes as an argument to the -n option.
⇒ To read faq.info, an Info file in the current directory, beginning with
the node Text, type:
$ info -n 'Text' -f faq.info RET
NOTES: You can also read Info documentation directly from the Emacs editor;
type CTRL- H i while in Emacs to start the Emacs Info reader, and then
use the same commands as in the stand-alone info tool (see Recipe 10.1.1
[Getting Acquainted with Emacs], page 232).
The Emacs “incremental” search command, CTRL- S, also works in info;
it’s a very fast, efficient way to search for a word or phrase in an entire Info text
(like this entire book); see Recipe 14.9.1 [Searching Incrementally in Emacs],
page 352.
Some people use Info for everything; on Linux systems, Info is set up to
display a tool’s man page in Info, if the tool lacks Info documentation. So if a
foofoo tool doesn’t have any Info manual, typing info foofoo will give you
its man page.
subdirectory with the name of that package. For example, additional docu-
mentation for the hostname package is in /usr/doc/hostname, and documen-
tation for the passwd package is in /usr/doc/passwd. Most packages have a
file called README that usually contains relevant information. Often this file is
compressed as README.gz, in which case you can use zless instead of less.
The Linux Documentation Project (ldp) has overseen the creation of more
than 100 howto files, each of which covers a particular aspect of the instal-
lation or use of Linux-based systems.
The ldp howtos are compressed text files stored in the /usr/doc/HOWTO
directory; to view them, use zless. The file /usr/doc/HOWTO/HOWTO-
Index.gz contains an annotated index of all the howto documents installed
on the system.5
The /usr/doc/FAQ directory contains a number of faq (“Frequently Asked
Questions”) files on various subjects.
Finally, some distributions also keep a directory in /usr/doc for their own
documentation; Debian, for example, uses /usr/doc/debian for documen-
tation relating to that distribution: the files that make up the Debian faq
are in the /usr/doc/debian/FAQ directory, available in both html format,
which you can view in a Web browser (see Recipe 5.10 [Browsing Files and
Directories], page 157), and as a compressed text file, which you can view in
zless.
⇒ Here are two ways to use this.
• To view the html version of the Debian faq in the lynx Web
browser, type:
$ lynx /usr/doc/debian/FAQ/debian-faq.html RET
• To view the compressed text version of the Debian faq in zless,
type:
$ zless /usr/doc/debian/FAQ/debian-faq.txt.gz RET
NOTES: It’s often very useful to use a Web browser to browse through the
documentation files in these directories—see Recipe 5.10 [Browsing Files and
Directories], page 157.
5
ldp documents are available in other formats as well, including html and dvi.
52 The Linux Cookbook, 2nd Edition
Chapter 3: The Shell 53
3. The Shell
The subject of this chapter is the shell, the program that reads your command
input and runs the specified commands. It gets its name because it gives a
covering that protects you from the outer environment of the system, like the
hard protective encasements of the soft mollusks of the sea. The shell is the
intermediary between you and the system, and all interaction is done through
it; it is both your working environment and your interface. You are said to be
“in” a shell from the very moment you’ve successfully logged in to the system,
until right when you log out.
The “$” character preceding the cursor is called the shell prompt; it tells
you that the system is ready and waiting for input. On Debian systems,
the default shell prompt also includes the name of the current directory (see
Chapter 5 [Files and Directories], page 125). A tilde character (~) denotes
your home directory, which is where you’ll find yourself when you log in.
For example, a typical user’s shell prompt, when in his home directory,
might look like Figure 3-1.
~ $
Figure 3-1. A Bash shell promt.
If your shell prompt shows a pound sign (#) instead of a “$,” this means
that you’re logged in with the superuser, or root, account. Beware: The root
account has complete control over the system; one wrong keystroke and you
might accidentally break it something awful. You need to have a different user
account for yourself, which you use for your regular activities (see Recipe A.6.1
[Making a User Account], page 717).
You may sometimes hear the shell called the “command shell,” because
you run commands through it, but the shell isn’t just a prompt where you
run other programs—it is also a programming language. Its built-in facilities
for writing programs is very powerful. In this chapter, I will show you the
basics to get you started, but you should know that many books have been
written on shell programming.
There are many shells available for Linux. Some may look similar to each
other, but they can behave quite differently. We’re going to cover the Bash
shell, which is the most commonly used shell on Linux systems and is almost
always the default Linux shell. (Its name stands for “Bourne again shell”—a
pun on the name of Steve Bourne, who was author of the traditional unix
shell, the Bourne shell.)
54 The Linux Cookbook, 2nd Edition
NOTES: For more information on Bash’s command line editing features, con-
sult the Info documentation for bash (see Recipe 2.8.5 [Reading an Info Man-
ual], page 48).
Typing Commands
text Insert text at the point where the cursor is; any text
already existing to the right of the cursor is shifted
further right to accommodate the new text.
(continued)
Cutting and Pasting
CTRL- K Kill, or “cut,” all text on the input line, from the
character the cursor is underneath to the end of the
line.
CTRL- Y Yank, or “paste,” the text that was last killed. Text
is inserted where the cursor is.
Movement
CTRL- A Move the cursor to the beginning of the input line.
NOTES: These keyboard commands are the same as those used by the Emacs
editor (see Recipe 10.1 [Using Emacs], page 232). Many other Emacs keyboard
commands also work on the command line (see Recipe 10.1.3 [Using Basic
Emacs Editing Keys], page 237). And, for Vi aficionados, it is possible to
configure Bash to recognize Vi-style bindings instead (see Recipe 3.7.3 [Using
Shell Startup Files], page 86).
METHOD #1
To quote a reserved character, precede it with a backslash (\). The backslash
is Bash’s escape character; a character that immediately follows it will be
interpreted literally, and not for any reserved meaning. The one exception
to this rule is a newline character (see Recipe 3.1.12 [Typing a Long Line],
page 66).
⇒ Here are some ways to use this.
• To echo the string “Isn't this nice?,” type:
The last two examples use the special Bash variable HOSTNAME, whose value
is always the name of the current host (see Recipe 3.5 [Using Shell Variables],
page 77). First, the text “$HOSTNAME” is displayed because its “$” is escaped,
and then second, the $HOSTNAME variable is expanded to the value it contains.
In this example, the system’s hostname is lucky.
NOTES: For only one reserved character, this is the simplest quoting method;
while you certainly can quote any complex quotation this way, it is cumber-
some to add all the backslashes.
When passing a phrase to a command that takes multiple arguments, you
will have to escape spaces, too. So the phrase in the first example becomes
“Isn'\t\ this\ nice?”
METHOD #2
Quote a literal phrase by enclosing it in single quote characters ('). All charac-
ters inside the quotes are taken literally, and not for any reserved meaning—so
there’s no way to expand variables in single-quoted text. You can even quote
newlines with this method. The only character you can’t pass in single quotes
is a single quote itself.
58 The Linux Cookbook, 2nd Edition
METHOD #3
Quote a phrase by enclosing it in double quote characters (") to retain the spe-
cial meaning of some characters: the dollar sign ($), backtick (`), exclamation
point (!), and backslash (\).
This means that: Variables are expanded to their values (see Recipe 3.5
[Using Shell Variables], page 77), command output may be specified (see
Recipe 3.1.11 [Specifying the Output of a Command as an Argument],
page 65), command history may be referenced (see Recipe 3.4 [Using Your
Command History], page 74), and single characters may be escaped, as de-
scribed in Method #1 above.
You can pass single quote and newline characters; to pass double quotes,
dollar signs, backticks, or backslashes, escape them first with a backslash (\).
Pass an exclamation point by escaping it outside of the double quotes.
Chapter 3: The Shell 59
NOTES: You can sometimes get away with quoting an exclamation point in
double quotes, but because it’s reserved for referencing your Bash command
history, using it in the wrong context can have unexpected results. Unless
60 The Linux Cookbook, 2nd Edition
you’re only using the single quotes method, it’s safest to escape an exclamation
point outside of the double quotes.
METHOD #4
To pass special characters as a string, give them as $'string', where string is
the string of characters to be passed. This is called “ansi-c style” quoting.
Special backslash escape sequences for certain characters are commonly
included in a string, as listed in the following table.
$
Chapter 3: The Shell 61
1
The unix way of saying this is that the command “rings the system bell.”
62 The Linux Cookbook, 2nd Edition
Notice how by typing only the letter “e” followed by TAB twice brings up
a series of files, while “em” is completed to “emacs,” because all options in
this directory beginning with the letters “em” complete to at least that word.
The final two TAB completions were made without ringing the bell, meaning
that the completions made were the only possibilities.
NOTES: Many applications also support command and/or file name comple-
tion; the most famous example of this is the Emacs text editor (see Recipe 10.1
[Using Emacs], page 232).
This operation fixes the misspelled “frmo” with “from,” and so the input
line looks like this:
$ echo from
⇒ To transpose the words “bash” and “man,” type:
$ bash man ALT- T
This operation correctly forms the command to view the bash manual
page:
$ man bash
METHOD #1
To run more than one command on the input line, type each command in the
order you want them to run, separating each command from the next with a
semicolon (;). This is sometimes a quick way to run several non-interactive
commands in sequence.
⇒ Here are two ways to use this.
• To clear the screen and then log out of the system, type:
$ clear; logout RET
• To run the hostname command three times, type:
NOTES: There are many useful things you can do when combining commands
in this way. One popular use of this technique is to run sleep first and then
some other command next, to run that second command on a delay. This is
good for making screen shots in some other window (see Recipe 19.1.1 [Taking
a Screen Shot in X], page 441).
64 The Linux Cookbook, 2nd Edition
METHOD #2
You can also run a list of commands by putting them in a file, one per line.
Use the special “.” command, and give the name of the file as an argument.
This runs, in the current shell, all of the commands that are in the file.
⇒ To run the commands in the file ~/lists/nightly, type:
$ . ~/lists/nightly RET
NOTES: This method is good for running many commands with long argu-
ments. For example, you might want to run a tool that takes an url as an
argument, and you have a long series of such urls to run it on. Use a text
editor to copy the urls into a file, one on each line, and then insert the name
of the tool at the beginning of each line.
The built-in source command is a synonym for the period; the act of
running commands from a file with this method is often called “sourcing” a
file.
shell will run it and ignore the second command; if the first command doesn’t
exist, returns an error, or otherwise returns with a non-zero exit status, the
shell will run the second command.
⇒ To run either w or who, type:
$ w || who RET
In this example, if w exists and runs without errors, the shell will run it
and exit; otherwise, it will run who.
NOTES: You can nest substitutions, putting one substitution inside another
one.
METHOD #1
To substitute a command’s output, give the command enclosed in parentheses
and preceded by a dollar sign ($).
⇒ To locate any files on the system containing your username somewhere
in its name, type:
$ locate $(whoami) RET
METHOD #2
To substitute a command’s output, give the command enclosed in backtick
characters (`).
⇒ To locate any files on the system containing your username somewhere
in its name, type:
$ locate `whoami` RET
NOTES: This is the old-fashioned way of doing it. The backticks enclosing
any nested substitutions must be each preceded with backslash characters (\);
also use backslash to specify dollar sign or literal backslash characters.
$ ech\ RET
> o verylo\ RET
> ngwor\ RET
> d RET
verylongword
$
NOTES: It may not always look as tidy, but you can type a long command
without using this technique.
As with redirecting the standard output, there are two variations; 2>>
works just like 2> but it appends the standard error to a file, if the file already
exists.
⇒ To append the standard error of apropos shells to an existing file
command.error, type:
$ apropos shells 2>> command.error RET
Chapter 3: The Shell 69
To redirect both standard output and standard error to the same file, use
&> instead of the stdout and stderr operators.
⇒ To redirect the standard output and the standard error of apropos
shells to a file named commands, type:
$ apropos shells &> commands RET
NOTES: The &> operator overwrites pre-existing files; there is no &>> operator
for appending both stdin and stderr in such cases.
This redirects the standard output of the command apropos bash shell
shells to the standard input of the command less, which displays it on the
screen for perusal.
Use the -a option to append to the file, and not overwrite any existing
data.
To redirect to multiple files, string multiple tee commands together.
⇒ To write a copy of the output of apropos bash shell shells to a file
called shell.commands, append a copy of the output to a file named
command.suggestions, and peruse the output with less at the same
time, type (all on one line):
$ apropos bash shell shells | tee shell.commands | tee -a
command.suggestions | less RET
The shell assigns each job a unique job number. You can use it as an
argument to specify the job to commands. Do this by preceding the job
number with a percent sign (%).
To find the job number of a job you have running, list your jobs (see
Recipe 3.3.4 [Listing Your Jobs], page 73).
The following sections describe the various commands for managing jobs.
Type CTRL- Z to suspend or stop the foreground job—useful for when you
want to do something else in the shell and return to the current job later. The
job stops until you either bring it back to the foreground or make it run in
the background (see Recipe 3.3.3 [Putting a Job in the Foreground], page 73
and see Recipe 3.3.2 [Putting a Job in the Background], page 72).
For example, if you are reading a document in info, typing CTRL- Z will
suspend the info program and return you to a shell prompt where you can
do something else (see Recipe 2.8.5 [Reading an Info Manual], page 48). The
shell outputs a line giving the job number (in brackets) of the suspended job,
the text “Stopped” to indicate that the job has stopped, and the command
line itself, as shown here:
[1]+ Stopped info -f manual.info
In this example, the job number is 1 and the command that has stopped
is “info -f manual.info.” The + character next to the job number indicates
that this is the most recent job.
If you have any stopped jobs when you log out, the shell will tell you this
instead of logging you out, as in Figure 3-2.
$ logout RET
There are stopped jobs.
$
Figure 3-2. Stopped jobs when logging out.
At this point, you can list your jobs (see Recipe 3.3.4 [Listing Your Jobs],
page 73), stop any jobs you have running (see Recipe 3.3.5 [Stopping a Job],
page 73), and then log out.
72 The Linux Cookbook, 2nd Edition
To move a specific job to the foreground when you have multiple jobs in
the background, specify the job number as an option to fg.
⇒ To bring job 3 to the foreground, type:
$ fg %3 RET
$ jobs RET
[1]- Stopped apropos shell >shell-commands
[2]+ Stopped apropos bash >bash-commands
$
⇒ To run the cat tool and then interrupt it while it is running in the
foreground, type:
$ cat RET
CTRL- C RET
$
Use kill to interrupt (or “kill”) a background job, specifying the job
number as an argument.
⇒ To kill job number 2, type:
$ kill %2 RET
$ history RET
1 who
2 apropos shell >shell-commands
3 apropos bash >bash-commands
4 history
$
This command shows the contents of your command history file, listing one
command per line, each prefaced by its event number. Use an event number
to specify that event in your history (see Recipe 3.4.3 [Specifying a Command
from Your History], page 76).
If your history is a long one, this list will scroll off the screen, in which
case you may want to pipe the output to less in order to peruse it. It’s
also common to search for a past command by piping the output to grep (see
Recipe 3.2.4 [Redirecting Output to Another Command’s Input], page 69, and
Recipe 14.1 [Searching Text for a Word], page 333).
⇒ To search your history for the text “apropos,” type:
This command will show the events from your history containing the text
“apropos.” (The last line of output is the command you just typed.)
METHOD #1
You can use the Bash reverse-incremental search feature, CTRL- R, to search,
in reverse, through your command history. You’ll find this useful if you re-
member typing a command line with “foo” in it recently, and you wish to
repeat the command without having to retype it. Type CTRL- R followed by
76 The Linux Cookbook, 2nd Edition
the text foo, and the last command you typed containing “foo” appears on
the input line.
Like the Emacs command of the same name (see Recipe 14.9.1 [Searching
Incrementally in Emacs], page 352), this is called an incremental search be-
cause it builds the search string in character increments as you type. Typing
the string “cat” will search for (and display) the last input line containing a
“c,” then “ca,” and finally “cat,” as you type the individual characters of the
search string. Typing CTRL- R again retrieves the next previous command
line that has a match for the search string.
⇒ Here are two ways to use this.
• To put the last command you entered containing the string “grep”
back on the input line, type:
$ CTRL- R
(reverse-i-search)`': grep
• To put the third-to-last command you entered containing the string
“grep” back on the input line, type:
$ CTRL- R
(reverse-i-search)`': grep
CTRL- R CTRL- R
NOTES: When a command is displayed on the input line, type RET to run
it. You can also edit the command line as usual.
METHOD #2
You can also pipe your history through grep to output lines that match a
pattern (see Recipe 14.2 [Searching Text for a Phrase], page 334). This does
not put anything on the input line, but will give all the matches at once. You
might also want to pipe this output to a text pager such as less so you can
peruse it (see Recipe 9.1 [Perusing Text], page 211).
⇒ To peruse all the lines in your command history containing the text
“newfile,” type:
$ history | grep newfile | less RET
( ) takes you back through past events, and the down arrow key ( ) moves
you forward to more recent events. When a history event is on the input line,
you can edit it as normal, and type RET to run it as a command; it will then
become the newest event in your history.
⇒ To specify the second-to-last command in your history, type:
$
NOTES: The special event number “!” is the last event, so typing !! is another
way to run the last command you typed.
Values themselves may contain variables, which are then expanded when
the variable is assigned. You can use any quoting method to give the value,
and you can specify the output of a command (see Recipe 3.1.11 [Specifying
the Output of a Command as an Argument], page 65).
⇒ Here are two ways to use this.
• To give a variable called NAME a value of the contents of the
FIRSTNAME and LASTNAME variables, with a space between them, type:
$ NAME="$FIRSTNAME $LASTNAME" RET
• To give a variable called NAME a value of the output of the whoami
command, type:
$ NAME=`whoami` RET
To change the contents of an existing variable, just give its name as the
variable to use.
⇒ To assign a new value to an existing variable called NAME, type:
$ NAME="whoami" RET
$ $NAME RET
mary
$
Chapter 3: The Shell 79
In this example, the variable NAME is shown to contain the string “whoami.”
When you want to output other characters immediately after the name of
a variable, enclose the variable name in curly braces ({}), with the dollar sign
on the outside and immediately preceding it.
⇒ To display the contents of the variable NAME followed by the string “now,”
type:
Without the curly braces, it would have looked to the shell as though you
were referencing a variable called NAMEnow.
Since the replacement text has spaces in it, I’ve quoted it (see Recipe 3.1.3
[Quoting Reserved Characters], page 56).
You can put special characters in the prompt variable in order to output
special text. For example, the characters “\w” in the value of PS1 will list the
current working directory at that place in the shell prompt text.
⇒ To change your prompt to the default Bash prompt—the current working
directory followed by a “$” character—type:
The following table lists some special characters and their text output at
the shell prompt.
Chapter 3: The Shell 81
NOTES: See Chapter 5 [Files and Directories], page 125, for a complete de-
scription of directories and the path.
82 The Linux Cookbook, 2nd Edition
The MAIL variable contains the full pathname to your system mail file,
usually a directory in /var/spool/mail/ whose name is the same as your
username. This is where your incoming mail arrives on the system, and it is
the file that the shell checks to see if you have mail. When new messages are
written to this file, the shell will tell you, before giving you another input line,
that you have mail waiting. To turn off mail call, set MAIL to nothing.
⇒ To turn off mail call in the shell, type:
$ MAIL= RET
⇒ To see how many seconds the current shell has been running, type:
$ echo $SECONDS RET
NOTES: To find out how long the shell has been running in minutes, hours,
or some other unit of time, you can convert the number of seconds output
with units (see Recipe 29.5.1 [Converting an Amount between Units of Mea-
surement], page 567).
Once you see how an alias works, you might be tempted to make an alias
for everything. However, there are differences between aliases and scripts
(discussed in the next section) that you should know.
With an alias, the command you run will show up in your shell history
instead of the alias name you use to call it, whereas with a shell script, only
the name of the script will appear and not the commands in the script. Only
you can run an alias; a script, if it is put in a public bin directory, can be run
by everyone on the system.
Aliases are best for calling a tool, with or without options or arguments,
by another name. How to do that is shown below.
This command makes “bye” an alias for the exit tool in the current shell,
so typing bye would then run exit.
You can also include options and arguments in an alias. When you do, be
sure to enclose the entire alias in double quotes.
This command makes “ls” an alias for the ls file listing tool with its --
color=auto option specified, which sets color when the output is directed to
a terminal that is capable of displaying it.
This is a common alias, and many Linux systems come preconfigured with
it in the default .bashrc file. It’s also common to make “l” an alias for ls
with the -l option (see Recipe 5.3.3 [Listing File Attributes], page 136).
When you have this alias defined you can still pass other options to ls just
by specifying them; so typing ls -l in this case will execute ls --color=auto
-l as the actual command.
Aliases are always expanded before the shell looks on your path, so to run
a tool or program whose name is also an alias, give the full path name of
84 The Linux Cookbook, 2nd Edition
the program to run (see Chapter 5 [Files and Directories], page 125, for more
about the path).
⇒ To run the actual ls tool with the -l option when “ls” is already defined
as an alias for something, type:
$ /bin/ls -l RET
NOTES: When you define an alias, it only works in the current shell. To make
an alias work every time you run a shell, put it in your .bashrc startup file,
which is a hidden file in your home directory.
NOTES: If you set an alias in your .bashrc or .bash_profile file, this will
remove it—but only for the current shell. To remove such an alias from all
future sessions, edit the file where it is defined, and remove that particular
alias line.
#!/bin/sh
echo Hello, world
2. Use chmod to make the file executable:
$ chmod a+x hello RET
set (see Recipe 6.3.6 [Making a File Executable], page 170). Scripts can take
arguments, just like other kinds of programs.
If a script is stored in a directory that’s on your path (see Recipe 3.5.7
[Adding to Your Path], page 81), just type the name of the script to run it.
Otherwise, give the path name of the script, either full or relative, to run it
(full and relative path names are discussed in Chapter 5 [Files and Directories],
page 125).
⇒ Here are some ways to use this.
• To run a script called hello that is kept in a directory on your path,
type:
$ hello RET
• To run a script called hello that is kept in the current directory but
isn’t on your path, type:
$ ./hello RET
• To run a script called hello that is kept in the directory
~/input/files/new, type:
$ ~/input/files/new/hello RET
NOTES: To keep things neat, and to avoid having to call scripts by full path
names, you should consider keeping them in your own directory for binaries,
as described in Recipe C.1 [Using a Directory for Personal Binaries], page 727.
There are separate configuration files for login and all other shells so that
you can put specific customizations in your .bash_profile that only run
when you first log in to the system. To avoid having to put commands in
both files when you want to run the same ones for all shells, append the
following to the end of your .bash_profile file:
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
This makes Bash run the .bashrc file in your home directory when you
log in. In this way, you can put all of your customizations in your .bashrc
file, and they will be run both at log in and for all subsequent shells. Any
customizations before this line in .bash_profile run only when you log in.
For example, a simple .bash_profile might look like Figure 3-3, and a
simple .bashrc file, in turn, might look like Figure 3-4.
The .bash_profile in Figure 3-3 prints a welcome message with the
figlet text font tool (see Recipe 16.4.1 [Outputting Horizontal Text Fonts],
page 401), and then runs the user’s .bashrc file.
The .bashrc in Figure 3-4 sets a few useful command aliases and uses a
custom path and shell prompt whenever a new shell is run.
When you log out, Bash reads and executes the commands in the
.bash_logout file in your home directory, if it exists. To run commands
when you log out, put them in this file.
⇒ To clear the screen every time you log out, your .bash_logout should
contain the following line:
clear
This executes the clear command, which clears the screen of the current
terminal.
NOTES: Some distributions come with default shell startup files filled with all
kinds of interesting things. Debian users might want to look at the example
startup files in /usr/share/doc/bash/examples/startup-files.
The first and last lines of the file show the beginning and ending time and
date of the capture session. To stop recording the typescript, type exit at a
shell prompt. By default, typescripts are saved to a file called typescript in
the current directory; specify the file name as an argument.
⇒ To create a typescript of a shell session and save it to the file
log.19990525, type:
times. As a result, you may end up with multiple sessions “nested” inside
each other like a set of Russian dolls.
METHOD #1
To start another shell and return to your current shell later, just run the
new shell by giving the name of its command (the command to run Bash, for
example, is bash).
This will suspend your current shell and run the new shell; when you exit
the new shell, you will return to your old shell.
⇒ To run a new Bash shell, type:
$ bash RET
METHOD #2
To run a shell in place of your current shell, use exec. Give as an argument
the name of the command of the new shell you want to run. This stops your
current shell and replaces it with the new shell. If you run this command from
a login shell, then when you exit the new shell, you will be logged out.
NOTES: You can use exec to run any command in place of the current shell,
not just another shell.
Chapter 3: The Shell 91
You can also type CTRL- D at the shell prompt, which works as a shortcut
to the exit command.
⇒ To exit the current shell, type:
$ CTRL- D
NOTES: Exiting your login shell will log you out of the system (see
Recipe 2.2.2 [Logging Out of the System], page 31).
$ echo $0 RET
ksh
$
installed on the system.3 If you have second thoughts, just hit RET when it
asks—then, your login shell will not be changed.
⇒ To change your default shell to pdmenu, type:
$ chsh RET
Password: sesame RET
Changing the login shell for suzie
Enter the new value, or press return for the default
Login Shell [/bin/bash]: pdmenu RET
$
In this example, the user suzie with a password of “sesame” changed her
login shell to pdmenu, a shell described in the next recipe.
3
A list is kept at /etc/shells.
Chapter 3: The Shell 93
4.1 Running X
When you start X, you should see a mouse pointer appear on the screen as
a large, black “X.” If your X is configured to start any tools or applications,
they should each start and appear in individual windows. A very plain and
simple X session might look like Figure 4-1.
The root window is the background behind all of the other windows. It is
usually set to a color, but you can change it (see Recipe 4.7.3 [Changing the
1
Sometimes you might catch it being called “X Windows,” but this term is technically
incorrect.
96 The Linux Cookbook, 2nd Edition
Window managers typically allow you to customize the colors and borders
that are used to display a window, as well as the type and location of but-
tons that appear on the window (see Recipe 4.2 [Running a Program in X],
page 101). For example, in the image above, the clock itself is the oclock
program, while the title bar above it is drawn by the fvwm2 window man-
ager. With the AfterStep window manager, the title bar would look a little
different, as in Figure 4-2.
4.1.1 Starting X
There are two principal ways to start X. How you start it on your system will
depend on whether or not the X Display Manager is installed.
METHOD #1
Xdm
DEB: xdm
RPM: xdm
WWW: http://www.xfree86.org/
METHOD #2
On systems not running xdm, the virtual console reserved for X will be blank,
until you start X yourself by running startx in another virtual console. Mes-
sages from startx, including any error messages, are displayed in the console
you run it in, while X itself will run in the seventh virtual console.
⇒ Here are two ways to use this.
• To start X yourself from another virtual console, type:
$ startx RET
• To run startx and redirect both its standard output and standard
error to a log file, type:
$ startx &> ~/startx.log RET
Chapter 4: The X Window System 99
NOTES: If your system runs xdm, you can always switch to the seventh virtual
console (or whichever console xdm is running on), and then log in at the xdm
login screen.
4.1.2 Stopping X
There are a few methods for stopping X.
METHOD #1
The normal way to end an X session is to do it through your window manager.
Most window managers have an Exit X menu option or something similar that
you can select with the mouse; others have keystroke commands for exiting X.
3
A bit is the computer’s smallest unit of information, and can be either a binary 0 or 1;
pixels are the individual colored dots that make up your display screen.
100 The Linux Cookbook, 2nd Edition
• To end your X session if you are running the fvwm2 window man-
ager, do the following:
1. Click the left mouse button anywhere in the root window to pull
up the start menu.
2. Choose Really quit? from the Exit Fvwm submenu.
• To end your X session if you are running the AfterStep window man-
ager, do the following:
1. Click the left mouse button anywhere in the root window to pull
up the start menu.
2. Choose Exit? from the Quit submenu.
3. Click Logout.
• To end your X session if you are running the Ion window manager,
do the following:
1. Press F12.
If you started your X session with startx, these commands will return you
to a shell prompt in the virtual console where the command was typed. If,
on the other hand, you started your X session by logging in to xdm on the
seventh virtual console, you will be logged out of the X session and the xdm
login screen will appear; you can then switch to another virtual console or log
in to X again.
METHOD #2
To exit X immediately and terminate all X processes, press the CTRL- ALT-
BKSP combination (if your keyboard has two ALT and CTRL keys, use the
left ones). You’ll lose any unsaved application data, but this is useful when
you cannot exit your X session normally—in the case of a system freeze or
other problem.
⇒ To exit X immediately, type:
CTRL- ALT- BKSP
Chapter 4: The X Window System 101
METHOD #1
Most window managers have a “start menu” of some kind; it’s usually accessed
by clicking the left mouse button anywhere on the root window. To run an X
client from the start menu, click the left mouse button to select the client’s
name from the submenus.
⇒ To start a square-shaped, analog-face clock from the start menu, do the
following:
1. Click the left mouse button on the root window to make the menu
appear.
2. Click the left mouse button through the application menus and onto
Xclock (analog).
This starts the xclock client, specifying the option that displays an analog
face, as in Figure 4-3.
METHOD #2
You can also start a client by running it from a shell window—useful for
starting a client that isn’t on the menu, or for when you want to specify
options or arguments. When you run an X client from a shell window, the
102 The Linux Cookbook, 2nd Edition
client opens in its own window, but runs as a foreground job in that shell;
to use the shell window while the client is running, run the client in the
background (see Recipe 3.3.2 [Putting a Job in the Background], page 72).
⇒ To run a digital clock from a shell window, type:
$ xclock -digital & RET
You can give positive or negative numbers for the XOFF and YOFF fields.
Positive XOFF values specify a position from the left of the screen; negative
values specify a position from the right. If YOFF is positive, it specifies a
position from the top of the screen; if negative, it specifies a position from the
Chapter 4: The X Window System 103
bottom of the screen. When giving these offsets, you must specify values for
both XOFF and YOFF.
To place the window in one of the four corners of the desktop, use zeroes
for the appropriate XOFF and YOFF values, as follows:
Or, to put it all together, you can specify the size and location of a window
with one geometry line that includes all four values.
⇒ To start an xclock with a width of 120 pixels, a height of 100 pixels, an
x-offset of 250 pixels from the right side of the screen, and a y-offset of
25 pixels from the top of the screen, type:
$ xclock -geometry 120x100-250+25 RET
to the appropriate option: -bg for background color, -bd for window border
color, and -fg for foreground color.
⇒ To start an xclock with a light blue window background, type:
$ xclock -bg lightblue RET
⇒ To display an X client’s third menu, press and hold CTRL, move the
mouse pointer to somewhere in the X client’s window, and click the third
mouse button.
NOTES: If the idea of maximizing all your X client windows appeals to you, I
suggest looking at Ion, a window manager with no real concept of “windows”
at all, but only clients running maximized to full-screen size (see Recipe 4.7.5
[Using Other Window Managers], page 120).
Chapter 4: The X Window System 107
NOTES: Some window managers may have slightly different variations on this
method, but the basic principle will be the same.
$ xwininfo RET
2. Click the left mouse button anywhere in the window you’d like in-
formation on.
This command outputs, in the terminal window you typed it in, a list of
information on the client window you selected with the mouse.
the lower right-hand corner of your screen, even when you scroll across a vir-
tual desktop. Both your current desktop and active X client are highlighted
in the pager.
The default fvwm2 virtual desktop size is nine desktops in a 3x3 grid, as
in Figure 4-5.
A terminal emulator lets you run a shell in an X client window. The standard
terminal emulator for X on Linux systems is xterm, which emulates the dec
110 The Linux Cookbook, 2nd Edition
vt102/220 and Tektronix 4014 video terminals.4 You can run commands
in an xterm window just as you would in a virtual console; a shell in an
xterm acts the same as a shell in a virtual console (see Chapter 3 [The Shell],
page 53).
You can use all of the standard X client options with xterm (see Recipe 4.2
[Running a Program in X], page 101), but it also has many options of its own,
which are described in the next recipe.
⇒ To open a new window with a shell, setting the text font to Lucida Sans
Typewriter face at a body size of 18 pixels, type:
$ xterm -fn lucidasanstypewriter-18 RET
This example requires that you already have a terminal emulator running,
with a shell prompt you can type from. If you don’t have one, then you will
have to start an xterm by selecting it from an application menu, as provided
through your window manager.
⇒ To open a new window with a shell when using the Ion window manager,
setting the text font to Lucida Sans Typewriter face at a body size of 18
pixels, type:
F3
Run: xterm -fn lucidasanstypewriter-18 RET
You can cut and paste text from an xterm to another X client (see
Recipe 10.3 [Manipulating Selections of Text], page 253).
To scroll through text that has scrolled past the top of the screen, type
SHIFT- PgUp. The number of lines you can scroll back to depends on the
value of the scrollback buffer, specified with the -sl option; its default value
is 64.
4
To see what the original hardware looks like, see the following:
http://www.cs.utk.edu/~shuford/terminal/dec.html and
http://www.cs.utk.edu/~shuford/terminal/various.html#tek.
Chapter 4: The X Window System 111
There are even more options than this; consult the xterm man page for a
complete listing (see Recipe 2.8.4 [Reading a Page from the System Manual],
page 46).
the name of the command to run as an argument. An xterm will open with
that command, and it will run in its own window; when that command exits,
the xterm window will close. This is handy for when you just want to run a
particular command in its own window, but don’t need a shell.
⇒ To run bc in its own X window, type:
$ xterm -e bc RET
When you exit the command, the shell will exit and the window will close.
You can also pass arguments to the command.
⇒ To run lynx with the url file:/usr/local/, type:
$ xterm -e lynx file:/usr/local/ RET
In this example, lynx opens the given url in its own window, and will
remain until you either kill the window or exit lynx.
NOTES: If calling xterm with other options, the -e option must be the last
option specified in the command line.
AfterStep This color vt102 terminal emulator was made to work with
XVT the AfterStep window manager, but can also be used with oth-
ers; has many special effects such as tinting and shading, yet is
smaller than xterm—and uses less swap space, too.
DEB: aterm
RPM: aterm
WWW: http://aterm.sourceforge.net/
Enlightened This color vt102 terminal emulator was made to work with
Terminal the Enlightenment window manager, but can also be used with
Emulator others; supports themes and has many features to control its
appearance.
DEB: eterm
RPM: Eterm
WWW: http://www.eterm.org/
Chapter 4: The X Window System 115
Konsole This graphical terminal emulator for kde allows you to run
multiple terminals in a single window.
DEB: konsole
RPM: konsole
WWW: http://konsole.kde.org/
Multi This graphical terminal emulator for gnome features enhance-
Gnome ments inspired by Konsole, that allow for multiple terminals in
Terminal a single window.
DEB: multi-gnome-terminal
RPM: multi-gnome-terminal
WWW: http://multignometerm.sourceforge.net/
Multi As the name implies, this terminal emulator supports various
Lingual foreign language encodings.
TERMinal DEB: mlterm
RPM: mlterm
WWW: http://mlterm.sourceforge.net/
PowerShell This color terminal emulator allows multiple terminals in the
same window that you can switch between by clicking on “tab”
buttons.
DEB: powershell
RPM: powershell
WWW: http://powershell.sourceforge.net/
ouR XVT Known to everyone by its command name, rxvt, this is a color
vt102 terminal emulator designed to be a xterm replacement,
and is smaller and less memory-intensive as the latter, but with
less emulation options and configurability.
DEB: rxvt
RPM: rxvt
WWW: http://sourceforge.net/projects/rxvt/
Unicode This is xterm with Unicode support.
DEB: xterm
RPM: xterm
WWW: http://dickey.his.com/xterm/
116 The Linux Cookbook, 2nd Edition
Wterm This is based on ouR XVT, but optimized for the Window
Maker window manager. Its features include tranparency, tint-
ing, and background images.
DEB: wterm
RPM: wterm
WWW: http://largo.windowmaker.org/files.php#wterm
Click Close or type Q to exit the program and close the magnified win-
dow.
4.7 Configuring X
There are some aspects of X that people usually want to configure right away.
This section discusses some of the most popular, including changing the video
mode, automatically running clients at startup, and choosing a window man-
ager. You’ll find more information on this subject in both The X Window
Chapter 4: The X Window System 117
User HOWTO and The Configuration HOWTO (for how to read them, see
Recipe 2.8.6 [Reading System Documentation and Help Files], page 50).
To cycle through all available modes, type either of these key combinations
repeatedly.
NOTES: For more information on video modes, see The XFree86 Video Tim-
ings HOWTO (see Recipe 2.8.6 [Reading System Documentation and Help
Files], page 50).
#! /bin/sh
#
# A sample .xsession file.
To change the root window pattern, use the -bitmap option, and give the
name of the bitmap file to use.
⇒ To tile the root window with a star pattern, type:
$ xsetroot -bitmap /usr/X11R6/include/bitmaps/star RET
When specifying a pattern, use the -fg and -bg options to specify the
foreground and background colors.
⇒ To tile the root window with a light slate gray star pattern on a black
background, type (all on one line):
$ xsetroot -fg slategray2 -bg black -bitmap
/usr/X11R6/include/bitmaps/star RET
Chapter 4: The X Window System 119
Use xsetroot with the special -gray option to change the root window to
a shade of gray designed to be easy on the eyes, with no pattern.
⇒ To make the root window a gray color with no pattern, type:
$ xsetroot -gray RET
NOTES: You can also put an image in the root window (although this con-
sumes memory that could be spared for a memory-hogging Web browser in-
stead; but see Recipe 17.1.2 [Putting an Image in the Root Window], page 410,
for how to do it).
To try one of these window managers out, select it from the application
menu as given by the current window manager. This will exit your window
122 The Linux Cookbook, 2nd Edition
manager and start the new one. If you find one you like and wish to make it the
default, edit your .xsession file so that its last line contains exec followed by
the full path name of the window manager to use (see Recipe 4.7.2 [Running
X Clients Automatically], page 117).
⇒ To make AfterStep your default window manager, put the following as
the last line in your .xsession file:
exec /usr/bin/X11/afterstep
NOTES: Some window managers (such as twm and wm2) do not have ap-
plication menus, so if you run such a window manager you won’t be able to
easily switch to another during that session—you’ll have to exit X and start
it again.
II. FILES 123
II. FILES
124 The Linux Cookbook, 2nd Edition
Chapter 5: Files and Directories 125
Each user has a branch in the /home directory for his own files, called
his home directory. The hierarchy in the previous illustration has two home
directories: joe and jon, both subdirectories of /home.
dict
bin
usr
jon
play
work
joe
home
bin
etc
(root)
file you want to specify. This unique, specific path from the root directory to
a file is called the file’s full path name. (When referring to a file that is not a
directory, this is sometimes called the absolute file name).
You can specify any file or directory on the system by giving its full path
name. A file can have the same name as other files in different directories
on the system, but no two files or directories can share a full path name.
For example, user joe can have a file schedule in his /home/joe/work di-
rectory and a file schedule in his /home/joe/play directory. While both
files have the same name (schedule), they are contained in different direc-
tories, so each has a unique full path name—/home/joe/work/schedule and
/home/joe/play/schedule.
However, you don’t have to type the full path name of a tool or application
in order to start it. The shell keeps a list of directories, called the path, where
it searches for programs. If a program is “in your path,” which means that it
is in one of these directories, you can run it simply by typing its name.
By default, the path includes /bin and /usr/bin. For example, the who
command is in the /usr/bin directory, so its full path name is /usr/bin/who.
Since the /usr/bin directory is in the path, you can type who to run
/usr/bin/who, no matter what the current working directory is.
The following table describes some of the standard directories on Linux
systems.
1
Technically, there are other characters that you can use—but doing so may get you into
trouble later on.
130 The Linux Cookbook, 2nd Edition
The file name before any file extensions, but without the path, is called the
base file name. For example, the base file name of /home/lisa/house.jpeg
is house, without the dot or trailing jpeg, and without the path.
For a list of commonly used file extensions and their meanings, see Appen-
dix B [Conventional File Name Extensions], page 723.
The following sections show how to make new files. To rename an existing
file, just move it to a file with the new name—see Recipe 5.5 [Moving Files
and Directories], page 144.
This tool “touches” the files you give as arguments. If a file does not exist,
it creates it; if the file already exists, it changes the modification timestamp
on the file to the current date and time, just as if you had used the file.
NOTES: Often, you make a file when you edit it, such as with a text or image
or sound editor; in that case, you don’t need to make the file first.
METHOD #1
To use a file with space in its name, enclose the file in single-quote characters
(').
⇒ To list the contents of the directory named Top Secret, type:
$ ls 'Top Secret' RET
You can also use double quote characters (") to quote; if a file name con-
tains one kind of quote in its name, use the other.
⇒ To list the contents of the directory named McHale's Restuarant, type:
$ ls "McHale's Restaurant" RET
132 The Linux Cookbook, 2nd Edition
METHOD #2
To use a file with space characters in its name, precede each space character
with a backslash character (\).
⇒ To change to the directory named Newspaper Photo Archive, type:
$ cd Newspaper\ Photo\ Archive RET
In this example, rm was called with the -i option, which removes files
interactively, asking for confirmation before each remove takes place (see
Recipe 5.6.2 [Removing Files Interactively], page 150).
NOTES: If you don’t want spaces in a file, but you would like the words in
its name to be separated, you might change the spaces in the file name to
underscore characters (_). This is a common unix convention.
$ pwd RET
/home/mrs
$
In this example, pwd output the text /home/mrs, indicating that the current
working directory is /home/mrs.
$ ls RET
apple cherry orange
$
134 The Linux Cookbook, 2nd Edition
In the first example, the current working directory contains three files:
apple, cherry, and orange.
The following subsections describe some commonly used options for con-
trolling which files ls lists, and what information about those files ls outputs.
You can combine these options to get their combined effects; the order in which
the options are specified does not matter. There are even more options than
what is given here; the Info documentation for ls is worth perusing. It is one
of the most often used file commands on unix-based systems.
NOTES: There are a few other common ways to list the contents of directories.
One that is common when in X, and when you want to peruse image files in
those directories, is to use Mozilla or some other Web browser as a local file
browser. Use the prefix2 file:/ to view local files. Alone, it opens a directory
listing of the root directory; file:/home/joe opens a directory listing of
user joe’s home directory, file:/usr/local/src opens the local source code
directory, and so on. Directory listings will be rendered in html on the fly
in almost all browsers, so you can click on subdirectories to traverse to them,
and click on files to open them in the browser. This and other methods for
browsing files are described in Recipe 5.10 [Browsing Files and Directories],
page 157.
This command lists the root directory in color, as in Figure 5-2. (While
this illustration is black and white, the actual directory listing is in color.)
2
Called a urn, or “Uniform Resource Name.”
Chapter 5: Files and Directories 135
Figure 5-2. A color directory listing.
NOTES: Many systems are set up to use this flag by default, so that using ls
with no options will list in color. If yours isn’t set up this way, and you’d like
it to be, you can always make ls a shell alias word for ls --color in your
.bashrc startup file (see Recipe 3.6.1 [Calling a Command by Some Other
Name], page 83 and see Recipe 3.7.3 [Using Shell Startup Files], page 86).
/ File is a directory.
* File is executable.
@ File is a symbolic link (see Recipe 5.7 [Giving a File
More Than One Name], page 152).
| File is a fifo (also called a named pipe), a special
file that processes use for reading from and writing
to.
= File is a socket, a special file that provides a
connecting point through which processes may
communicate.
136 The Linux Cookbook, 2nd Edition
$ ls -F RET
repeat* test1 test2 words/
$
second column lists the number of hard links to the file. The third and fourth
columns give the names of the user and group that the file belongs to. The
fifth column gives the size of the file in bytes, the sixth column gives the date
of last modification, and the last column gives the file name.
Other options change the defaults for the long-style output.
To change the modification date from the abbreviated month, day, and
then year output to show the full time and date (like the default of date, as
described in see Recipe 27.1 [Displaying the Date and Time], page 537), use
the special --full-time option.
⇒ To output a verbose listing of the /usr/share/doc/bash directory, giving
the full time and date of last modification, type:
$ ls -l --full-time /usr/share/doc/bash RET
This command outputs a verbose listing of the files in the
/usr/share/doc/bash directory, showing the full time and date of
last modification, as in Figure 5-4.
Use the -A option to list almost all files in the directory: it lists all files,
including dot files—with the exception of the .. and . directory files.
⇒ To list all files in the current directory except for .. and ., type:
$ ls -A RET
When output from ls is piped to anywhere but the terminal, ls uses this
single-column format.
Normally, ls lists files in columns going vertically—first the leftmost col-
umn will be filled, and then the next column, all the way over toward the right
side of the screen. Use -x to make the columns list horizontally instead—so
that the first line across is filled with file names first, and then the next line,
until all files are listed.
Chapter 5: Files and Directories 139
Use the -m option to output files not in columns at all, but in a single
horizontal line, separated by commas.
⇒ To output the contents of /usr/bin in a single line, with file names
separated by commas, type:
$ ls -m /usr/bin RET
METHOD #1
To sort files by size, use the -S option. Files are sorted with the largest first.
⇒ To list all of the files in the /usr/bin directory sorted by size, with the
largest first, type:
$ ls -S /usr/bin RET
METHOD #2
Use the -t option with ls to sort a directory listing by time, so that the files
are listed according to when they were last modified, with the most recently
modified listed first.
⇒ To list all of the files in the /usr/tmp directory sorted by their modifica-
tion time, with the mostly recently modified files first, type:
$ ls -t /usr/tmp RET
METHOD #3
To sort files by their extension, use the -X option. Files with no extension are
listed first.
⇒ To list all files in the current directory, sorted by extension, type:
$ ls -X RET
140 The Linux Cookbook, 2nd Edition
METHOD #4
Use -v to give a version sort, where instead of sorting by character, the
file names are sorted by the way they are numbered, so that file-2 will
come between file-1 and file-10, and not after the two files as it would
in a normal character sort. This is useful for sorting files whose names are
numbered in some way, such as by versions, indices, or date.
⇒ To list all of the files in the current directory ending in .jpeg and sorted
by version, type:
$ ls -v *.jpeg RET
METHOD #5
Use -r to reverse the order of the sorted output. This works with all other
sort options.
⇒ Here are some ways to use this.
• To list files in the current directory from highest ascii character
value to lowest, type:
$ ls -r RET
• To list all of the files in the /usr/bin directory sorted by their size,
with smallest files first, type:
$ ls -Sr /usr/bin RET
• To list all of the files in the current directory sorted by modification
date, with the most recently modified files last, type:
$ ls -tr RET
METHOD #6
Use the -U option to turn off all sorting and output files in unsorted order—the
order they appear on the disk.
⇒ To output all files in the current directory in the order they appear on
the disk, type:
$ ls -U RET
$ ls -R RET
play work
play:
notes
work:
notes
$
This command recursively lists the contents of the root directory, /, and all
of its subdirectories. It is common to combine this with the attribute option,
-l, to output a verbose listing of all the files on the system:
$ ls -lR / RET
NOTES: You can’t list the contents of some directories on the system if you
don’t have permission to do so (see Recipe 6.3 [Controlling Access to Files],
page 167).
This command copies the file my-copy to a new file called neighbor-copy
that is identical to my-copy in every respect except for its name.
While -p does not copy any subdirectories a directory may contain, you
can use the -a (“archive”) option instead, which preserves attributes when-
ever possible but also copies any subdirectories as well as symbolic links (see
Recipe 5.7 [Giving a File More than One Name], page 152). This is good for
making archival backups of one directory tree to another.
⇒ To make an archival copy of the contents of /cdrom to the current direc-
tory, type:
$ cp -a /cdrom . RET
The -R option does not copy files that are symbolic links (see Recipe 5.7
[Giving a File More Than One Name], page 152), and it does not retain all
original permissions. To recursively copy a directory, including links, and
retain all of its permissions, use the -a (“archive”) option. This is useful for
making a backup copy of a large directory tree.
⇒ To make an archive copy of the directory tree public_html to the direc-
tory private_html, type:
$ cp -a public_html private_html RET
~/photographs/01/
~/photographs/01/640x480
~/photographs/01/320x280
~/photographs/01/src
~/photographs/02
~/photographs/02/640x480
~/photographs/02/320x280
~/photographs/02/src
~/photographs/03
~/photographs/03/640x480
~/photographs/03/320x280
~/photographs/03/src
... continued ...
Figure 5-6. Subdirectories with a unique parent.
⇒ To copy all src directories to the /mnt directory, giving each of the files
the unique name of their parent directory in ~/photographs, type:
NOTES: To rename files by this method, use mv instead of cp (see Recipe 5.5
[Moving Files and Directories], page 144).
⇒ To move the file notes in the current working directory to ../play, type:
$ mv notes ../play RET
This command moves the file notes in the current directory to play, a
subdirectory of the current working directory’s parent. If a file notes already
exists in play, that file is overwritten. If the subdirectory play does not exist,
this command moves the file notes from the current directory to its parent
directory, renaming the file play.
To move a file or directory that is not in the current directory, give its full
path name as an argument.
⇒ To move the file /usr/tmp/notes to the current working directory, type:
$ mv /usr/tmp/notes . RET
This command moves the file /usr/tmp/notes to the current working di-
rectory.
To move a directory, give the path name of the directory you want to move
and the path name to move it to as arguments.
⇒ To move the directory work in the current working directory to play,
type:
$ mv work play RET
This command moves the directory work in the current directory to the
directory play. If the directory play already exists, mv puts work inside
play—it does not overwrite directories.
Renaming a file is the same as moving it; just specify as arguments the file
to rename followed by the new file name.
⇒ To rename the file notes to notes.old, type:
$ mv notes notes.old RET
The following recipes describe other ways to move and rename files.
METHOD #1
Use the rename tool, which comes as a part of the perl programming lan-
guage, to rename groups of files. It takes two arguments: a quoted perl
expression describing the change to make, and the files to make the change
146 The Linux Cookbook, 2nd Edition
on. If a file already exists, rename will output a warning and will not rename
the file, but other files will be renamed.
To use rename to change uppercase letters in file names to lowercase, use
tr/A-Z/a-z/ as the expression.
⇒ To change the file names of all of the files in the current directory to
lowercase letters, type:
$ rename 'tr/A-Z/a-z/' * RET
You can specify which files to work on, and you can specify that only
certain parts of a filename are to be changed.
⇒ Here are some ways to use this.
• To rename all of the files in the current directory ending with .MP3
to files of the same names in lowercase letters, type:
$ rename 'tr/A-Z/a-z/' *.MP3 RET
• To rename all of the files in the current directory ending with .MP3
to files of the same names with extensions in lowercase letters, type:
$ rename 's/.MP3/.mp3/' *.MP3 RET
In the first example, a file with a name like Music-Recording.MP3
or ANOTHER-MUSIC-RECORDING.MP3 would be renamed to music-
recording.mp3 and another-music-recording.mp3, while in the second
example, these files would be renamed to Music-Recording.mp3 and
ANOTHER-MUSIC-RECORDING.mp3.
METHOD #2
To change the uppercase letters in a group of file names to lowercase, use mv
with the -i option to move the files interactively, deriving lowercase file names
by piping the old names through the tr filter (see Recipe 13.4 [Transposing
Characters in Text], page 316). Loop through all the files in the first extension,
running this command line on each of them, with Bash’s built-in for construct
(see the bash Info documentation for more information on this built-in).
⇒ To rename all of the files in the current directory to all lowercase letters,
type:
$ for i in * RET
> { RET
> mv -i $i `echo $i | tr '[A-Z]' '[a-z]'` RET
> } RET
$
Chapter 5: Files and Directories 147
You can use the semicolon character (;) to run this all on one command line
as a single command. The following command is equivalent to the preceding
example:
for i in *; { mv -i $i `echo $i | tr '[A-Z]' '[a-z]'`; }
The -i option is used with mv because otherwise this command may in-
advertently remove files—if, for example, you have files named CAT, Cat, and
cat, this command without the -i will remove two of them.
Furthermore, for files that are not affected by the transformation to low-
ercase (for example, a file named dog), this command will do nothing, and a
message will be output indicating that the original file name and the new file
name are the same.
⇒ To lowercase all of the file names in the current directory that have a
.JPG extension, type:
$ for i in *.JPG; { mv -i $i `echo $i | tr '[A-Z]' '[a-z]'`; } RET
METHOD #1
Use the rename tool, which comes as a part of the perl programming lan-
guage. It takes two arguments: a quoted perl expression describing the
change to make, and the files to make the change on.
148 The Linux Cookbook, 2nd Edition
⇒ To rename all the files in the current directory ending in .JPG to files
ending in .jpeg, type:
$ rename 's/.JPG/.jpeg/' *.JPG RET
METHOD #2
Use mv to move the files, deriving the new file names with the basename tool.
Loop through all of the files, running this command line on each of them,
with Bash’s built-in for construct (see the bash Info documentation for more
information on this built-in).
⇒ To rename all the files in the current directory then end in .JPG to files
that end end in .jpeg, type:
You can use the semicolon character (;) to run these commands on one
command line. The following command is equivalent to the previous example:
for i in *.JPG; { mv -i $i `basename $i JPG`jpeg; }
METHOD #3
To rename a group of files from one extension to another, use mv with a for
loop, as with Method #2, but instead of using basename, specify the new
extension with the Bash shell parameter expansion feature.3
⇒ To rename all of the .jpg files in the current directory, so that they all
have a .jpeg file name extension instead, type:
3
For more information on this feature, consult the Info documentation for bash (see
Recipe 2.8.5 [Reading an Info Manual], page 48).
Chapter 5: Files and Directories 149
METHOD #1
One way is to use tab completion to complete the name of the file (see
Recipe 3.1.4 [Letting the Shell Complete What You Type], page 61). This
works when the name of the file you want to remove has enough characters to
uniquely identify it so that completion can work.
⇒ To use tab completion to remove the file No Way in the current directory,
type:
$ rm No TAB Way RET
In this example, once TAB was typed, the shell filled in the rest of the file
name (“ Way”).
150 The Linux Cookbook, 2nd Edition
METHOD #2
When a file name begins with a control character or other strange character,
you can specify the file name with a file name pattern that uniquely identifies
it (see Recipe 5.8 [Specifying File Names with Patterns], page 153, for tips on
building file name patterns). Use the -i option to verify the deletion first.
⇒ To delete the file ^Acat in a directory that also contains the files cat and
dog, type:
$ rm -i ?cat RET
rm: remove `^Acat'? y RET
$
In the preceding example, the expansion pattern “?cat” matches the file
^Acat and no other files in the directory. The -i option was used because,
in some cases, no unique pattern can be made for a file—for example, if this
directory also contained a file called 1cat, the preceding rm command in the
example would also attempt to remove it; with the -i option, you can answer
n to it.
METHOD #3
The two previous methods won’t work with a file that begins with a hyphen
character, because rm interprets such a file name as an option; to remove a
file like that, use the -- option—it specifies that what follows are arguments
and not options.
⇒ To remove the file -cat from the current directory, type:
$ rm -- -cat RET
#!/bin/sh
/bin/rm -i $*
NOTES: Question 3.6 in the unix faq4 discusses this issue and gives a shell
script called can that you can use in place of rm—it puts files in a “trash-
can” directory instead of removing them; you then periodically empty out the
trashcan with rm.
4
See the file /usr/doc/FAQ/unix-faq-part3, or on the Web:
http://www.faqs.org/faqs/unix-faq/faq/.
152 The Linux Cookbook, 2nd Edition
METHOD #1
Use ln (“link”) to make a link to a file. Give as arguments the name of the
existing file to link to and the name to use for the link. By default, ln makes
hard links.
Chapter 5: Files and Directories 153
This command makes a hard link from an existing file, seattle, to a new
file, emerald-city. You can read and edit the emerald-city file just as
you would seattle; any changes you make to emerald-city are also written
to seattle (and vice versa). But if you remove the emerald-city file, the
seattle file is not removed (and vice versa).
METHOD #2
To create a symbolic link, use ln with the -s option.
⇒ To create a symbolic link from seattle to emerald-city, type:
$ ln -s seattle emerald-city RET
Brackets also have special meaning when used in conjunction with other
characters, as described in the following table.
• To remove all files in the current working directory that begin with
a hyphen and have the text “out” somewhere else in their file name,
type:
$ rm -- -*out* RET
• To concatenate all files whose names consist of an “a” character
followed by two or more characters, type:
$ cat a??* RET
Use tree to output an ascii text tree graph of a given directory tree.
⇒ To output a tree graph of the current directory and all its subdirectories,
type:
$ tree RET
.
|-- projects
| |-- current
| `-- old
| |-- 1
| `-- 2
`-- trip
`-- schedule.txt
4 directories, 3 files
$
In the preceding example, a tree graph is drawn showing the current di-
rectory, which contains the two directories projects and trip; the projects
directory in turn contains the directories current and old.
To output a tree graph of a specific directory tree, give the name of that
directory tree as an argument.
Chapter 5: Files and Directories 157
⇒ To output a tree graph of your home directory and all its subdirectories,
type:
$ tree ~ RET
NOTES: Another tool for outputting directory trees is described in Recipe 24.2
[Listing a File’s Disk Usage], page 502.
METHOD #1
Midnight Commander
DEB: mc-common
mc
RPM: mc
WWW: http://www.ibiblio.org/mc/
The easiest method for browsing files on your system is to use a “file manager”
tool that was made for that purpose. There are at least a few on Linux, aside
from the file managers that are part of gnome and kde5 ; the most popular
stand-alone file manager is probably the venerable “Midnight Commander.”
Type mc to run it. Give as an argument the name of a directory to browse,
either relative to the current directory or with its full path name. If you give
none, mc will use the current working directory.
⇒ To browse the /usr/local/ directory with the Midnight Commander,
type:
$ mc /usr/local RET
5
Nautilus and Konqueror, respectively.
158 The Linux Cookbook, 2nd Edition
METHOD #2
Lynx
DEB: lynx
RPM: lynx
WWW: http://lynx.browser.org/
You can view and peruse local files in a Web browser, such as the text-only
browser lynx or the graphical Mozilla browser for X.
The lynx tool is very good for browsing files on the system—give the name
of the directory to browse as an argument, and lynx will display a listing of
available files and directories in that directory.
Chapter 5: Files and Directories 159
You can use the cursor keys to browse and press RET on a subdirectory
to traverse to that directory.6 You can use lynx to display plain text files,
compressed text files, and files written in html; it’s useful for browsing system
documentation in the /usr/doc and /usr/share/doc directories, where many
software packages come with help files and manuals written in html.
Use the -localhost option to disable any urls that point to remote hosts.
⇒ Here are two ways to use this.
• To browse the system documentation files in the /usr/doc directory,
disabling all links to other hosts, type:
$ lynx -localhost /usr/doc RET
• To browse the files and subdirectories in the current directory, type:
$ lynx . RET
An illustration of what Lynx looks like when browsing the root directory
of a typical system is given in Figure 5-8.
6
In X, you can also use the mouse; see Recipe 33.2.8 [Using Lynx with a Mouse], page 648.
160 The Linux Cookbook, 2nd Edition
METHOD #3
Mozilla
DEB: mozilla-browser
RPM: mozilla
WWW: http://www.mozilla.org/
Use Mozilla to browse files much as with Lynx as described in Method #2,
giving a full path name as an argument.
⇒ To browse the system documentation files in the /usr/share/doc direc-
tory in Mozilla, type the following in Mozilla’s Location window, or give
it as an argument to mozilla:
/usr/share/doc
An illustration of what Mozilla looks like when browsing the root directory
of a typical system is given in Figure 5-9.
NOTES: Other Web browsers work in this way, too. For other recommended
browsers to use, see the table in Recipe 33.11 [Using Other Web Browsers],
page 667.
162 The Linux Cookbook, 2nd Edition
Chapter 6: Sharing Files 163
6. Sharing Files
Groups, file ownership, and access permissions are Linux features that enable
users to share files with one another. But this topic is important to know even
if you don’t plan on ever sharing files with other users on the system; these are
concepts that will help you understand how file access and security work in
Linux, and enable you to control the way a file may be accessed. By changing
the access permissions to files, files can be placed into a state so that they
can’t be modified, copied, or even viewed by certain users—including you!
This command uses the cat tool to output the entire contents of the file
(see Recipe 9.2 [Displaying Text], page 216), listing all fields. Use cut to
output only certain fields (see Recipe 13.7.4 [Removing Columns from Text],
page 324).
⇒ To output a list of all group names on the system, type:
$ cut -d : -f1 /etc/group RET
NOTES: For more information about the user group file, consult the group
man page.
$ groups RET
steward galley crew
$
In this example, three groups are output: steward (the user’s login group),
galley, and crew.
⇒ To list the group memberships of user marlow, type:
In this example, the command outputs the given username, marlow, fol-
lowed by the name of one group, marlow, indicating that user marlow belongs
to only one group: his login group.
Chapter 6: Sharing Files 165
There are two methods for listing the members of a particular group.
METHOD #1
Members
DEB: members
Use the members tool to list the members of a particular group. Give the
name of the particular group as an argument.
⇒ To output a list of the members of the galley group, type:
In this example, three usernames are output, indicating that these three
users are the members of the galley group.
NOTES: The members tool is not yet widely available outside of the Debian
distribution; if you can’t locate a copy, you can always install the sources from
the Debian package (see Recipe 1.1.2 [Preparation of Recipes], page 3).
METHOD #2
On systems without members conveniently installed, the members of a partic-
ular group may be listed by using grep in conjunction with cut. First, use
grep to output the line in /etc/group whose first field matches the partic-
ular group name, and pipe the output to cut to output only the last field,
containing the list of users who belong to that group.
⇒ To list all members of the crew group, type:
$ grep ^crew: /etc/group | cut -d : -f 4 RET
NOTES: For more information on grep and cut, see Recipe 14.1 [Searching
Text for a Word], page 333 and Recipe 13.7.4 [Removing Columns from Text],
page 324, respectively.
166 The Linux Cookbook, 2nd Edition
⇒ To give group ownership of the maps directory and all the files it contains
to the bridge group, type:
$ chgrp -R bridge maps RET
NOTES: The superuser, root, can always access any file on the system, re-
gardless of its access permissions.
For more information on file permissions and access modes, see the
fileutils Info documentation (see Recipe 2.8.5 [Reading an Info Manual],
page 48).
For example, use u+w to add write permission to the existing permissions
for the user who owns the file, and use a+rw to add both read and write
permissions to the existing permissions of all users. (You could also use ugo+rw
instead of a+rw.)
NOTES: Often, shell scripts that you obtain or write yourself do not have
execute permission set, and you’ll have to do this yourself.
Chapter 7: Finding Files 171
7. Finding Files
Sometimes you may want to locate files on the system that match given cri-
teria, such as a particular name or file size. This chapter will show you how
to find a file when you know only part of the file name, and how to find a file
whose name matches a given pattern. You will also learn how to list files and
directories by size and how to find the locations of commands.
These are not searches for matching the contents of files. That kind of
activity is described in Chapter 14 [Searching Text], page 333. A method
of searching the contents of files you find is given in Recipe 7.2.7 [Running
Commands on the Files You Find], page 178.
For more information on finding files, consult the find Info documentation
(see Recipe 2.8.5 [Reading an Info Manual], page 48).
Sometimes, a locate search will generate a lot of output. Pipe the output
to less to peruse it (see Recipe 9.1 [Perusing Text], page 211).
⇒ To peruse a list of all .cfg files on the system, type:
$ locate .cfg | less RET
172 The Linux Cookbook, 2nd Edition
This command will search all directories on the system to which you have
access; if you don’t have execute permission for a directory, find will report
that permission is denied to search the directory.
The -name option is case-sensitive; use the similar -iname option to find a
name regardless of case.
⇒ To list all files on the system whose file name is top, regardless of case,
type:
$ find / -iname top RET
This command would match any files whose name consisted of the letters
top, regardless of case—including Top, top, and TOP.
Chapter 7: Finding Files 173
Use file expansion characters (see Recipe 5.8 [Specifying File Names with
Patterns], page 153) to find files whose names match a pattern. Give these
file name patterns between single quotes.
⇒ Here are some ways to use this.
• To list all files on the system whose names begin with the characters
top, type:
$ find / -name 'top*' RET
• To list all files whose names begin with the three characters top
followed by exactly three more characters, type:
$ find / -name 'top???' RET
• To list all files whose names begin with the three characters top
followed by five or more characters, type:
$ find / -name 'top?????*' RET
• To list all files in your home directory tree that end in .tex, regard-
less of case, type:
$ find ~ -iname '*.tex' RET
• To list all files in the /usr/share directory tree that end with .jpg
or .jpeg, regardless of case, type:1
$ find /usr/share -iname '*.jp*g' RET
• To list all files in the /usr/share directory tree with the text farm
somewhere in their name, type:
$ find /usr/share -name '*farm*' RET
Use -regex in place of -name to search for files whose full or relative path
names match a regular expression, a pattern describing a set of strings (see
Recipe 14.3 [Matching Patterns of Text], page 335).
⇒ Here are two ways to use this.
• To list all files in the current directory tree whose relative path names
have either the string net or comm anywhere in them, type:
$ find . -regex '.*\(net\|comm\).*' RET
• To list all files in the /usr/share directory tree that end only with
.jpg or .jpeg, regardless of case, type:
$ find /usr/share -iregex '.*\.\(jpg\|jpeg\)' RET
1
This pattern also matches files that contain any other character or characters in place
of the “e”—for example, .jpog or .jp123g. To match files ending only with .jpg or
.jpeg, use the -regex or -iregex search that is described next.
174 The Linux Cookbook, 2nd Edition
The -regex option matches the whole path name, relative to the directory
tree you specify, and not just file names; for this reason, the regexps in the
previous examples began with “.*,” so that characters making up the path
were matched first. To only match file names in a search for a word or phrase,
exclude the forward slash character (/) after the string you’re searching for,
and exclude directory names with \! -type d (see Recipe 7.4.5 [Finding the
Number of Files in a Listing], page 184).
⇒ To list all files in the current directory tree whose names have either the
string net or comm anywhere in their file names, type:
$ find . -regex '.*\(net\|comm\).[^/]*' \! -type d RET
Use the -empty option to find empty files—files whose size is 0 bytes. This
is useful for finding files that you might not need, and can remove.
⇒ To find all empty files in your home directory tree, type:
$ find ~ -empty RET
-amin specifies the number of minutes ago that the file was accessed; you can
also find files that were accessed more recently than the file name given as an
argument to -anewer was modified. Finally, -atime specifies the number of
24-hour periods ago when the file was last accessed.
⇒ Here are some ways to use this.
• To find all files in your home directory tree that were last accessed
one hour ago, type:
$ find ~ -amin 60 RET
• To find all files in your home directory tree that were last accessed
within the past sixty minutes, type:
$ find ~ -amin -60 RET
• To find all files in the /usr/share directory tree that were last ac-
cessed twenty-four hours ago, type:
$ find /usr/share -atime 1 RET
• To find all files in the /usr/share directory tree that were last ac-
cessed more recently than the file ~/template was modified, type:
$ find /usr/share -anewer ~/template RET
Include the -daystart option to measure time from the beginning of the
current day, instead of 24 hours ago. This option must precede the time
expression it works on.
⇒ To find all files in the /usr/share directory tree that were last accessed
two days ago, type:
$ find /usr/share -daystart -atime 2 RET
• To find all the files on the system whose status has changed more
recently than the file /etc/inittab was modified, type:
$ find / -cnewer /etc/inittab RET
• To find all files in the current directory tree whose status last changed
exactly twenty-four hours ago, type:
$ find . -ctime 1 RET
• To find all files in the current directory tree whose status has changed
within the last twenty-four hours, type:
$ find . -ctime -1 RET
Include the -daystart option to measure time from the beginning of the
current day, instead of 24 hours ago. This option must precede the time
expression it works on.
⇒ To find all files in the current directory tree whose status last changed a
week ago, type:
$ find . -daystart -ctime 7 RET
• To list the files in the /usr directory tree that were modified within
the past five minutes, type:
$ find /usr -mmin -5 RET
Include the -daystart option to measure time from the beginning of the
current day, instead of 24 hours ago. This option must precede the time
expression it works on.
⇒ Here are some ways to use this.
• To list all of the files in your home directory tree that were modified
yesterday, type:
$ find ~ -daystart -mtime 1 RET
• To list all of the files in the /usr directory tree that were modified
one year or longer ago, type:
$ find /usr -daystart -mtime +365 RET
• To list all of the files in your home directory tree that were modified
from two to four days ago, type:
$ find ~ -daystart -daystart -mtime +2 -mtime -4 RET
To find files newer than a given date, use the trick described in the find Info
documentation: Create a temporary file in /tmp with touch whose timestamp
is set to the date you want to search for, and then specify that temporary file
as the argument to -newer.
⇒ To list all files in your home directory tree that were modified after May
4 of the current year, type:
$ touch -t 05040000 /tmp/timestamp RET
$ find ~ -newer /tmp/timestamp RET
NOTES: You can also find files that were last accessed a number of days after
they were modified by giving that number as an argument to the -used option.
This is useful for finding files that get little use—files matching -used +100,
say, were accessed 100 or more days after they were last modified.
In this example, the command grep organic file is executed for each file
that find finds, with file being the name of each file in turn.
To have find pause and confirm execution for each file it finds, use -ok
instead of -exec.
⇒ To remove files from your home directory tree that were accessed more
than one year after they were last modified, pausing to confirm before
each removal, type:
$ find ~ -used +365 -ok rm '{}' ';' RET
Chapter 7: Finding Files 179
As all options are combinable, you can use multiple calls of the same option.
So you can combine several of the same time options to get a range of times,
for instance.
⇒ To find all files in your home directory whose contents were modified
today, but at least 120 minutes ago, type:
$ find ~ -daystart -mtime 0 -mmin +120 RET
Use the special -o option (the or operator), to separate two options when
either of them are to be matched. For example, you can use it with multiple
-name options to find different file names in the same directory tree.
⇒ To find all files ending in .ps, .pdf, or .dvi in the current directory tree,
type (all on one line):
$ find . -name '*.ps' -o -name '*.pdf' -o -name
'*.dvi' RET
The following tables describe some of the many options you can use with
find. The first table lists and describes find’s general options for specifying
its behavior.
The following table lists and describes find’s options for specifying which
files to find.
Specify the numeric arguments to these options in one of three ways: pre-
ceded by a plus sign (+) to match values equal to or greater than the given
argument; preceded by a hyphen or minus sign (-) to match values equal to
or less than the given argument; or list the number alone to match exactly
that value.
-amin minutes Time in minutes since the file was last accessed.
-anewer file File was accessed more recently than file.
-atime days Time in days since the file was last accessed.
-cmin minutes Time in minutes since the file was last changed.
-cnewer file File was changed more recently than file.
-ctime days Days since the file was last changed.
-empty File is empty.
-group group Name of the group that owns file.
-iname pattern Case-insensitive file name pattern to match
(“report” matches the files Report, report,
REPORT, etc.).
-ipath pattern Full path name of file matches the pattern
pattern, regardless of case (“./r*rt” matches
./records/report and ./Record-Labels/ART.
-iregex regexp Path name of file, relative to specified directory tree,
matches the regular expression regexp, regardless of
case (“t?p” matches TIP and top).
-links links Number of links to the file (see Recipe 5.7 [Giving
a File More Than One Name], page 152).
-mmin minutes Number of minutes since the file’s data was last
changed.
-mtime days Number of days since the file’s data was last
changed.
-name pattern Base name of the file matches the pattern pattern.
Chapter 7: Finding Files 181
The following table lists and describes find’s options for specifying what
to do with the files it finds.
outputs files sorted alphabetically). Include the -l option to output the size
and other file attributes.
⇒ To list the files in the current directory, with their attributes, sorted with
the largest files first, type:
$ ls -lS RET
NOTES: Pipe the output to less to peruse it (see Recipe 9.1 [Perusing Text],
page 211).
$ ls | wc -l RET
19
$
In this example, the command outputs the numeral “19,” indicating that
there are 19 files in the current directory.
Since ls does not list hidden files by default (see Recipe 5.3.4 [Listing
Hidden Files], page 138), the preceding command does not count them. Use
ls’s -A option to count dot files as well.
⇒ To count the number of files—including dot files—in the current directory,
type:
$ ls -A | wc -l RET
81
$
This command outputs the numeral “81,” indicating that there are 81 files,
including hidden files, in the current directory.
To list the number of files in a given directory tree, and not just a single
directory, use find instead of ls, giving the special find predicate \! -type
d to exclude the listing (and therefore, the counting) of directories.
⇒ Here are some ways to use this.
• To list the number of files in the /usr/share directory tree, type:
$ find /usr/share \! -type d | wc -l RET
• To list the number of files and directories in the /usr/share directory
tree, type:
$ find /usr/share | wc -l RET
• To list the number of directories in the /usr/share directory tree,
type:
$ find /usr/share \! -type f | wc -l RET
Chapter 7: Finding Files 185
8. Managing Files
File management tools include those for splitting, comparing, and compress-
ing files, making backup archives, and tracking file revisions. Other manage-
ment tools exist for determining the contents of a file, and for changing its
timestamp.
$ type ls RET
ls is aliased to `ls --color=auto'
$
To specify a timestamp other than the current system time, use the -d
option, followed by the date and time that should be used enclosed in quote
characters. You can specify just the date, just the time, or both.
⇒ Here are some ways to use this.
• To change the timestamp of file pizzicato to May 17, 1990 at 2:16
p.m., type:
$ touch -d '17 May 1990 14:16' pizzicato RET
• To change the timestamp of file pizzicato to May 17th of the current
year, type:
$ touch -d '17 May' pizzicato RET
• To change the timestamp of file pizzicato to 2:16 p.m. of the cur-
rent day, type:
$ touch -d ’14:16’ pizzicato RET
NOTES: When only the time is given, the date is set to the current date, and
when only the date is given, the time is set to “0:00.” When just a year is
given, the current day and month is used, and when a day and month but no
year is given, the current year is used.
For more information on date input formats, consult the Info documenta-
tion for date (see Recipe 2.8.5 [Reading an Info Manual], page 48).
mpeg2, level 3 (mp3) format. Your file, large.mp3, is 4,394,422 bytes in size,
and you want to transfer it from your desktop to your laptop, but your laptop
and desktop are not connected on a network—the only way to transfer files
between them is by floppy disk. Because this file is much too large to fit on
one floppy, you use split.1
The split tool copies a file, chopping up the copy into separate files of
a specified size. It takes as optional arguments the name of the input file
(using standard input if none is given) and the file name prefix to use when
writing the output files (using “x” if none is given). The output files’ names
will consist of the file prefix followed by a group of letters: aa, ab, ac, and so
on—the default output file names would be xaa, xab, and so on.
Specify the number of lines to put in each output file with the -l option,
or use the -b option to specify the number of bytes to put in each output file.
To specify the output files’ sizes in kilobytes or megabytes, use the -b option
and append “k” or “m,” respectively, to the value you supply. If neither -l
nor -b is used, split defaults to using 1,000 lines per output file.
⇒ To split large.mp3 into separate files of one megabyte each, whose names
begin with large.mp3., type:
$ split -b1m large.mp3 large.mp3. RET
This command creates five new files whose names begin with: large.mp3.
The first four files are one megabyte in size, while the last file is 200,118
bytes—the remaining portion of the original file. No alteration is made to
large.mp3.
You could then copy these five files onto four floppies (the last file fits on
a floppy with one of the larger files), copy them all to your laptop, and then
reconstruct the original file with cat (see Recipe 10.6 [Concatenating Text],
page 256).
⇒ To reconstruct the original file from the split files, type:
$ cat large.mp3.* > large.mp3 RET
$ rm large.mp3.* RET
In this example, the rm tool is used to delete all of the split files after the
original file has been reconstructed.
1
Another method for splitting files is to use gnu shar, the shell archiver, which bundles
files into archives made especially for transmission by email. It can split and compress
files as it archives them.
Chapter 8: Managing Files 191
METHOD #1
Midnight Commander
DEB: mc-common
mc
RPM: mc
WWW: http://www.ibiblio.org/mc/
The most quick and easy way to determine whether two entire directories
differ is to use mc, the Midnight Commander. By default, mc draws two
directory columns upon starting; select two directories, one in each column,
and then compare them with the directory compare command, CTRL- X d
(press CTRL- X and then type d).
There are three ways you can compare files in this manner: the quick
method, which just compares file size and date (if files have different con-
tents but identical sizes, they will still show up as not differing); a size-only
comparison; and the “thorough” method, which compares all files byte by
byte.
192 The Linux Cookbook, 2nd Edition
METHOD #2
The second method is to use cmp on all files in each of the directories. Loop
through all of the files, running this command on each of them, using the Bash
built-in for construct (see the bash Info documentation for more information
on this built-in).
⇒ To compare all of the files in the directory ~/site/current with all of
the files in the directory ~/development/latest, type:
$ for i in ~/site/current/*; { cmp $i ~/development/latest/$i; }
NOTES: This cmp method only works on directories that contain regular files;
if the directories contain subdirectories, this method will fail.
In this example, the differences between each file in one directory and its
counterpart in the other directory are displayed in turn; press N to move to
the next file, and P to move to the previous one.
194 The Linux Cookbook, 2nd Edition
You can use diff to compare two directories and all of their contents. This
is useful for making a patch of a directory of text files, such as a directory of
computer program source code, or a collection of writing. To do this, give the
names of the directories to compare as arguments to diff.
To examine the differences between whole directory trees, where each direc-
tory may contain subdirectories, use the -r option to search recursively, and
use the -N option to have diff write a whole new file in one directory where it
doesn’t exist (and have it delete whole files where a file exists only in the other
directory). Since a directory diff will tend to be large, use the -u option to
specify the unified patch format, which eliminates some redundancies and is
more compact than the normal patch format.
⇒ Here are two ways to use this.
• To make a patch to change the ~/apples directory to match the
~/oranges directory, specifying all files in ~/apples to be changed
to their equivalents in ~/oranges, and writing the patch to a file
called fruit-patch.diff in the current directory, type:
$ diff -N apples oranges > fruit-patch.diff RET
• To make a patch to change the ~/apples directory tree to match
the ~/oranges directory tree, specifying all files in ~/apples and its
subdirectories to be changed to their equivalents in the ~/oranges
tree, and writing the patch to a file in the current directory called
fruit-patch.diff in unified format, type:
$ diff -r -u -N apples oranges > fruit-patch.diff RET
To apply one of these patches, use patch with the -p1 option, which elim-
inates leading slashes in filenames. Put the patch file in the directory you
want to patch, and run the patch tool from that directory. Use the -s option
to work silently, omitting any output to the standard output.
⇒ To silently apply the patch file fruit-patch.diff to the ~/apples di-
rectory, type:
The wdiff tool is a front-end to diff. It finds and displays the differences
between words in the two text files you give as arguments. It outputs an
annotated version of the second file, showing the changes necessary to make it
identical to the first: Word deletions are marked like “[- this -],” additions
are marked like “[+ this +],” and changes are marked like “{+ this +}.”
⇒ To peruse an annotated copy of the file story_draft.1, showing the
changes necessary to make it identical to the file story_draft.2, type:
$ wdiff story_draft.2 story_draft.1 | less RET
To forgo the default annotations and instead make annotations good for
sending to a printer, use the -p option; deleted text is underlined and inserted
text is output in bold.
⇒ Here are two ways to use this.
• To print an annotated copy of the file story_draft.1, showing the
changes necessary to make it identical to the file story_draft.2,
type:
$ wdiff -p story_draft.2 story_draft.1 | lpr RET
• To peruse an annotated copy of the file story_draft.1, showing
the changes necessary to make it identical to the file story_draft.2
with underlining and bold lettering, type:
$ wdiff -p story_draft.2 story_draft.1 | less RET
Use wdiff with the -s option to display a number of statistics about the
differences: the total number of words; the number of common words and the
percentage relative to the total; the number of words deleted or inserted, and
the percentage relative to the total; and the number of words changed, and
the percentage relative to the total. These statistics are output as two lines
at the end, after an annotation of the second file is output.
196 The Linux Cookbook, 2nd Edition
NOTES: The wdiff command is not included with all Linux distributions.
METHOD #1
Use the gzip (“gnu zip”) tool, giving as arguments the names of any files to
compress; it writes compressed versions of the specified files, appends a .gz
extension to their file names, and then deletes the original files.
⇒ To compress the file war-and-peace, type:
$ gzip war-and-peace RET
METHOD #2
Bzip2
DEB: bzip2
RPM: bzip2
WWW: http://sources.redhat.com/bzip2/
Use the bzip2 tool, giving as arguments the names of any files to compress;
it writes compressed versions of the specified files, appends a .bz2 extension
to their file names, and then deletes the original files.
⇒ To compress the file war-and-peace, type:
$ bzip2 war-and-peace RET
METHOD #1
To access the contents of a file compressed with gzip, use gunzip to uncom-
press (or “decompress”) it.
As with gzip, gunzip takes as an argument the name of the file or files to
work on. It expands the specified files, writing the output to new files without
the .gz extension, and then it deletes the compressed files.
⇒ To expand the file war-and-peace.gz, type:
$ gunzip war-and-peace.gz RET
METHOD #2
Bzip2
DEB: bzip2
RPM: bzip2
WWW: http://sources.redhat.com/bzip2/
To access the contents of a file compressed with bzip2, use bunzip2 to un-
compress it.
Chapter 8: Managing Files 199
As with bzip2, bunzip2 takes as an argument the name of the file or files
to work on. It expands the specified files, writing the output to new files
without the .bz2 extension, and then it deletes the compressed files.
⇒ To expand the file war-and-peace.bz2, type:
$ bunzip2 war-and-peace.bz2 RET
To see what’s in a compressed file without uncompressing the file on disk, use
see, giving the name of the file as an argument. This is handy when you want
to read or look at the contents of a compressed file, but you’d like to keep it
compressed after you’ve looked at it.
see can read files compressed by either gzip or bzip2; if it is a text file,
see uses less to display the file (see Recipe 9.1 [Perusing Text], page 211); if
it is a dvi file, see shows it with xdvi; PostScript, eps, and pdf files are all
viewed in gv, if it is installed.
⇒ To view the contents of full_dossier.pdf.bz2, type:
$ see full_dossier.pdf.bz2 RET
NOTES: see will not work for compressed images; to view their contents
without uncompressing them, use display. It can view compressed image file
formats (see Recipe 17.1 [Viewing an Image in X], page 407).
The see command is not commonly included with some Linux distribu-
tions. You can install a copy from the sources on its Debian package page (see
Recipe A.4 [Managing deb Packages], page 709).
in the previous section, and the files in the archive retain the structure and
permissions of the original files.
Use the tar tool to create, list, and extract files from archives.2 Archives
made with tar are sometimes called “tar files,” “tar archives,” or—because
all the archived files are rolled into one big file—“tarballs.”
The following recipes show how to use tar to create an archive, list the
contents of an archive, and extract the files from an archive. Two common
options used with all three of these operations are -f and -v: to specify
the name of the archive file, use -f followed by the file name, and use the -v
(“verbose”) option to have tar output the names of files as they are processed.
While the -v option is not necessary, it lets you observe the progress of your
tar operation.
NOTES: The name of this tool comes from “tape archive,” because it was
originally made to write the archives directly to a magnetic tape device. It is
still used for this purpose, but today, archives are almost always saved to a
file on disk.
For more information about managing archives with tar, consult its Info
documentation (see Recipe 2.8.5 [Reading an Info Manual], page 48).
This command lists the contents of the project.tar archive. Using the
‘code-v option along with the -t option causes tar to output the permissions
and modification time of each file, along with its file name—the same format
used by the ls command with the -l option (see Recipe 5.3.3 [Listing File
Attributes], page 136).
Include the -z option to list the contents of a compressed archive.
⇒ To list the contents of a compressed archive called project.tar.gz, type:
$ tar -ztvf project.tar.gz RET
This command extracts the contents of the project.tar archive into the
current directory.
If an archive is compressed, which usually means it will have a .tar.gz or
.tgz extension, include the -z option.
202 The Linux Cookbook, 2nd Edition
NOTES: If there are files or subdirectories in the current directory with the
same name as any of those in the archive, those files will be overwritten
when the archive is extracted. If you don’t know what files are included in
an archive, consider listing the contents of the archive first as shown in the
preceding recipe.
Another reason to list the contents of an archive before extracting them
is to determine whether the files in the archive are contained in a directory.
If not, and the current directory contains many unrelated files, you might
confuse them with the files extracted from the archive.
To extract the files into a directory of their own, make a new directory,
move the archive to that directory, and change to that directory, where you
can then extract the files from the archive.
popular for managing free software projects on the Internet. For information
on using cvs, consult its Info documentation (see Recipe 2.8.5 [Reading an
Info Manual], page 48).
$ ci novel RET
novel,v <-- novel
enter description, terminated with single '.' or
end of file:
NOTE: This is NOT the log message!
>> The Great American Novel. RET
>> . RET
$
This command deposits the file in an rcs repository file called novel,v,
and the original file, novel, is removed. To edit or access the file again, you
must check out a revision of the file from rcs to work on (see the next recipe
for how to do this).
Whenever you have a new revision that you want to save, use ci again to
check in the file. This begins the process all over again.
204 The Linux Cookbook, 2nd Edition
For example, suppose you have checked out the first revision of novel and
changed the file so that it now looks like Figure 8-2.
This is a very long tale about a great many things, including my long
voyage across America, and back home again.
Figure 8-2. A new revision of novel.
⇒ To deposit this revision in rcs, type:
$ ci novel RET
novel,v <-- novel
new revision: 1.2; previous revision: 1.1
enter log message, terminated with single '.' or end of
file:
>> Second draft. RET
>> . RET
$
If you create a subdirectory called RCS (in all uppercase letters) in the
current directory, rcs recognizes this specially named directory instead of the
current directory as the place to store the ,v revision files. This helps reduce
clutter in your work directory.
If the file you are depositing is a text file, you can have rcs insert a line of
text in the file, every time the file is checked out, containing the name of the
file, the revision number, the date and time in utc (Coordinated Universal
Time), and the user id of the author. To do this, put the text “$Id$” at a
place in the file where you want this text to be written. You only need to do
this once; each time you check the file out, rcs replaces this string in the file
with the header text.
For example, this chapter was written to a file, managing-files.texinfo,
whose revisions were tracked with rcs; the “$Id$” string in this file currently
reads:
$Id: managing-files.texinfo,v 2.11 2004/07/03 18:54:01 m Exp m $
NOTES: You should always make your log message descriptive enough so that
later, you won’t be confused about what you had done to the file.
To check out the latest revision of a file that you intend to edit (and to
check in later as a new revision), use the -l (for “lock”) option. Locking a
revision in this fashion prevents overlapping changes from being made to the
file, should another revision be accidentally checked out before this revision is
checked in.
⇒ To check out the latest revision of the file novel for editing, type:
$ co -l novel RET
This command checks out the latest revision of file novel from the novel,v
repository, writing it to a file called ‘novel’ in the current directory. (If a file
with that name already exists in the current directory, co asks whether or not
to overwrite the file.) You can make changes to this file and then check it in
as a new revision (see the previous recipe).
You can also check out a version of a file as read only, where changes cannot
be written to it. Do this to check out a version to view only and not to edit.
To check out the current version of a file for examination, type co followed
by the name of the file.
⇒ To check out the current revision of file novel, but not permit changes
to it, type:
$ co novel RET
This command checks out the latest revision of the file novel from the rcs
repository novel,v (either from the current directory or in a subdirectory
named RCS).
To check out a version other than the most recent version, specify the
version number to check out with the -r option. Again, use the -l option to
allow the revision to be edited.
⇒ To check out revision 1.14 of file novel, type:
$ co -l -r1.14 novel RET
You could give the command in the preceding example on one long line,
like so:
for i in *.html; { ci -f -r3.0 -m"Updated for new product
release" $i; co -l $i; }
208 The Linux Cookbook, 2nd Edition
III. TEXT 209
III. TEXT
210 The Linux Cookbook, 2nd Edition
Chapter 9: Viewing Text 211
9. Viewing Text
Dealing with textual matter is the meat of Linux (and of most computing), so
there are going to be many chapters about the various aspects of text. This
first chapter in this part of the book shows how to view text on your display
screen.
Text files come in any number of formats, from formatted text in some par-
ticular language—such as English or the c programming language—to saved
email messages or html files. Plain text files don’t have to have a .txt or
.text file name extension, although they often do (see Appendix B [Conven-
tional File Name Extensions], page 723).
If you are not sure whether the content of a file is text or not, use file to
find out, as described in Recipe 8.1.1 [Determining a File’s Type and Format],
page 187.
A tool that just allows you to view text on the screen, but not edit it, is
called a pager. When most people view text without editing it, they use less,
which is described in the following recipes.
There are many ways to view or otherwise output text. For example, you
can view text as you browse files and their contents, as described in Recipe 5.10
[Browsing Files and Directories], page 157. When your intention is to edit the
text of a file, you should open it in a text editor, as described in Chapter 10
[Editing Text], page 231. The Vi editor comes with a special command, view,
to open a file in read-only mode with Vi, so that it can only be viewed—you
cannot, accidentally or intentionally, make any changes to the file while it is
open if you use this command.
Some kinds of files—such as PostScript, dvi, and pdf files—often contain
text in them, but they are technically not text files. These are image format
files, and I describe methods for viewing them in Recipe 17.4 [Previewing
Print Files], page 413.
Another tool, zless, is identical to less, but you use it to view compressed
text files; it allows you to read a compressed text file’s contents without having
to uncompress the file first (see Recipe 8.4 [Using File Compression], page 196).
Most of the system documentation in the /usr/doc and /usr/share/doc
directories, for example, consists of compressed text files.
You may, on occasion, be confronted with a reference to a command for
paging text, called more. It was the standard tool for paging text until it gave
way to less in the early to mid 1990s; less comes with many more options—
its most notable advantage being the ability to scroll backward through a
file—but at the expense of being almost exactly three times the size of more.
Hence, there are two meanings to the saying, “less is more.”
The following table summarizes the most essential keyboard commands
for paging through text in less. It lists the keystrokes and describes the
commands.
Cursor Movement
Scroll back through the text (“up”) one line.
Miscellaneous
R or CTRL- L Redraw (or “repaint”) the screen.
NOTES: less has many command line options as well as key commands to
be used while running, and there are all kinds of tricks you can do with it—
almost enough for a whole chapter. If this sort of thing interests you, it’s
worth reading through the less man page.
NOTES: You can make your own custom prompt, making use of a number
of variables that hold information about the file; see the less man page for
information on how to do this.
METHOD #1
To display raw control characters in text, run less with the -r option. This
may, of course, cause any number of problems with screen display, as the raw
characters may affect it.
⇒ To peruse the file live.transcript and display any raw control charac-
ters in it, type:
$ less -r live.transcript RET
Chapter 9: Viewing Text 215
METHOD #2
To display raw control characters in text, but try to keep the screen appear-
ance, use less with the -R option. This displays raw control characters, but
any disparities that may be caused by the control characters on the screen are
controlled, whenever possible.
⇒ To peruse the file live.transcript and display any raw control charac-
ters in it, but attempt to keep the screen in order, type:
$ less -R live.transcript RET
Figure 9-1. Viewing multiple files in less.
METHOD #1
You can specify more than one file to page through with less, and you can
specify file patterns in order to open all of the files that match that pattern.
The files will be displayed in sequence—less displays each file in turn, be-
ginning with the first file you specify or the first file that matches the given
216 The Linux Cookbook, 2nd Edition
pattern. To move to the next file, press N; to move to the previous file, press
P.
This command starts less, which then opens all of the files that match
the given pattern /usr/doc/FAQ/unix-faq-part*, and begins displaying the
first one, as in Figure 9-1.
METHOD #2
Another method is to use cat to concatenate all the files together, and pipe
that output to less. There will be no indicator to mark where one file ends
and another begins, but you can scroll through the entire text cleanly without
pressing buttons to move from file to file.
⇒ To page through all of the unix faq files in /usr/doc/FAQ all at once,
type:
$ cat /usr/doc/FAQ/unix-faq-part* | less RET
There is no indicator when one file ends and the next begins, but rather,
all are treated as one long file in the order given. (In this case, where the
wildcard character was used, they are displayed in the order in which the
shell expands the “*” to all of their names.)
If you have a small text file that you want to look at, you just cat it to
the screen. It’s quick, it gets the job done, you don’t have to think about it.
But while it is useful for concatenating text (see Recipe 10.6 [Concatenating
Text], page 256), it isn’t always the best way to peruse or read text—a very
large text will scroll off the top of the screen, for example.
Chapter 9: Viewing Text 217
To visually display the end of each line, use the -E option; it specifies that a
“$” should be output after the end of each line. This is useful for determining
whether lines contain trailing space characters. (You can also use grep to
output lines containing trailing spaces.)
Also useful is the -T option, which outputs tab characters as their literal
control character, written in hat notation as “^I.”
The -A option combines all three of these options—it is the same as spec-
ifying -vET.
⇒ Here are some ways to use this.
• To output the file translation with a “$” character displayed at
the end of every line, type:
$ cat -E translation RET
• To output the file translation with all tab characters written as
“^I” instead of literal tabs, type:
$ cat -T translation RET
• To output the file translation with non-printing characters, in-
cluding tabs, displayed in hat notation, and with a “$” character
displayed at the end of each line, type:
$ cat -A translation RET
218 The Linux Cookbook, 2nd Edition
You can specify as a numeric option the number of lines to output. If you
specify more lines than a file contains, head just outputs the entire text.
⇒ Here are two ways to use this.
• To output the first line of file placement-list, type:
$ head -1 placement-list RET
• To output the first 66 lines of file placement-list, type:
$ head -66 placement-list RET
NOTES: An old unix tool named line just output the first line of its input.
This tool does not exist for Linux, but you can make a pretty good imitation
with head by defining “line” as an alias for head -1 (for more information
on making aliases, see Recipe 3.6 [Using Alias Words], page 82).
To specify which part of the text to output by its relation to the beginning
of the text, precede the number with a plus sign (+).
Chapter 9: Viewing Text 219
NOTES: You can achieve the same result with less; to do this, type F while
perusing the text (see Recipe 9.1 [Perusing Text], page 211).
METHOD #1
To output a particular line of a file, use sed (see Recipe 10.5 [Editing Streams
of Text], page 255). Give the line number to output followed by !d as a quoted
argument to sed; give the filespec to output from as the second argument.
⇒ To output line 47 of file placement-list, type:
$ sed '47!d' placement-list RET
To output a region of more than one line, give the starting and ending line
numbers, separated by a comma.
⇒ To output lines 47 to 108 of file placement-list, type:
$ sed '47,108!d' placement-list RET
METHOD #2
To output the middle part of some text, you can also combine multiple head
or tail commands on a pipeline (see Recipe 3.2.4 [Redirecting Output to
Another Command’s Input], page 69).
220 The Linux Cookbook, 2nd Edition
In the preceding example, three commands were used: The first five lines
of file placement-list are passed to tail, which outputs the last line in the
output (the fifth line in the file); then, the last head command outputs the
first character in that last line, which achieves the desired result.
To output all of the lines of text except those between two patterns, omit
the -n option.
⇒ To output all the text from file book-draft, except that which lies be-
tween the text “Chapter 3” and “Chapter 4,” type:
$ sed '/Chapter 3/,/Chapter 4/p' book-draft RET
NOTES: For more on sed, see Recipe 10.5 [Editing Streams of Text], page 255.
Chapter 9: Viewing Text 221
METHOD #1
Use od, the “octal dump” tool, with the -c option to show the ascii characters
in some text. This outputs the characters grouped 16 per line, separated by
spaces and, when possible, giving backslash escapes for control characters. A
column is displayed on the left, containing the offset (the number of bytes into
the file) of the first character in that line. Use the -A option and give “d” as
an argument to output these numbers in decimal and not the default, which
is octal.
⇒ Here are some ways to use this.
• To display the literal characters in the file details, grouped 16 per
line, with each line prefaced by an offset number, type:
$ od -Ad -c details RET
• To output the literal characters in the last line of file details, type:
$ tail -1 details | od -Ad -c RET
METHOD #2
You can get the same effect as od with hexdump. Use the -c option, which
displays each byte in the file as the character it represents. As with Method
#1, 16 characters of the input is displayed on each line, separated by spaces,
and a column is written on the left-hand side showing the offset value of the
file, except in this case the offset is given in hexadecimal.
⇒ To display the literal characters in the file exam, grouped 16 per line, with
each line prefaced by an offset number in hexadecimal, type:
$ hexdump -c exam RET
There are several methods for doing this, each with its own output format.
All of them are capable of outputting in hexadecimal (or “hex” for short);
these outputs are sometimes called hex dumps.
METHOD #1
The hexdump filter dumps its input in any one of a number of formats, showing
a number of characters from the file per line, and preceded with a number
indicating the location in the file of the first character in that line.
To display text in hex, first use the tr filter to eliminate carriage returns
from the input, and pass this text to hexdump with the -c option, which dis-
plays its input in hexadecimal, with one byte per character. 16 characters of
the input are displayed on each line, separated by spaces, and a column is
written on the left-hand side showing the offset value of the file, in hexadeci-
mal.
⇒ To peruse the contents of the file ‘tarpon’ in hexadecimal, type:
$ tr -d '\r' < tarpon | hexdump -c | less RET
METHOD #2
Use od, “octal dump,” to make a literal and unambiguous dump of some text.
It works as a filter or takes the name of a file as an argument, and can output
in octal, hexadecimal, or other formats
Use the -t option to specify the format type of the output, and give “x1”
as an argument to specify that the display should be in hexadecimal, with
one byte per integer (with an argument of “x2,” a hex integer is displayed for
every two bytes of input).
⇒ To peruse the contents of the file details in hex, type:
$ od -t x1 details | less RET
This command outputs the values of each literal character of the file
details in hexadecimal, 16 characters per line, separated by spaces. Each
line is preceded by an offset value (in octal) indicating the offset in the file
of the first character in that line. To change the offset display from octal to
decimal, use the -A option and give “d” as an argument (or give “x” if you
want hex).
To display the printable characters in a new column on the right-hand side
of the screen, add a “z” to the end of your argument to the -t option. Each
line of the column will be prefaced with a greater-than sign (>) and end with
a less-than sign (<).
Chapter 9: Viewing Text 223
⇒ To peruse the contents of the file details in hex, showing the file’s print-
able characters in its own column, type:
$ od -t x1z details | less RET
METHOD #3
Midnight Commander
DEB: mc-common
mc
RPM: mc
WWW: http://www.ibiblio.org/mc/
When you view a file in mc, you can toggle the display of hex values. To do
this, type F3 on a file in the directory listing to view the file, and then type
F4 while viewing the file to toggle between viewing the ascii characters or
their hex values; type F10 to exit viewing the file, and type F10 again to
exit mc.
METHOD #4
To view a hex dump of a buffer in Emacs, use hexl-mode.
⇒ To view a hex dump of the current buffer, type:
ALT- X hexl-mode RET
NOTES: This mode is good for viewing and editing binary files in Emacs.
METHOD #1
To view the html-formatted text itself, just view it with less as with any
text file, as described in Recipe 9.1 [Perusing Text], page 211.
224 The Linux Cookbook, 2nd Edition
METHOD #2
To view an html-formatted text file with the html formatting applied to the
text, open the file in a Web browser as described in Methods #2 and #3 of
Recipe 5.10 [Browsing Files and Directories], page 157.
⇒ To view the html-formatted text file homepage.html as rendered html,
type:
$ mozilla homepage.html RET
In this last example, the new file program.txt will contain overstrike char-
acters for boldface text. The original file program.1 is unaltered.
NOTES: All man pages are written in nroff format, hence the use of that
command to view it.
METHOD #1
Cutils
DEB: cutils
WWW: http://www.sigala.it/sandro/software.html#cutils
Use the chilight filter, distributed as part of the Cutils package, to view
C program source code with language highlighting. Given the name of a file
as an argument (or the standard input if the file name is omitted), chilight
outputs the C program source code, highlighted in one of a number of formats.
Specify the highlighting format by giving one of the following as an argument
to the -f option; the default value is “tty.”
METHOD #2
To view C program source code with highlighting, use enscript to “pretty-
print” it, as described in Recipe 15.2.4 [Outputting Text with Language High-
lighting], page 365.
226 The Linux Cookbook, 2nd Edition
This method outputs the text in PostScript, which you then view or print.
It also works with many other languages and formats, and not just C—see
the table in the aforementioned recipe.
In this example, the gv command was used to display the enscript output.
NOTES: Without a second argument, look uses the system dictionary. This
is described in Recipe 11.2.1 [Listing Words That Match a Pattern], page 283.
There are a few methods for viewing text containing backspace underlines
in different ways.
METHOD #1
Use less to peruse text containing backspace underlines (see Recipe 9.1 [Pe-
rusing Text], page 211).
⇒ To peruse the file term-paper so that you can view any backspace un-
derlines it contains, type:
$ less term-paper RET
METHOD #2
Use the ul tool to output text containing backspace underlines, so that these
underlines are displayed correctly on your terminal.
⇒ To output the file term-paper so that you can view underlined text, type:
$ ul term-paper RET
METHOD #3
Use colcrt to convert backspace underlining to dashing (a row of hyphen
characters, like “------”) drawn beneath the underlined text.
⇒ To output the file term-paper, with all backspace underlining converted
to dashing, type:
$ colcrt term-paper RET
Dashing inserts a new line in the text directly underneath any underlined
text, and this is not always desirable. Use the ‘-’ option to supress underlining
entirely, and display any underlined text as plain text.
⇒ To output the file term-paper, with all backspace underlining removed,
type:
$ colcrt - term-paper RET
228 The Linux Cookbook, 2nd Edition
This displays the values of each character in octal, decimal, and hexadec-
imal, and also displays their escape codes. These values can be useful for
quoting special characters.
The iso_8859_1 man page contains the entire iso 8859-1 character set,
including all extended characters above the standard 127 ascii characters.
Chapter 9: Viewing Text 229
You can use this page to see all of the characters in this character set and
how to input them.
NOTES: There’s a special way to “quote” these characters in Emacs; this tech-
nique is described in Recipe 10.1.4 [Inserting Special Characters in Emacs],
page 239.
The miscfiles package also contains charts for these character sets, as
explained in Recipe 11.4 [Using Word Lists and Reference Files], page 289.
230 The Linux Cookbook, 2nd Edition
Chapter 10: Editing Text 231
To call Emacs but a text editor does not do it justice—it’s a large application
capable of performing many functions, including reading email and Usenet
news, browsing the World Wide Web, and even perfunctory psychoanalysis
(for proof, see Recipe 30.7 [Undergoing Psychoanalysis], page 594).
There are two major variants of Emacs, with a number of minor branches
and alternates. gnu Emacs is distributed by the fsf as part of its “gnu
system,” and is the original Emacs. XEmacs (formerly Lucid Emacs) is an
alternate version. It offers essentially the same features gnu Emacs does, but
also contains its own features for use with the X Window System (it also
behaves differently from Gnu Emacs in some minor ways).
Gnu Emacs and XEmacs are by far the most popular emacsen (as they
are referred to in number); other flavors include jed (see Recipe 10.8 [Us-
ing Other Text Editors], page 263) and Chet’s Emacs (ce), developed by a
programmer at Case Western Reserve University. gnu Emacs is the flavor of
Emacs assumed in the recipes that follow, but in principle they should work
with most any Emacs variant.
First is a brief introduction to using Emacs, interspersed with the necessary
Emacs jargon; that is followed by recipes that describe how to use some of
Emacs’s unique editing features.
Upon startup in X, a typical gnu Emacs window looks like Figure 10-1
(the client window will differ depending on your window manager):
you can access and choose the same menu items in a text menu window by
typing F10.1
A file or other text open in Emacs is held in its own area called a buffer.
By default, the current buffer appears in the large area underneath the menu
bar. To write text in the buffer, simply type it. The place in the buffer where
the cursor sits is called point, and is referenced by many Emacs commands.
The filled-in area on the scroll bar represents the text that is displayed in
the window in relation to the rest of the buffer. Thus, the scroll bar will be
filled completely in a new, small, or empty buffer (as in the illustration), and
when you are near the bottom of a very large buffer, only a tiny portion near
the bottom of the scroll bar will be filled.
The horizontal bar near the bottom of the Emacs window and directly
underneath the current buffer is called the mode line; it gives information
about the current buffer, including its name, what percentage of the buffer
fits on the screen, what line point is on, and whether or not the buffer is saved
to a file.
The mode line also lists the modes active in the buffer. Emacs modes
are general states that control the way Emacs behaves—for example, when
overwrite-mode is set, the text you type overwrites the text at point; in
insert-mode (the default), the text you type is inserted at point. Usually,
either fundamental-mode (the default) or text-mode will be listed.
Just beneath the mode line is the echo area where Emacs writes brief status
messages, such as error messages; it is the last line in the Emacs window.
When you type a command that requires input, that input is requested in
this area (and when that happens, the place you type your input, in the echo
area, is then called the minibuffer). If you look closely, you can see that it
has its own scroll bar, too.
Emacs makes extensive use of CTRL and ALT key combinations. Because
Emacs is different in culture from the editors and approach of the Microsoft
Windows and Apple macos world, it has gotten a rather unfounded reputation
in those corners that it is odd and difficult to use. This is not so. The keyboard
commands to run its various functions are designed for ease of use and easy
recall—once you get used to this concept, you can type these key combinations
very quickly.
In Emacs notation, these keypresses are written a certain way. Many com-
mands are begun by typing CTRL- X, which is written “C-x” (the command
to exit Emacs, for example, is CTRL- X CTRL- C, and is written “C-x C-c.”)
1
The F10 key also works in X, where it behaves the same as in a terminal.
Chapter 10: Editing Text 235
(If the menu bar is already turned off, running this function will turn it
back on.)
Type CTRL- G in Emacs to quit a function or command that you are
typing; if you make a mistake when typing a command, this is useful for
canceling and aborting the keyboard input.
The find-file function prompts for the name of a file and opens a copy of
the file in a new buffer; its keyboard accelerator is CTRL- X CTRL- F (you
can keep CTRL depressed while you press and release the X and F keys).
⇒ To run the find-file function, type:
ALT- X find-file RET
This command runs the find-file function, which prompts for the name
of a file and opens a copy of the file in a new buffer.
Emacs can have more than one buffer open at once. Any file names you
give as an argument to emacs will open in separate buffers:
$ emacs diary etc/todo etc/rolo RET
(You can also make new buffers and open files in buffers later, of course.)
Just as functions are prefaced by the ALT- X keystroke, many commands
are prefaced by the similar CTRL- X keystroke, particularly commands that
work on buffers, files, or have to do with exiting Emacs.
To switch between buffers, type CTRL- X CTRL- B. Then, give the name
of the buffer to switch to, followed by RET; alternatively, type RET without
a buffer name to switch to the last buffer you visited. (Viewing a buffer in
Emacs is called visiting the buffer.)
2
Technically, this refers to the META key. Chances are that your keyboard has an ALT
key and no META key, though, in which case you use ALT to type it, so I’ve used
ALT to notate this key (see Recipe 1.2 [Typographical Conventions], page 6).
236 The Linux Cookbook, 2nd Edition
If a buffer does not exist, Emacs will make a new buffer with the name you
give.
When you start Emacs, a special buffer named *scratch* exists, which
you can use for writing notes and other things you don’t want to save; its
contents aren’t saved, and the next time you run Emacs the *scratch* buffer
will be empty again.
⇒ To switch to the *scratch* buffer, type:
CTRL- X CTRL- B *scratch* RET
To write some text in the current buffer, just type it. Text you type is
inserted at point.
⇒ To insert a line of text at point in the current buffer, type:
This is how to type in Emacs. RET
Now that we have run through the essential Emacs terminology, I’ll show
you how to exit the program.
To kill Emacs, use CTRL- X CTRL- C which also gives you a chance to
save any unsaved buffers before Emacs is killed. You can also type CTRL- Z
to suspend Emacs as a background job, so that you can return to it later (see
Recipe 3.3.3 [Putting a Job in the Foreground], page 73). In X, CTRL- Z
does not suspend Emacs but rather it iconifies the Emacs window. Deiconify
it to bring it back (see Recipe 4.3.5 [Deiconifying an X Window], page 107).
⇒ Here are some ways to use this.
• To kill Emacs, with a chance to save any unsaved buffers first, type:
CTRL- X CTRL- C RET
• To suspend Emacs when you are running it in the console, type:
CTRL- Z
Chapter 10: Editing Text 237
This command opens the tutorial, a special read-only file, into its own
buffer.
NOTES: Incidentally, CTRL- H is the Emacs help key; all help-related com-
mands begin with this key. For example, to read the Emacs faq, type CTRL-
H F, and to run the Info documentation browser (which contains The gnu
Emacs Manual), type CTRL- H i.
Moving Point
or CTRL- P Move point up to the previous line.
or CTRL- B Move point back (to the left) through the buffer one
character.
or CTRL- F Move point forward (to the right) through the buffer
one character.
(continued)
Moving Point
ALT- B Move point backward one word.
PgUp or CTRL- V Move point forward through the buffer one screenful.
PgDn or ALT- V Move point backward through the buffer one screen-
ful.
Getting Help
CTRL- H t Start the Emacs tutorial.
The preceding examples both do the same thing: They insert a formfeed
character at point.
An interesting use of CTRL- Q is to underline text. To do this, insert a
literal CTRL- H character followed by an underscore (_) after each character
you want to underline.
⇒ To underline the character before point, type:
CTRL- Q CTRL- H _
You can then use ul to output the text to the screen (see Recipe 13.9
[Underlining Text], page 327).
Another kind of special character insert you might want to make is for
accented characters and other characters used in various languages.
There are two methods for inserting them in a buffer.
METHOD #1
To insert an accented character, use iso-accents-mode. When this mode is
active, you can type a special accent character followed by the character to
be accented, and the proper accented character will be inserted at point.
The following table shows the special accent characters and the key com-
binations to use.
(continued)
Prefix . . . Plus This Letter Yields This Result
' i í
' o ó
' u ú
` a à
` e è
` i ì
` o ò
` u ù
~ a ã
~ c ç
~ d d̃
~ n ñ
~ t t̃
~ u ũ
~ < <<
~ > >>
~ ! ¡
~ ? ¿
^ a â
^ e ê
^ i î
^ o ô
^ u û
/ a å
/ e æ
/ o ø
⇒ To write the text “Emacs ist spaß!” at point in the current buffer, type:
ALT- X iso-accents-mode RET
Emacs ist spa"ss!
In the event that you want to type the literal key combinations that make
up an accented character in a buffer where you have iso-accents-mode on,
type the prefix character twice.
⇒ To type the text “'o” (and not the accent character ó) in a buffer while
iso-accents-mode is on, type:
''o
242 The Linux Cookbook, 2nd Edition
METHOD #2
To insert accented characters and other special language characters in a buffer
without entering iso-accents-mode, use CTRL- X 8 followed by the special
key combination of accent prefix and character, as described in the previous
table.
Non-letter characters do not require the accent prefix with this method.
⇒ To write the text ‘¡Hasta Ma~ nana!’ at point in the current buffer, type:
CTRL- X 8 !Hasta Ma CTRL- X 8 ~nana!
To define an abbrev, type the abbrev you want to use and then type CTRL-
X aig. Emacs will prompt in the minibuffer for the text you want the abbrev
to expand to; type that text and then type RET.
• To define “ww” as an abbrev for ‘Walla Walla, Washington,’ do the fol-
lowing:
1. First, type the abbrev itself:
ww
2. Next, specify that this text is to be an abbrev; type:
CTRL- X aig
Chapter 10: Editing Text 243
Now, whenever you type the text “ww” followed by a whitespace or punctu-
ation character in the current buffer, that text will expand to the text “Walla
Walla, Washington.”
To save the abbrevs you have defined so that you can use them later,
use the write-abbrev-file function. This saves all of the abbrevs currently
defined to a file that you can read in a future Emacs session. (You can also
open the file in a buffer and edit the abbrevs if you like.)
⇒ To save the abbrevs you have currently defined to the file ~/.abbrevs,
type:
ALT- X write-abbrev-file RET ~/.abbrevs RET
Then, in a future Emacs session, you can use the read-abbrev-file func-
tion to define those abbrevs for that session.
⇒ To read the abbrevs from the file ~/.abbrevs, and define them for the
current session, type:
ALT- X read-abbrev-file RET ~/.abbrevs RET
NOTES: Macros are fundamental to how Emacs works—in fact, the name
Emacs is derived from “Editing MACroS,” because the first version of Emacs
in 1976 was actually a collection of such macros written for another text editor.
10.2 Using Vi
Nvi
DEB: nvi
RPM: nvi
WWW: http://www.bostic.com/vi/
WWW: http://vasc.ri.cmu.edu/old_help/Editors/Vi/
The following recipes work for the Vi editor. Its name, pronounced “vye,”
or sometimes “vee-eye,” is short for visual ; when it was first invented, it was
Chapter 10: Editing Text 245
among the first text editors to visually display the text on the entire screen
for interactive editing (other interactive editors of the time typically displayed
files line by line).
As with Emacs, there are many variants of Vi; a few of the more popular
ones today are Vim and Elvis, both newer implementations that have many
more features than the original Vi. This section will assume use of Nvi, a new
implementation of the original Vi for bsd that is commonly found on most
Linux systems today.
Vi is a modal editor, where the meaning of text you type depends on the
current editing mode the editor is in. When you start, Vi is in command mode,
which means that the text you type is interpreted as literal Vi commands.
A typical Vi session, upon startup in command mode with a new file, looks
like Figure 10-2.
The cursor is positioned in the upper right-hand corner. Vi fills lines on
the screen after the end of the file with the tilde character (~); so when you
are in a new file, such as when you start Vi with no arguments, the screen is
filled with tildes because there is nothing yet in the file.
The bottom line of the screen is called the command line, and is where Vi
displays important messages and information about the file you are editing.
When Vi starts, the command line displays three things: First, the name of
the recovery file used for this file.3 Second, Vi displays the name of the file
3
Vi uses the /tmp directory to store temporary files for all files that you edit; it saves your
editing work so that you can recover it in the event of a crash, or if you accidentally exit
Vi before you save it.
246 The Linux Cookbook, 2nd Edition
being edited; in this case, the file doesn’t have a name yet, so “new file” is
written on the command line. The third thing displayed on the command line
is the line number of the file that the cursor is on.
4
This is also called input mode.
Chapter 10: Editing Text 247
This moves from command mode to insert mode, inserts the text “Hello,
world.” and a newline character in the current file, where the cursor was, and
then brings Vi back to command mode.
The command to get help is :help, and to get a list of commands and
their usage, run the :viusage command.
⇒ To get a list of Vi commands and their usage, type:
:viusage RET
When you open a file in Vi, the content of the file is placed in its own
buffer, as with Emacs. Changes are not made to a file on disk until you write
them.
To write a buffer to a file, use :w and give the name of the file to write to.
Use :wq instead to write the file to disk and quit, and use :q! to abandon all
unsaved editing, and quit Vi.
⇒ Here are two ways to use this.
• To write the contents of the buffer to the file my_practice_file,
and then exit Vi, type:
:wq my_practice_file RET
• To abandon any unsaved editing and exit Vi, type:
:q! RET
NOTES: You can also type ZZ to write the changes to the current file and
exit.
⇒ To run the vi tutorial, type the following from your home directory:
$ cp /usr/doc/nvi/vi.beginner.gz . RET
$ gunzip vi.beginner.gz RET
$ vi vi.beginner RET
Cursor Movement
CTRL- F Scroll text down one full screen.
(continued)
Cursor Movement
) Move backward one sentence.
numberG Go to line number. (With no number preceding it,
G goes to the last line in the file.)
0 Go to beginning of line cursor is on.
$ Go to end of line cursor is on.
Cutting and Pasting
x Delete character cursor is on.
dd Delete line cursor is on.
D Delete everything from the cursor to the end of the
line.
J Join the line the cursor is on with the line that fol-
lows it (i.e., delete the newline character between
them).
p Paste, after the cursor, the last text that was
deleted.
P Paste, before the cursor, the last text that was
deleted.
number yy “Yank” current line. If preceded by a number, then
yank that number of lines.
u Undo last edit made.
. Redo last edit made.
Searching
/pattern RET Search forward for pattern (if none given, then
search for the next forward occurrence of the last
pattern searched for). Searches wrap from end of
file to beginning.
?pattern RET Search backward for pattern (if none given, then
search for the next backward occurrence of the last
pattern searched for). Searches wrap from beginning
of file to end.
250 The Linux Cookbook, 2nd Edition
:q! RET Quit without saving, even if there have been changes
to the file.
:wq name RET Write file to disk and quit Vi; if name is given, write
it to that file name.
ZZ Write file and quit Vi.
Chapter 10: Editing Text 251
To run a shell command in Vi, use :! while in command mode, and follow it
with the name of the command. The output is displayed on the screen while
your editing session is suspended; press RET to go back to the editing session.
⇒ Here are two ways to use this.
NOTES: After this last example, you can return to input mode by typing a
command such as i.
You can insert the output of a command into the file you are editing in Vi.
To do this, use :r! followed by the command. Output is inserted at the point
where the cursor is pointing.
⇒ To insert the current date and time in the current file in Vi, at the point
where the cursor is, type:
:r!date RET
252 The Linux Cookbook, 2nd Edition
10.2.7 Customizing Vi
There are a number of options you can set in Vi; use the set command
followed by the name of the option to set it. Given alone, set lists all of the
options that have changed from their defaults, and given with the all option,
set lists all options that are available.
⇒ Here are two ways to use this.
• To show all the options that have been changed from their default
behavior, type:
:set RET
• To show all available options, type:
:set all RET
The following table lists some of the set options and describes their actions.
NOTES: For the complete list of options, consult the vi man page.
To paste the text that was last selected with the mouse, click the middle mouse
button at the place you want to paste to. You can also use the keyboard by
moving the cursor to where you want to paste and then typing SHIFT- INS.
These commands work both in X and in a terminal.
In X, to display the content of the X selection in its own window, run the
xpaste X client; its only purpose in life is to display this text in its window.
In Emacs, pasting text is called yanking the text. Emacs offers an addi-
tional keystroke, CTRL- Y (“yank”), to yank the text that was last selected
or killed. This key also works in the Bash shell, where it pastes the last text
that was killed with CTRL- K in that shell session, if any.
The utility of a token is that when you leave that part of the text, you can
quickly return to it later by searching for the token string.
The string you use for a token must be something unique that does not
appear in the text proper, and yet is something that you can recognize. Use
it to bookmark a point in a text you are editing, for when you need to move
elsewhere in the text to do some other thing, but have intend to come back to
this place later. It’s also handy for when you are editing a text and have to
keep a space blank for the time being, such as someone’s name that you will
add later, once it becomes known.
When you want to go back to the place you have marked with the token,
just search for the token using the editor’s search facilities. (In Vi, you can
use the m command to set a named mark in the file at the point where the
cursor is.)
My favorite token is “tk,” the printers’ mark. This two-letter combination
occurs rarely in English text, and it is very short, so it is a good one to use
for such purposes.5
Some people use a silly nonsense word that they can remember, and others
use “***” or “###” or some other thing.
stream and replace it with some other pattern in the output stream is
“s/searchpattern/replacepattern/g”; to filter the output of a command, you
can quote this command as an argument to sed and put it on a pipeline.
⇒ To output a calendar of the current month, with all “1” characters re-
placed with “l” characters, type:
$ cal | sed 's/1/l/g' RET
This example uses cal to display a calendar (see Recipe 27.3.1 [Displaying
a Calendar], page 539). The output of cal is edited by sed and then sent to
standard output.
You can also use sed to edit the contents of files by giving some filespec as
a second argument; the content of the files are sent to standard output with
the specified editing changes, and the original files are not altered.
⇒ Here are two ways to use this.
• To output the contents of the file remarks, replacing every instance
of the text “quite pleased;’ with “absolutely delighted,” type
(all on one line):
$ sed 's/quite pleased/absolutely delighted/g'
remarks RET
• To output the contents of all files in the current directory whose
file names end with remarks, replacing every instance of the text
“surprised” and “nearly shocked” with “utterly astounded,”
type (all on one line):
$ sed 's/surprised\|nearly shocked/utterly
astounded/g' *remarks RET
NOTES: See Appendix D [References for Further Interest], page 731, for more
information on sed.
In this example, the text file novels was created and contains four lines
of text (the last line with the CTRL- D is never part of the file).
Typing text like this without an editor will sometimes do in a pinch but, if
you make a mistake, there is not much recourse besides starting over—you can
type CTRL- U to erase the current line, and CTRL- C to abort the whole
thing and not write the text to a file at all, but that’s about it.
In this example, no files were specified to cat for input, so cat used the
standard input; then, one line of text was typed, and this text was appended
to file novels, the file used in the previous recipe. So now this file would look
like Figure 10-5.
METHOD #1
The shell script given in Figure 10-7 will insert the lines you give it into the
file specified as an argument.
Put it in a file called ins, and install it as a shell script (see Recipe A.3.4
[Installing a Shell Script], page 708).
#!/bin/sh
/bin/ed $1 <<EOF
0a
`cat -`
.
w
q
EOF
Figure 10-7. The ins file.
To insert one or more lines of text at the beginning of a file, give the
name of the file into which the text should be inserted as an argument to ins;
ins will read lines of text from the standard input and insert them at the
beginning of the file. (It works by opening the file in ed, a simple line editor.)
Give the eof—that is, type CTRL- D on a line by itself—to signify the
end of the lines of text to insert.
260 The Linux Cookbook, 2nd Edition
⇒ To insert several lines of text at the beginning of the file novels, type:
This command inserts two lines of text at the beginning of novels, the file
used in the previous examples in this section. This file would now look like
Figure 10-8.
METHOD #2
To use cat to insert text at the beginning of a file, use cat to concatenate the
standard input and the file; redirect this to a new file name that will contain
the file with the inserted text at the beginning.
⇒ To insert several lines of text at the beginning of the file novels, type:
This command writes a new file, novels.tmp, containing the lines you
typed and then the contents of novels. To keep the file with this inserted
text, move novels.tmp to novels.
Chapter 10: Editing Text 261
Clam Chowder
Lobster Bisque
Vegetable
Figure 10-9. The soups file.
6
This is a fairly simple use of m4; it can do much more, including run commands, ma-
nipulate text, and run custom macros. Consult its Info documentation for more (see
Recipe 2.8.5 [Reading an Info Manual], page 48).
262 The Linux Cookbook, 2nd Edition
BLT
Ham on Rye
Roast Beef
Figure 10-10. The sandwiches file.
Soups
-----
include(soups)
Sandwiches
----------
include(sandwiches)
Figure 10-11. The menu file.
⇒ To process the file and write it to the file monday.txt, type:
$ m4 menu > monday.txt RET
Soups
-----
Clam Chowder
Lobster Bisque
Vegetable
Sandwiches
----------
BLT
Ham on Rye
Roast Beef
Figure 10-12. The monday.txt file.
Chapter 10: Editing Text 263
NOTES: You can write more than one include file that will use your files—and
these include files themselves can have inclusions of their own.
AEE The advanced easy editor has a pop-up menu interface and is meant
to be usable with no prior instruction; includes an interface for use
in X, xae.
DEB: aee
RPM: aee
WWW: http://mahon.cwx.net/
Cooledit Cooledit is a popular, fast text editor for use in X; its features
include anti-aliased fonts, Unicode support, and extensibility via
the Python programming language. It’s based on the Midnight
Commander’s terminal editor, and it’s unique in that it is unlike
either Emacs or Vi.
DEB: cooledit
RPM: cooledit
WWW: http://cooledit.sourceforge.net/
DEB: dedit
DEB: e3
RPM: e3
WWW: http://www.sax.de/~adlibit/
DEB: ee
WWW: http://mahon.cwx.net/
DEB: elvis
RPM: elvis
WWW: http://elvis.vi-editor.org/
DEB: emacsen-common
emacs21
RPM: emacs
WWW: http://www.emacs.org/
DEB: glimmer
RPM: glimmer
WWW: http://glimmer.sourceforge.net/
DEB: jed
RPM: jed
WWW: http://www.jedsoft.org/jed/
JOE Joe’s Own Editor, joe, is a full-screen editor with a look and feel
reminiscent of the old dos text editors, such as edit.
DEB: joe
RPM: joe
WWW: http://sourceforge.net/projects/joe-editor/
DEB: le
RPM: le
WWW: http://tinyurl.com/23325
MCedit This is the full-screen terminal editor that comes with the Midnight
Commander.
DEB: mc-common
mc
RPM: mc
WWW: http://www.ibiblio.org/mc/
DEB: nano
RPM: nano
WWW: http://www.nano-editor.org/
DEB: ted
RPM: Ted
WWW: http://www.nllgg.nl/Ted/
DEB: the
the-doc
RPM: THE
WWW: http://hessling-editor.sourceforge.net/
DEB: nvi
RPM: nvi
WWW: http://www.bostic.com/vi/
DEB: vim
RPM: vim
WWW: http://www.vim.org/
DEB: wily
WWW: http://www.cs.yorku.ca/~oz/wily/
DEB: xcoral
RPM: xcoral
WWW: http://xcoral.free.fr/
Xedit Xedit is a simple text editor that comes with, and works in, X. It
lets you insert, delete, copy, and paste text as well as open and save
files—the very basics.
DEB: xbase-clients
RPM: XFree86
WWW: http://www.xfree86.org/
DEB: emacsen-common
xemacs21
RPM: xemacs
WWW: http://www.xemacs.org/
NOTES: If you are using the wrong word to begin with, none of the computer-
ized spell-check tools will correct this error—for example, if you have “there”
when you mean “their,” the computer cannot catch it (yet!).
1
On an increasing number of systems, this file is being replaced with
/usr/share/dict/words; administrators should make a symbolic link from
this to the shorter, preferred form.
2
In other words, they are correct whether they appear entirely in lowercase letters, capi-
talized, or entirely in uppercase letters.
276 The Linux Cookbook, 2nd Edition
$ spell RET
occurance RET
occurance
CTRL- D
$
In this example, spell echoed the word “occurance,” meaning that this
word was not in the system dictionary and therefore was quite likely a mis-
spelling. Then, CTRL- D was typed to exit spell.
NOTES: You can also add (or remove) words by manually editing the file with
a text editor, but take care to keep the list in alphabetical order!
3
If a word is reasonably universal, you may, of course, contact the global maintainers of
wenglish or other appropriate packages, and try to convince them that said word ought
to be included.
4
On newer systems, this file is sometimes replaced by ~/aspell_default.
278 The Linux Cookbook, 2nd Edition
Use ispell to spell check a file interactively, so that every time a misspelling
is found, you’re given a chance to replace it then and there.5
⇒ To interactively spell-check fall-lecture.notes, type:
$ ispell fall-lecture.notes RET
When you type this, ispell begins checking the file. It stops at the first
misspelling it finds, as in Figure 11-1.
On the top line of the screen, ispell displays the misspelled word, fol-
lowed by the name of the file. Underneath this is the sentence in which the
misspelling appears, with the word in question highlighted. Following this is
a list of suggested words, each offset by a number—in this example, ispell
has only one suggestion: “lectures.”
To replace a misspelling with a suggested word, type the number that
corresponds to the suggested word (in this example, you would type 0 to
replace the misspelling with “lectures”). You only need to type the number
of your selection—a RET is not required.
5
aspell is designed to be a drop-in replacement for ispell, with greatly improved sug-
gestion algorithms. If your system has aspell, use it instead; it otherwise works like
ispell.
Chapter 11: Grammar and Reference 279
Figure 11-1. A misspelling caught by ispell.
You can also type a correction yourself; this is useful when ispell either
offers no suggestions, or when it does and the word you want is not one of
them. To do this, type r (for “replace”) and then type the replacement word,
followed by RET.
Sometimes, ispell will question a word that you may not want to count
as a misspelling, such as proper names and the like—words that don’t appear
in the system dictionary. There are a few things you can do in such cases, as
follows.
To accept a misspelled word as correct for the current ispell session only,
type a; from then on during the current session, this word will be considered
correct.
If, however, you want ispell (and spell, and all other tools that access
the system dictionary) to remember this word as being correct for this and
all future sessions, insert the word in your own personal dictionary. Type u
to insert a copy of the word uncapitalized, in all lowercase letters—this way,
even if the word is capitalized at the beginning of a sentence, the lowercase
version of the word is saved. From then on, in the current ispell session
and in future sessions, this word will be considered correct whether it appears
entirely in lowercase letters, capitalized, or entirely in uppercase letters.
When case is important to the spelling—for example, in a word that
is a proper name such as “Seattle,” or a word with mixed case, such as
“DeSalle”—type i to insert a copy of the word in your personal dictionary
with its case just as it appears; this way, words spelled with the same letters
but with different cases will be considered misspellings.
When ispell finishes spell-checking a file, it saves its changes to the file
and then exits. It also makes a copy of the original file, without the changes
280 The Linux Cookbook, 2nd Edition
applied; this file has the same name as the original but with .bak added to
the end—in our example, the backup file is called fall-lecture.notes.bak.
This is useful if you regret the changes you’ve made and want to restore the
file to how it was before you mucked it up—just remove the spell-checked file
and then rename the .bak file to its original name.
The following table is a reference to the ispell key commands, listing the
keys and describing their actions.
The first command, ispell-word, checks the spelling of the word at point;
if there is no word at point, it checks the first word to the left of point. This
command has a keyboard shortcut, ALT- $. The second command, ispell-
region, checks the spelling of all words in the currently selected region of
text. The third command, ispell-buffer, checks the spelling of the entire
buffer.
⇒ Here are some ways to use this.
• To check the spelling of the word at point, type:
ALT- X ispell-word RET
The term dictionary on Linux systems generally refers to one of two things:
the traditional Unix-style dictionary, which is an alphabetically sorted word
list containing no actual definitions, and the newer database-style dictionary
that contains the headwords as well as their definitions. The latter is the
kind of thing most people mean when they talk about dictionaries. (When
most Unix folk talk about dictionaries, however, they almost always mean the
former.)
WordNet is a lexical reference system in the form of a database containing
thousands of words arranged in synonym sets. You can search the database
and output the results in text with the wn tool or the wnb X client (the
“WordNet browser”).
Use of the X client is fairly straightforward—type a word in the dialog box
near the top of the screen, followed by RET, to get its definitions, which are
displayed in the large output window underneath the dialog box.
For example, when you do a search for the definition of the word “browse,”
the WordNet browser will look like Figure 11-2.
part of speech a word may have; in the preceding example, the word “browse”
can be either a noun or a verb, so two menus are shown.
To get a list of all word sense information available for a given word, run wn
with the word as an argument. This outputs a list of all word sense information
available for the word, with each possible sense preceded with the name of the
option to use to output it.
⇒ To output a list of word senses available for the word “browse,” type:
$ wn browse RET
To find some words that rhyme with a given word, use grep to search
/usr/dict/words for words ending in the same last few characters as the
284 The Linux Cookbook, 2nd Edition
word they should rhyme with (see Recipe 14.4.2 [Matching Lines Ending with
Certain Text], page 343).
⇒ To output a list of words that rhyme with “friend,” search
/usr/dict/words for lines ending with “end”:
$ grep 'end$' /usr/dict/words RET
The dict Development Group has a number of free dictionaries on its Web site
[http://www.dict.org/]. On that page, you can look up words (including
using a thesaurus and other searches) from a dictionary that contains over
300,000 headwords, or you can make a copy of its dictionary for use on your
own system. A dict client exists for accessing dict servers and outputting
definitions locally; this tool is available in the dict package.
286 The Linux Cookbook, 2nd Edition
Two venerable unix tools for checking writing have recently been made avail-
able for Linux-based systems: style and diction.
Old-timers probably remember these names—the originals came with
at&t unix as part of the much-loved “Writer’s Workbench” (wwb) suite
of tools back in the late 1970s and early 1980s.7
at&t “unbundled” the Writer’s Workbench from its unix Version 7 prod-
uct, and as the many flavors of unix blossomed over the years, these tools
were lost by the wayside—eventually becoming the stuff of unix lore.
In 1997, Michael Haardt wrote new Linux versions of these tools from
scratch. They support both the English and German languages, and they’re
now part of the gnu Project.
Two additional commands that were part of the Writer’s Workbench have
long been standard on Linux: look and spell, described previously in this
chapter.
The following are recipes that use either diction or style.
If you don’t specify a file name, diction reads text from the standard
input until you type CTRL- D on a line by itself. This is especially useful
when you want to check a single sentence, as in Figure 11-3.
$ diction RET
Let us ask the question we wish to state. RET
(stdin):1: Let us [ask the question -> ask]
[we wish to state -> (cliche, avoid)].
CTRL- D
$
Figure 11-3. Checking a sentence with diction.
To check the text of a Web page, use lynx with the -dump and -nolist
options to output the plain text of a given url, and pipe this output to
diction. (If you expect there to be a lot of output, add another pipe at the
end to less so you can peruse it.)
To peruse the url http://www.westegg.com/cliche/random.cgi with
markings for possible wordy and misused phrases, type (all on one line):
$ lynx -dump -nolist http://www.westegg.com/cliche/random.cgi |
diction | less RET
288 The Linux Cookbook, 2nd Edition
NOTES: To check text for overused words, use the method described in
Recipe 12.2.4 [Counting Word Occurrences in Text], page 299.
Like diction, style reads text from the standard input if no text is
given—this is useful for the end of a pipeline, or for checking the writing
style of a particular sentence or other text you type.
The sentence characteristics of the text that style outputs are as follows:
• Number of characters
• Number of words, their average length, and their average number of syl-
lables
• Number of sentences and average length in words
• Number of short and long sentences
• Number of paragraphs and average length in sentences
• Number of questions and imperatives
The various readability formulas that style uses and outputs are as fol-
lows:
Chapter 11: Grammar and Reference 289
8
To get an idea how the ari ranks text, see its rankings for various popular Web sites at
http://www.readability.info/commonscores.shtml.
290 The Linux Cookbook, 2nd Edition
The gnu Miscfiles collection is a group of text files containing various facts
and reference material, such as common abbreviations, telephone area codes,
and English connective phrases.
The files are stored in the /usr/share/misc directory, and they are
all compressed; use zless to peruse them (see Recipe 9.1 [Perusing Text],
page 211).
The following table lists the files as they appear in /usr/share/misc and
describes their contents.
But miscfiles is not the only reference package available for Linux; other
related packages include the following:
NOTES: The official gnu miscfiles distribution also includes the Jargon
File and the /usr/dict/words dictionary file, which are available in separate
packages for Debian, and are removed from the Debian miscfiles distribu-
tion. On Debian systems, /usr/dict/words is part of the standard spelling
packages, and the Jargon File comes in the optional jargon package and in-
stalls in /usr/share/jargon.
Use wtf to see what an acronym stands for. This is useful for decoding the
kind of acronyms commonly used in Usenet chatter and other online chat
forums. If it doesn’t know the answer, it checks with whatis before giving
up (see Recipe 2.8.2 [Getting a Description of a Program], page 46), so it will
also tell you what any tool or program installed on the system is.
Give the acronym to translate as an argument to wtf, optionally preceded
by “is.”
⇒ To translate the acronym “lol,” type:
$ wtf lol RET
NOTES: While wtf is useful for decoding the acronyms of online writing, it
doesn’t know anything outside of this scope. So it can’t tell you, for instance,
what laser stands for (but the WordNet dictionary can—see Recipe 11.2
[Using Dictionaries], page 282), although it will tell you all about how ymmv
even when you do rtfb, so you see it is nbd.
Other collections of acronyms are available with the miscfiles collection
(see Recipe 11.4.1 [Consulting Word Lists and Helpful Files], page 290).
Chapter 12: Analyzing Text 293
NOTES: You can get a count of how many different words are in a text, too—
use the method described in Recipe 12.2.3 [Listing Only the Unique Words
in Text of a Text], page 298, and pipe the output to wc. To count the aver-
age length of words, sentences, and paragraphs, use style (see Recipe 11.3.3
[Checking Text for Readability], page 288).
294 The Linux Cookbook, 2nd Edition
NOTES: This counts the number of words in a text; to count the number of
times a word occurs, see Recipe 12.2 [Listing Words in Text], page 297.
METHOD #1
Use wc with the -l option to specify that just the number of lines be counted
and output.
⇒ To output the number of lines in the file outline, type:
$ wc -l outline RET
METHOD #2
The count-lines-page function in Emacs outputs in the minibuffer the num-
ber of lines on the current page (as delimited by pagebreak characters, if
any—see Recipe 13.3 [Paginating Text], page 312), followed by the number
of lines in the buffer before the line that point is on, and then the number of
lines in the buffer after point.
⇒ To count the number of lines per page in the current buffer in Emacs,
type:
CTRL- X l
Chapter 12: Analyzing Text 295
Emacs outputs the number of lines per page of the current buffer in the
echo area.
For example, suppose the output in the minibuffer is this:
Page has 351 lines (69 + 283)
This means that the current page contains 351 lines, and point is on line
number 70—there are 69 lines before this line and 283 lines after it.
NOTES: This method is quick and easy, but it will not count more than one
occurrence on the same line, and it won’t find occurrences that are broken by
the end of a line.
For more recipes for searching text, and more about grep, see Chapter 14
[Searching Text], page 333.
To remove all of the punctuation from the listed words, pipe the output to
another tr that deletes it.
⇒ To peruse a list containing all of the words from the text file book as they
appear in the text, but with punctuation removed, type:
$ tr -s '[:blank:]' '\n' < book | tr -d '[:punct:]' | less RET
Dashes are not removed with punctuation. If the text to filter contains
em dashes consisting of two hyphens (--) with no spaces between the words
on either side of the dashes, first filter them out by with sed, replacing them
with a space character (see Recipe 10.5 [Editing Streams of Text], page 255).
Then pass that filtered text to tr.
298 The Linux Cookbook, 2nd Edition
⇒ To peruse a list containing all of the words from the text file book as they
appear in the text, but with punctuation removed, type (all on one line):
$ sed 's/--/ /g' book | tr -s '[:blank:]' '\n' |
tr -d '[:punct:]' | less RET
NOTES: If there is any whitespace before the first word in the input, this
method inserts a newline character at the beginning of the output. To remove
it, add tail +2 to the end of the pipeline but before you peruse or print it
(see Recipe 9.2.3 [Displaying the End Part of Text], page 218).
METHOD #1
To get a word-frequency count of words in some text, use the method as
described in the previous recipe but give the -c option to uniq, which will
precede each line with its count (the number of times it occurs in the text).
Then pipe the output to sort with the -n option to sort numerically and -r
to reverse the order.
⇒ Here are some ways to use this.
• To peruse a listing of all the words from the text file book with
punctuation removed, sorted by their frequency, listed with their
number of occurrences and beginning with the most frequent, type
(all on one line):
$ tr -s '[:blank:]' '\n' < book | tr -d '[:punct:]'
| sort | uniq -c | sort -n -r | less RET
300 The Linux Cookbook, 2nd Edition
• To peruse a listing of all the words from the text file book with
punctuation removed, sorted by their frequency regardless of case,
listed with their number of occurrences and beginning with the most
frequent, type (all on one line):
$ tr -s '[:blank:]' '\n' < book | tr -d '[:punct:]'
| tr '[:upper:]' '[:lower:]' | sort | uniq -c |
sort -n -r | less RET
METHOD #2
To get the total number of different words in a text, use the method for listing
unique words as described in the previous recipe, and pipe the output to wc
with the -l option. This counts all the lines of its input—which in this case
will be the list of unique words, one per line.
⇒ To output a total count of the number of unique words in the text file
book, type (all on one line):
$ tr -s '[:blank:]' '\n' < book | tr -d '[:punct:]' |
sort | uniq | wc -l RET
• To list the words that occur between eighty and eighty-five times in
the text file book with punctuation removed, type (all on one line):
$ tr -s '[:blank:]' '\n' < book | tr -d '[:punct:]'
| sort | uniq -c | sort -n -r | grep '^[ ]*8[0-5]
CTRL- Q CTRL- V' RET
consist entirely of exactly identical lines). To specify the threshold value, give
a number from 0 to 100 as an option after the two file names.
To ignore exact duplicates, give a fourth option. This can be any value or
character, so long as it’s there.
⇒ Here are some ways to use this.
• To output a list of any lines in the files invitations and addresses
that are similar to each other, type:
$ compare invitations addresses RET
• To output a list of any lines in the files weddings and parties that
match with a threshold level of 85 percent similarity, type:
$ compare weddings parties 85 RET
• To output a list of any lines in the files invitations and addresses
that are similar to each other, but not output exact duplicates, type:
$ compare invitations addresses 50 1 RET
NOTES: This tool has many handy uses. Use it whenever you might search
for close similarities, but not necessarily identical strings, in two samples of
text. For example, comparing catalog or sale lists with collector wish lists;
detecting plagiarism and authorship; and comparing reading lists. Its author
uses it to find and identify allusions in works of literature.
METHOD #1
Use fmt with the -u option to output text with “uniform spacing,” where the
space between words is reduced to one space character and the space between
sentences is reduced to two space characters.
⇒ To output the file term-paper with uniform spacing, type:
$ fmt -u term-paper RET
METHOD #2
Use cat with the -s option to “squeeze” multiple adjacent blank lines into
one.
⇒ To output the file term-paper with multiple blank lines output as only
one blank line, type:
$ cat -s term-paper RET
306 The Linux Cookbook, 2nd Edition
METHOD #3
You can combine both of these commands to output text with multiple adja-
cent lines removed and with uniform spacing between words. The following
example sends the output of the combined commands to less so that it can
be perused on the screen.
⇒ To peruse the text file term-paper with multiple blank lines removed and
giving the text uniform spacing between words, type:
$ cat -s term-paper | fmt -u | less RET
Notice that in this example, both fmt and less worked on their standard
input instead of on a file—the standard output of cat (the contents of term-
paper with extra blank lines squeezed out) was passed to the standard input of
fmt; its standard output (the space-squeezed term-paper, now with uniform
spacing) was sent to the standard input of less, which displayed it on the
screen.
METHOD #1
To remove all empty lines from text output, use grep with the regular expres-
sion “.” to match any character, and will therefore match any line that isn’t
empty (see Recipe 14.3 [Matching Patterns of Text], page 335). You can then
redirect this output to a file, or pipe it to other commands. The original file
is not altered.
⇒ To output all non-empty lines from the file term-paper, type:
$ grep . term-paper RET
This command outputs all lines that are not empty—so lines containing
only non-printing characters, such as spaces and tabs, will still be output.
METHOD #2
To remove from the output all empty lines, and all lines that consist of only
space characters, use grep with “[^ ].” as the regexp to search for.
⇒ To output only the lines from the file term-paper that contain more than
just space characters, type:
$ grep '[^ ].' term-paper RET
Chapter 13: Formatting Text 307
NOTES: This regexp will still output lines that contain only tab characters.
METHOD #3
To remove from the output all empty lines, and lines that contain only a
combination of tab or space characters, use grep with “[^[:space:]].” as
the regexp to search for. It uses the special predefined “[:space:]” regexp
class, which matches any kind of space character at all, including tabs.
⇒ To output only the lines from the file term-paper that contain more than
just space or tab characters, type:
$ grep '[^[:space:]].' term-paper RET
METHOD #4
If a file is double-spaced, where all even lines are blank, you can remove those
lines from the output by using sed with the “n;d” expression.
⇒ To output only the odd lines from file term-paper, type:
$ sed 'n;d' term-paper RET
⇒ To triple-space the file term-paper and write the output to the file term-
paper.print, type:
$ sed 'G;G' term-paper > term-paper.print RET
The “G” expression appends one blank line to each line of sed’s output;
using “;” you can specify more than one blank line to append (but you must
quote this command, because the semicolon (;) has meaning to the shell—see
Recipe 3.1.3 [Quoting Reserved Characters], page 56). You can use multiple
“G” characters to output text with more than double or triple spaces.
⇒ To quadruple-space the file term-paper, and write the output to the file
term-paper.print, type:
$ sed 'G;G;G' term-paper > term-paper.print RET
NOTES: sed is described in Recipe 10.5 [Editing Streams of Text], page 255.
This command is almost always used for printing, so the output is usually
just piped to lpr instead of being saved to a file. Many text documents have
a width of 80 and not 72 columns; if you are printing such a document and
need to keep the 80 columns across the page, specify a new width of 85. If
your printer can only print 80 columns of text, specify a width of 80; the text
will be reformatted to 75 columns after the 5-column margin.
⇒ Here are two ways to use this.
• To print the file owners-manual with a 5-column margin and 80
columns of text, type:
$ pr -t -o 5 -w 85 owners-manual | lpr RET
• To print the file ‘owners-manual’ with a 5-column margin and 75
columns of text, type:
$ pr -t -o 5 -w 80 owners-manual | lpr RET
NOTES: You can also use col with the -x option to turn all tabs in its input
to spaces.
To replace the newline character with some other character, use tr, giving
the newline character as the first quoted set, and the character to replace it
with as the second.
⇒ To take the text in the file many and replace any newlines with a formfeed,
and then send the output to the printer, type:
$ tr '\n' '\f' < many | lpr RET
that is typed); in some operating systems, lines end with both a newline char-
acter and a carriage return character (represented by “\m”). This shows up
as “^M” in a file. Remove them with col.
⇒ To process a file named operating_plan.txt, filtering out any carriage
returns from the text, and writing this filtered text to a new file called
operating_plan, type:
$ col < operating_plan.txt > operating_plan RET
You can then view the literal characters of both the raw and the processed
files to see that the carriage returns, displayed as “\r” in the raw file, are
gone—see Recipe 9.2.6 [Displaying the Literal Characters of Text], page 221.
NOTES: The brackets contain two characters: a space and a tab. In order to
pass the literal tab to this command, you do a verbatim insert by first typing
CTRL- V and then the key you want—in this case, TAB.
There are many options that you can use to customize the output of text
you paginate.
Chapter 13: Formatting Text 313
NOTES: It’s also common to use pr to change the spacing of text (see
Recipe 13.1 [Spacing Text], page 305).
NOTES: If a page has more lines than a printer can fit on a physical sheet of
paper, it will automatically break the text at that line as well as at the places
in the text where there are formfeed characters.
Use the -t option to omit the header and footer on each page entirely, and
use -T to omit the header, footer, and any formfeed characters that are in the
file.
314 The Linux Cookbook, 2nd Edition
⇒ To paginate the text in the file listings with no headers or footers, but
retaining any existing formfeeds, type:
$ pr -t listings RET
NOTES: There is currently no pr option to place headers on all but the first
page, so if you need to format text in this common convention, first use pr to
output to a file without headers, then use pr to output to another file with the
headers you want for the remaining pages. Then, use a text editor to combine
the first page of the former with the remaining pages of the latter.
To paginate columns from multiple files, use -m. The contents of the files
given as arguments are output together, each in its own column.
⇒ To output the text in col.1, col.2, and col.3 in paginated columns
with no headers, and with pages separated by formfeeds, outputting to a
file called comparisons, type:
$ pr -t -f -m col.1 col.2 col.3 > comparisons RET
Columns are made to fit pages of 72-character line widths; the columns are
truncated to fit this size unless you give the -J option, which makes columns
big enough to fit the text, regardless of line width.
⇒ To print the file results.data in six columns and not truncating long
lines, type:
$ pr -6 -t -J results.data | lpr RET
Use the -a option to output in rows (columns running across the page)
instead of columns running down.
⇒ To output the text in col.1, col.2, and col.3 in paginated columns
going across, outputting to a file called comparisons, type:
$ pr -a -m col.1 col.2 col.3 > comparisons RET
NOTES: You can also use head or tail to display only a certain part of the
text, such as an ending or a middle part, and pipe that to pr for pagination
(see Recipe 9.2 [Displaying Text], page 216).
To change a set of characters in some text to another given set, use tr and
give the two sets as arguments.
⇒ Here are some ways to use this.
• To output the contents of the file scanner-copy, translating all cap-
ital “O” characters to zeroes (0) in the output, type:
$ tr O 0 < scanner-copy RET
• To output the contents of the file CAPS, translating all uppercase
letters to their lowercase equivalents, type:
$ tr A-Z a-z < CAPS RET
318 The Linux Cookbook, 2nd Edition
In this example, only one set is given; any characters in that set that repeat
are squeezed into a single instance of the character.
Use two sets to replace a set of repeated characters with some other set.
⇒ To output the contents of the file moo, with all repeated “o” and “O”
characters replaced by one instance of “e” or “E,” type:
$ tr -s oO eE < moo RET
In the preceding example, any repeated characters other than “o” and “O”
are untouched, as are any “o” and “O” characters that are not repeated.
1
This example is equivalent to the previous example; one specifies text with a range and
another with a character class, but both produce the same result.
Chapter 13: Formatting Text 319
METHOD #1
The uniq tool outputs only the unique lines of its input—any lines occurring
more than once are only output once. The input must be sorted; that is,
duplicate lines must be neighboring (see Recipe 13.6 [Sorting Text], page 320).
⇒ To output the contents of the file options, with all duplicate lines filtered
out, type:
$ uniq options RET
To output only the lines that have duplicates, use the -d option. To output
only the lines that have duplicates, plus every instance of each duplicate line,
use -D instead.
⇒ Here are two ways to use this.
• To output only the lines in the file options that have duplicates, but
not the duplicates themselves, type:
$ uniq -d options RET
• To output all of the lines in the file options that have duplicates,
and all the duplicates themselves, type:
$ uniq -D options RET
METHOD #2
To filter out unique lines in some unsorted text, use sort with the -u option.
This sorts the input lines alphabetically and runs uniq on them.
320 The Linux Cookbook, 2nd Edition
Shantung
Honan
Szechwan
Hunan
Kiangsu
Kwangtung
Fukien
Figure 13-1. The provinces file.
⇒ Here are two ways to use this.
• To sort the file provinces and output all lines in ascending order,
type:
• To sort the file provinces and output all lines in descending order,
type:
To write the output to a file, give the file name as an argument to the -o
option.
⇒ To sort the file provinces and write all lines in descending order to the
file provinces.sorted, type:
$ sort -r -o provinces.sorted provinces RET
Use the -i option to ignore all spaces and all non-printing characters.
⇒ To sort the text in file orders, ignoring any preceding blank spaces and
non-printing characters, type:
$ sort -i orders RET
By default, the first field is used in both files. To specify the field for
the first file, use the -1 option and give the number of the field to use as an
argument; to specify the field for the second file, use -2.
⇒ To output the contents of the sorted files march.stats and april.stats,
joining by the third column in the first file and the second column in the
second file, type:
$ join -1 3 -2 2 march.stats april.stats RET
Columns are filled before rows. That is, the input lines run down the first
column, and then down the next, and so on. To have the input lines fill across
the rows instead, use the -x option.2
2
Some versions have documentation stating the opposite of this effect, but the program
works this way in practice.
324 The Linux Cookbook, 2nd Edition
⇒ To write the contents of the file years.list to a file called years, written
in columns of lines not longer than 80 characters and filling each row
before advancing to the next, type:
$ column -x years.list > years RET
To specify the number of characters to put in each line, give it as an
argument to the -c option.
⇒ To columnate the text in the file YearEnd.Financials with a line length
of 120 characters, and output it to the printer named finance, type:
$ column -c120 < YearEnd.Financials | lpr -Pfinance RET
METHOD #1
Use cut to output selected columns (called fields) from text. Give the fields
to output as arguments to the -f option. You can specify multiple fields by
delimiting them with commas, and you can specify a range of fields with a
hyphen character (-).
⇒ Here are some ways to use this.
• To output only the first field from the file bank-statement, type:
$ cut -f1 bank-statement RET
• To output the second and fourth fields from the file bank-statement,
type:
$ cut -f2,4 bank-statement RET
• To output the first and the third through fifth fields from the file
bank-statement, type:
$ cut -f1,3-5 bank-statement RET
Fields are output from lowest to highest, no matter which order you specify
them. If you specify a field out of range for the input text, cut outputs a blank
line for each line of input, and if cut can find no field at all in an input line,
it outputs the entire line. Use -s to suppress the printing of lines that do not
contain the selected field.
By default, cut counts fields as delimited by a tab character. To specify
some other delimiter, give it as an argument to the -d option.
Chapter 13: Formatting Text 325
⇒ To output only the second field from the file bank-statement, where
fields are delimited by a space character, and suppress output of lines not
containing this field, type:
$ cut -d " " -f2 bank-statement RET
Fields are output with the same delimiter used in the input. To specify
a different delimiter for the output, give it as an argument to the long-style
option --output-delimiter.
⇒ To take the third through fifth fields from the file ‘bank-statement,’
where fields are delimited by a space character, and output them delim-
ited by tab characters, type:
$ cut -d " " -f3-5 --output-delimiter CTRL- V TAB
bank-statement RET
METHOD #2
Use colrm to remove columns in text by their character positions. Given a
number as an argument, colrm will remove all text on each line, beginning at
that character position.
⇒ To output only the first two characters on each line of the file
percentages, type:
$ colrm 3 < percentages RET
METHOD #1
One way to number text is to use the nl (“number lines”) tool. Its default
action is to write its input (either the file names given as an argument, or
the standard input) to the standard output, with an indentation and all non-
empty lines preceded with line numbers.
⇒ To peruse the file report with each line of the file preceded by line num-
bers, type:
$ nl report | less RET
You can set the numbering style with the -b option followed by an ar-
gument. The following table lists the possible arguments and describes the
numbering style they select.
METHOD #2
The other way to number lines is to use cat with one of the following two
options: The -n option numbers each line of its input text, while the -b option
only numbers non-blank lines.
⇒ Here are two ways to use this.
• To peruse the text file citations with each line of the file numbered,
type:
$ cat -n citations | less RET
• To peruse the text file citations with each non-blank line of the file
numbered, type:
$ cat -b citations | less RET
In the preceding examples, output from cat is piped to less for perusal;
the original file is not altered.
To take an input file, number its lines, and then write the line-numbered
version to a new file, send the standard output of the cat command to the
new file to write.
⇒ To write a line-numbered version of file report to file report.lines,
type:
$ cat -n report > report.lines RET
The following recipes are for placing, converting, or removing these differ-
ent types of underlines in text.
METHOD #1
To place “_etext-style_” underlines in text, you just type an underscore
character before and after the text to be underlined. (Another variation is
to use the underscore for any space characters within the underlined text,
“_just_like_this_.”)
METHOD #2
To place an overstrike-style underline in some text, you need to insert a literal
backspace character (“Control-H”) immediately after a character you want to
underline, and follow that with an underscore character (_).
⇒ Here are two ways to use this.
You can convert one form to the other by using the Emacs replace-
regular-expression function and specifying the text to be replaced as
a regexp (see Recipe 14.3 [Regular Expressions—Matching Text Patterns],
page 335).
⇒ Here are some ways to use this.
• To replace plaintext-style italics with TEX \it commands, type:
ALT- X replace-regular-expression RET
_\([^_]+\)_ RET
\{\\it \1} RET
• To replace TEX-style italics with etext style underscores , type:
ALT- X replace-regular-expression RET
\{\\it \{\([^\}]+\)\} RET
_\1_ RET
Both of these examples use the special regexp symbol “\1,” which matches
the same text matched by the first “\( ... \)” construct in the previous
regexp.
NOTES: For more information on regexp syntax in Emacs, consult its Info
documentation (see Recipe 2.8.5 [Reading an Info Manual], page 48).
METHOD #1
To remove backspace underlining from text, use colcrt with the - option, as
described in Method #3 of Recipe 9.3.5 [Viewing Underlined Text], page 226.
⇒ To output a file containing backspace underlining called
zim.bibliography, writing to a new file called zimbib.txt
with no underlines at all, type:
$ colcrt - zim.bibliography > zimbib.txt RET
METHOD #2
To remove any text that is marked with underlines and not remove the under-
lines themselves, send the text to col with the -b option. This removes all of
the characters to be underlined, and the backspace character (“Control-H”)
that follows each one. The underline characters (_) are kept.
330 The Linux Cookbook, 2nd Edition
NOTES: This is also good for removing overstrikes from text, where a char-
acter such as “X” is used in place of an underline.
Specify a different separator with the -s option. This is often useful when
specifying non-printing characters, such as formfeeds. To specify such a char-
acter, use the ansi-c method of quoting (see Recipe 3.1.3 [Quoting Reserved
Characters], page 56).
⇒ To output prizes in page-for-page reverse order, type:
$ tac -s $'\f' prizes RET
The preceding example uses the formfeed, or page break, character as the
delimiter, so it outputs the file prizes in page-for-page reverse order, with
the last page output first.
Use the -r option to use a regular expression for the separator string (see
Recipe 14.3 [Regular Expressions—Matching Patterns of Text], page 335).
You can build regular expressions to output text in word-for-word and
character-for-character reverse order:
⇒ Here are two ways to use this.
• To output prizes in word-for-word reverse order, type:
$ tac -r -s '[^a-zA-z0-9\-]' prizes RET
Chapter 13: Formatting Text 331
Use the -i option to ignore the case when looking for matches.
⇒ To output lines in the file catalog containing “cd,” regardless of case,
type:
$ grep -i cd catalog RET
This search matches any lines in catalog where the pattern “cd” is found,
regardless of case. So it will match lines containing “CD” and “cd,” as well as
any other variation in case, like “Cd.”
However, this search also matches lines containing, say, the word
“anecdote,” as well as words like “CDROM” or “CDR,” because grep matches
patterns wherever they occur on a line.
To specify that only whole words should count as matches, use grep with
the -w option. This ignores matches that occur in the middle of a word. Only
entire words will count as a pattern match, which means the pattern’s location
must match two criteria: One, it must be either at the beginning of the line,
or be directly preceded by non-letters and non-digits; and two, it must either
be directly followed by non-letters or non-digits, or be at the end of the line.
⇒ To output lines in the file catalog containing the word “CD,” type:
$ grep -w CD catalog RET
1
The origin of its name is explained in Recipe 14.3 [Regular Expressions—Matching Pat-
terns of Text], page 335, where its advanced usage is discussed.
334 The Linux Cookbook, 2nd Edition
In this example, only lines containing the word “CD” are printed; lines with
words such as “CDROM” or “anecdote” are not printed unless they contain the
word “CD.”2
The preceding example outputs all lines in the file catalog that contain
the exact string “Compact Disc”; it will not match, however, lines containing
“compact disc” or any other variation on the case of letters in the search
pattern. Use the -i option to specify that matches are to be made regardless
of case.
⇒ To output lines in the file catalog containing the string “compact disc”
regardless of the case of the letters, type:
$ grep -i 'compact disc' catalog RET
This command outputs lines in the file catalog containing any variation
on the pattern “compact disc,” including “Compact Disc,” “COMPACT DISC,”
and “comPact dIsC.”
One thing to keep in mind is that grep only matches patterns that appear
on a single line, so in the preceding example, if one line in catalog ends with
the word “compact” and the next begins with “disc,” this command will not
match either line. There is a way around this with grep (see Recipe 14.4.3
[Finding Phrases Regardless of Spacing], page 343), and there is a way to do
it in Emacs (see Recipe 14.9.2 [Searching for a Phrase in Emacs], page 353).
A search string may contain tab characters as well as space characters. To
type a tab character in a quoted string, first type CTRL- V and then type
TAB (see Recipe 3.1.2 [Typing a Control Character], page 55).
⇒ To output lines in screenplay containing the text “In the beginning,”
only when directly preceded by a tab character, type:
$ grep ' CTRL- V TABIn the beginning' screenplay RET
Some special characters have reserved meanings, and to search for them
you must specify them in special ways, as described in the next recipe. The
2
However, the word “CD-ROM” would count as a match; grep considers the hyphen char-
acter to be a word separator, and thus sees “CD-ROM” as two words.
Chapter 14: Searching Text 335
period character (.) is one such character. When searching for just strings,
though, you can use the -F option to specify that the pattern you give is a
fixed string, with no special characters in it at all.
fgrep is equivalent to grep with the -F option. It is one of two variations
of grep assigned to perform a special purpose (the other is discussed below).
⇒ Here are two ways to use this.
• To search the file screenplay for the phrase “the end.,” regardless
of case, type:
$ grep -F 'the end.' screenplay RET
• To search the file screenplay for the phrase “the end.,” regardless
of case, type:
$ fgrep 'the end.' screenplay RET
The results of the two preceding examples are identical.
To search for a string containing double quote characters, use single quotes
to quote it, and vice versa. When the text you search for contains both kinds
of quote characters, don’t quote the string at all, but precede every quote and
space character in the string with a backslash character (\).
⇒ Here are some ways to use this.
• To output all lines in the file screenplay that contain the string
“"Frankly, Scarlett," he said,” type:
$ grep '"Frankly, Scarlett," he said' screenplay RET
• To output all lines in the file screenplay that contain the string “I
don’t give,” type:
$ grep "I don’t give" screenplay RET
• To output all lines in the file screenplay that contains the string
“Don't say "Goodbye",” type:
$ grep Don\'t\ say\ \"Goodbye\" screenplay RET
3
Since “nothing” can be found in the space between any two characters, the empty set
matches every line of its input, which can be useful in some scenarios.
4
You could also use fgrep to search, as described in See Recipe 14.2 [Searching Text for
a Phrase], page 334, but then your regexps would have to contain no metacharacters at
all.
Chapter 14: Searching Text 337
NOTES: The name “grep” derives from a command in the now-obsolete unix
ed line editor tool. The ed command for searching globally through a file for a
regular expression, and then printing on the screen those lines that contained a
match, was g/re/p, where re was the regular expression you’d use. Eventually,
the grep command was written to do this search on a file when not using ed.5
The grep variant egrep, “extended grep,” recognizes all of the extended
metacharacters without the preceding “\.” You can get the same effect in
plain grep by using the -E option.
The following sections describe some regexp recipes for commonly searched-
for patterns.
5
The ed command is still available on virtually all unices, Linux included, and the old
‘g/re/p’ still works. Perhaps an oft-used function, available only in one application
today, might become one of the new tools of tomorrow.
Chapter 14: Searching Text 339
For longer lines, where you don’t want to have to be counting periods, it
is more useful to use a different construct: “^.\{number\}$,” where number
is the number of lines to match. Use “,” to specify a range of numbers.
⇒ Here are two ways to use this.
• To output all lines in /usr/dict/words that are exactly 17 charac-
ters wide, type:
$ grep '^.\{17\}$' /usr/dict/words RET
• To output all lines in /usr/dict/words that are 25 or more charac-
ters wide, type:
$ grep '^.\{25,\}$' /usr/dict/words RET
This command outputs any lines in “playlist” that match the pattern
“the sea” or “cake,” including lines matching both patterns.
⇒ To output all lines in playlist that contain both patterns “the sea”
and “cake,” regardless of case, type:
$ grep -i 'the sea' playlist | grep -i cake RET
(continued)
To Match . . . Use This Regexp
An ip address [0-9]\{1,3\}\.[0-
9]\{1,3\}\.[0-
9]\{1,3\}\.[0-9]\{1,3\}
A Social Security number [0-9]\{3\}-\?[0-
9]\{2\}-\?[0-9]\{4\}
A United States telephone number \(1\+\)\?\(\(\?[0-
9]\{3\}\)\?\)\?\(-
\)\?[0-9]\{3\}\(-
\)\?[0-9]\{4\}
The following table shows how some of the preceding searches are simplified
with egrep.
An ip address [0-9]{1,3}\.[0-
9]{1,3}\.[0-
9]{1,3}\.[0-9]{1,3}
A Social Security number [0-9]{3}-?[0-
9]{2}-?[0-9]{4}
A United States telephone number (1+)?((?[0-9]{3})?)?(-
)?[0-9]{3}(-)?[0-9]{4}
NOTES: These regexps were quoted with single-quote characters; this is be-
cause some shells otherwise treat the “^” character as a special “metacharac-
ter” (see Recipe 3.1.3 [Quoting Reserved Characters], page 56).
NOTES: To use “$” in a regexp to find words that rhyme with a given word,
see Recipe 11.2.1 [Listing Words That Match a Pattern], page 283.
6
If the input is a file, use cat to do this, as in the example.
344 The Linux Cookbook, 2nd Edition
NOTES: The Emacs editor has its own special search for doing this—see
Recipe 14.9.2 [Searching for a Phrase in Emacs], page 353.
You can also reverse the order and use the -v option to output all lines
containing a given pattern that are not in a given context.
⇒ To list lines from the file email-archive that contain the word
“narrative,” but not when it is quoted, type:
$ grep narrative email-archive | grep -v '^>' RET
To output matches and the two lines before them, use -B; to output matches
and the two lines after them, use -A. Give a numeric value with either of these
options to specify that number of context lines instead of the default.
⇒ Here are some ways to use this.
• To search /usr/dict/words for lines matching “tsch” and output
two lines of context before each line of output, type:
$ grep -B tsch /usr/dict/words RET
• To search /usr/dict/words for lines matching “tsch” and output
six lines of context after each line of output, type:
$ grep -A6 tsch /usr/dict/words RET
• To search /usr/dict/words for lines matching “tsch” and output
ten lines of context before and three lines of context after each line
of output, type:
$ grep -B10 -A3 tsch /usr/dict/words RET
METHOD #1
When you search for a regexp in less, all matches are highlighted by default.
This is useful for perusing a file containing lines you are searching for, such
as a mail archive or Web log file.
⇒ To highlight the subject lines of all mail messages in the file you are
perusing in less, type:
/^Subject:.*$ RET
NOTES: To highlight seareches in vim, type :set hls when in command mode.
METHOD #2
You can use sed to output lines that match a regexp (see Recipe 10.5 [Edit-
ing Streams of Text], page 255). sed’s search and replace functions make it
possible to search for a regexp and surround it with the ansi escape sequences
necessary to display text in colors. This method works on color terminals.
⇒ To search the file itinerary for the pattern “Paris,” and output the
contents of the file with that pattern in red, type (all on one line):
$ sed 's/Paris/ CTRL- V ESC[31m& CTRL- V
ESC[37m/g' < itinerary RET
The color for the highlighted text is specified by the number in the first
escape sequence. In the preceding example, that number is 31 (the second
number resets the text color to white, using number 37, for the text following
the match). The following table lists available numbers and the colors they
set.
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Purple
36 Cyan
37 White
NOTES: If you want to pipe the output to a pager for perusal, you should
use either less with the -R option or use more, because control characters
by default are not “escaped” in less (see Recipe 9.1.4 [Perusing Raw Text],
page 214).
Chapter 14: Searching Text 347
METHOD #1
Use grep with the -o option to show only the matches, and not the entire
line containing the match.
⇒ To output all of the ip addresses contained in the file access.log, type
(all on one line):
$ grep -o
'[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'
access.log RET
NOTES: This option is new for grep, beginning in gnu grep version 2.5.
METHOD #2
You can also use sed to output only the matched patterns you search for,
and not the lines they are contained in. To do this, run sed with the -n
option and the expression “s/.*\(PATTERN \).*/\1/p,” where PATTERN
is the pattern to search for. Finally, give the name of the file to search as an
argument.
⇒ To output the contents of all double quotations (including the quotation
marks themselves), contained in the file dialogue, type:
$ sed -n 's/.*\(".*"\).*/\1/p' dialogue RET
When you search multiple files, each match that grep outputs is preceded
by the name of the file it’s in; suppress this with the -h option.
Chapter 14: Searching Text 349
METHOD #1
Lynx
DEB: lynx
RPM: lynx
WWW: http://lynx.browser.org/
You can grep the contents of a Web page or other url by giving the url to
lynx with the -dump and -nolist options, and piping the output to grep.
⇒ To search the contents of the url http://example.com/bingo for lines
containing the text “bango” or “bongo,” type (all on one line):
$ lynx -dump -nolist http://example.com/bingo |
grep b[ao]ngo RET
METHOD #2
Wget
DEB: wget
RPM: wget
WWW: http://www.gnu.org/software/wget/wget.html
To grep the actual html source of the Web page, use wget and give “-” as
an argument to the -O option, piping the output to grep.
⇒ To search the html sources of the url http://example.com/bingo for
five sequential digits, type (all on one line):
$ wget -O- http://example.com/bingo | grep
'[0-9]\{5\}' RET
METHOD #1
A quick way to search and replace some text in a file is to use the following
one-line perl command:
perl -pi -e "s/oldstring/newstring/g;" filespec RET
In this command, oldstring is the string to search for, newstring is the string
to replace it with, and filespec is the name of the file or files to work on. You
can use this for more than one file.
⇒ To replace the string “helpless” with the string “helpful” in all files in
the current directory that end with a three-character file extension, type:
$ perl -pi -e "s/helpless/helpful/g;" *.??? RET
METHOD #2
You can use sed to search for and replace text, as described in Recipe 10.5
[Editing Streams of Text], page 255.
⇒ To output the contents of the file marketing, replacing the text
“television,” capitalized or not, with “Internet,” type:
$ sed 's/[Tt]elevision/Internet/g' marketing RET
⇒ To search for the text “moon” in the current buffer from point in reverse
to the beginning of the buffer, type:
CTRL- R moon
The keyboard accelerator for this command is ALT- CTRL- S. To repeat
the last regexp search you made, type ALT- CTRL- S CTRL- S; then, as
long as you have CTRL held down, you can keep typing s to advance to the
next match, just as you would with an incremental search.
expression to replace it with. Regexps are matched from point to the end of
the buffer; to search and replace all occurrences in a buffer, run this function
when point is at the beginning of the buffer.
⇒ To replace the text “day” with the text “night” in the current buffer,
type:
In the preceding example, the regexp “day” was found (and replaced by
the regexp “night”) seven times from point to the end of the buffer.
This function is especially useful for replacing control characters with text,
or for replacing text with control characters, which you can specify with
CTRL- Q, the quoted-insert function (see Recipe 10.1.4 [Inserting Special
Characters in Emacs], page 239).
⇒ To replace all the “Control-M” characters in the current buffer with reg-
ular linefeeds, type:
through the text, type / followed by a regexp to search for; to search backward
through the text, use ?.
When you do a search, the word or other regexp you search for appears
highlighted throughout the text. Typing a / or ? with no search string will
search either forward or backward for the previous string or regexp.
⇒ Here are some ways to use this.
• To search forward through the text you are perusing for the word
“cat,” type:
/cat RET
• To search forward for the next instance of “cat,” type:
/ RET
• To search backward for the previous instance of “cat,” type:
? RET
• To search backward through the text you are perusing for the regexp
“[ch]at,” type:
?[ch]at RET
NOTES: In Vi, whose search facility works identically to less, the matches
are not highlighted by default.
356 The Linux Cookbook, 2nd Edition
Chapter 15: Typesetting and Word Processing 357
file formats they generate, are anathema to the generalized, tools-based, and
plain-text philosophy of unix and Linux (see Recipe 1.7.7 [unix and the Tools
Philosophy], page 22). “Word processing” itself may be an obsolete idea of the
1980s personal computing environment, and it may no longer be a necessity
in the age of the Internet—a medium in which plain text data is fluid and
natural, being a native format and accessible on all machines.
If you do need to design a special layout for hardcopy printing, you can
typeset the text. One could write a book on the subject of Linux typesetting;
unfortunately, no such book has yet been written. However, this chapter
contains recipes to get you started producing typeset output. These recipes
were selected as being the easiest to prepare or most effective for their purpose.
For a list of other popular tools avilable for Linux, including traditional
word processors, see Recipe 15.7 [Using Other Word Processors and Type-
setting Systems], page 391, and for more information on this subject, I
recommend Christopher B. Browne’s overview, “Linux Word Processing”
[http://www.cbbrowne.com/info/wp.html].
documents, and the third suggests the typesetting system(s) to use. These
systems are described in the remaining sections of this chapter.
as unformatted text, but the text of the printed output is formatted in basic
ways, such as being set in a font. You can also use PostScript previewers such
as gv or ghostview to view it on the screen. Additionally, you can convert
the PostScript to pdf or other image formats, like a jpeg image file. In fact,
once you make a PostScript file from text input, you can use any of the tools
to format this new PostScript file, including rearranging and resizing its pages
(see Chapter 20 [PostScript], page 451).
There are several methods for converting text to PostScript output, but
the best is to use enscript. This is a quick, effective way to make presentable
output from plain text. It converts the text file that is specified as an argument
into PostScript, making any number of formatting changes in between. It’s
great for quickly making nice output from a plain text file—you can use it to
do things such as output text in a font of your choosing, or paginate text with
graphical headers at the top of each page.
By default, enscript paginates its input, outputs it in a 10-point Courier
font, and puts a simple header at the top of each page containing the file
name, date and time, and page number in bold. Use the -B option to omit
this header.
If you have a PostScript printer connected to your system, enscript can
be set up to spool its output right to the printer. You can check whether
your system is set up this way by looking at the enscript configuration file,
/etc/enscript.cfg. The line
DefaultOutputMethod: printer
specifies that output is spooled directly to the printer. Changing “printer”
to “stdout” sends the output to the standard output instead.
Even if your default printer does not natively understand PostScript, it may
be able to take enscript output, anyway. Most Linux installations these days
have print filters set up so that PostScript spooled for printing is automatically
converted to a format the printer understands. If your system doesn’t have
this setup for some reason, convert the PostScript to a format recognized by
your printer with the gs tool, and then print that—see Recipe 20.3 [Converting
PostScript], page 459.
⇒ To convert the text file saved-mail to PostScript, with default format-
ting, and spool the output right to the printer, type:
$ enscript saved-mail RET
To select a specific printer to send to, follow the -d option with its name.
Chapter 15: Typesetting and Word Processing 361
⇒ To convert the text file memo to PostScript, and send it to the printer
named salesroom, type:
$ enscript -dsalesroom memo RET
To write the output to a file instead of spooling it, give the name of the file
you want to output as an argument to the -p option. This is useful when you
don’t have a PostScript printer and you need to convert the output first, or
for when you just want to make a PostScript image file from some text, or for
previewing the output before you print it. In the latter case, you can view it
on the display screen with a PostScript viewer application such as ghostview
(see Recipe 17.4.2 [Previewing a PostScript File], page 414).
⇒ To write the text file saved-mail to a PostScript file, saved-mail.ps,
and then preview it in X, type:
$ enscript -p report.ps saved-mail RET
$ ghostview saved-mail.ps RET
To send it to the standard output, specify “-” as the file; this is good for
passing the PostScript along on a pipeline to some other commands, without
writing it to a file at all.
⇒ To preview the text file saved-mail as a PostScript file in the gv viewer,
type:
$ enscript -p - saved-mail | gv - RET
The following recipes show how to use enscript to output text with dif-
ferent effects and properties. You can combine these options, and some of the
recipes will demonstrate that.
The -B option was used in the preceding examples to omit the output of
a header on each page. When headers are used, they’re normally output in
10-point Courier Bold; to specify a different font for the text in the header,
give its name as an argument to the -F option.
⇒ Here are two ways to use this.
• To print the contents of the text file saved-mail to a PostScript
printer, with text set in 10-point Times Roman and header text set
in 18-point Times Bold, type (all on one line):
$ enscript -f "Times-Roman10" -F "Times-Bold18" saved-mail RET
• To make a PostScript file called saved-mail.ps containing the con-
tents of the text file saved-mail, with text and headers both set in
16-point Palatino Roman, type (all on one line):
$ enscript -f "Palatino-Roman16" -F "Palatino-Roman16"
-p saved-mail.ps saved-mail RET
NOTES: A list of available Adobe Type 1 fonts, and the names used to specify
them, can be found at /usr/share/enscript/afm/font.map.
If you want to output a visual image of a text file, showing the way the
text looks as a whole but set at a font too small to read, use a small font size,
such as from 1 to 5.
By default, enscript wraps long lines over to the next, which does not
always look nice. Give the -c option to truncate long lines, or output the
Chapter 15: Typesetting and Word Processing 363
text in vertical slices (see Recipe 15.2.8 [Outputting Text in Vertical Slices],
page 369).
⇒ To write the file program.output to the default printer, with long lines
truncated, type:
$ enscript -c program.output RET
You can even print several pages on one page. To specify the number of
logical pages to print on every output page, give the number as an argument
to the -U option.
⇒ To print the file tipsheet to the default printer, with text set in 24-point
Times Roman and writing four logical pages to each printed page, type:
$ enscript -U4 -f "Times-Roman24" tipsheet RET
The text in this example was preceded by a few space characters, to set it
off from the border.
Because 72-point type is very large, you may want to use the --word-
wrap option with longer lines of text to wrap lines at word boundaries. You
might need this option because at these larger font sizes, you run the risk
of making lines that are longer than could fit on the page. You can also
use the -r option to print the text in landscape orientation, as described in
Recipe 15.2.7 [Outputting Text in Landscape Orientation], page 369.
Chapter 15: Typesetting and Word Processing 365
⇒ To print a sign in 63-point Helvetica Bold across the long side of the page,
type:
There are a number of options used to specify the properties of the under-
lay, as described in the following table.
Without the -G option, enscript outputs text with a plain header in bold
text, printing the file name and the time it was last modified. The -B option,
as described earlier, omits all headers.
Chapter 15: Typesetting and Word Processing 369
You can customize the header text by quoting the text you want to use
as an argument to the -b option. Use the special symbol “$%” to specify the
current page number in the header text.
⇒ To print the contents of the text file saved-mail with a custom header
label containing the current page number, type (all on one line):
$ enscript -b "Page $% of the saved email archive" saved-mail RET
NOTES: There is currently no option to place headers on all but the first
page, so if you need to format text in this common way, first use enscript
to output to a file without headers, then use enscript to output another file
with headers, and use psselect to combine the first page of the former with
the remaining pages of the latter (see Recipe 20.1.2 [Extracting Pages from a
PostScript File], page 452).
You can create your own custom fancy headers, too—this is described in
the “CUSTOMIZATION” section of the enscript man page.
followed by a number to specify that slice; slices are numbered beginning with
1.
⇒ To print the second slice from the file annual-report.txt, type:
$ enscript --slice=2 annual-report.txt RET
If the number of columns is either one or two, you can also give the number
itself as an option. Use the -j option to place borders around each column.
⇒ To send the file payroll-data to the default printer with the default
enscript processing, setting the text in two columns per page, each with
a border drawn around it, type:
$ enscript -j -2 payroll-data RET
Chapter 15: Typesetting and Word Processing 371
NOTES: You can also place text in paginated columns with pr, and then
send it to enscript (see Recipe 13.3.4 [Placing Text in Paginated Columns],
page 314).
To print just the odd or even pages, use the special “odd” and “even”
arguments. This is good for printing double-sided pages: First print the odd-
numbered pages, and then feed the output pages back into the printer and
print the even-numbered pages.
⇒ Here are two ways to use this.
• To print the odd-numbered pages of the file saved-mail with the
default headers, type:
$ enscript -a odd saved-mail RET
• To print the even-numbered pages of the file saved-mail with the
default headers, type:
$ enscript -a even saved-mail RET
The most capable typesetting tool for use on Linux-based systems is the TEX
typesetting system and related software. It is the premier computer typeset-
ting system—its output surpasses or rivals all other systems to date. The
advanced line and paragraph breaking, hyphenation, kerning, and other font-
characteristic policies and algorithms it can perform, and the precision with
which it can do them, have yet to be matched in word processors.
The TEX system itself—not a word processor or single program, but a
large collection of files and data—is packaged in distributions; teTEX is the
TEX distribution designed for Linux.
TEX input documents are plain text files written in the TEX typesetting
language, which the TEX tools can process and write to output files for print-
ing or viewing. This approach has great benefits for the writer: The plain text
input files can be written with and exchanged between many different com-
puter systems regardless of operating system or editing software, and these
input files do not become obsolete or unusable with new versions of the TEX
software.
Donald E. Knuth, the world’s foremost authority on algorithms, wrote
TEX in 19842 as a way to typeset his books3 , because he wasn’t satisfied with
the quality of available systems. Since its first release, many extensions to
the TEX formatting language have been made—the most notable being Leslie
Lamport’s LaTEX, which is a collection of sophisticated macros written in the
TEX formatting language, designed to facilitate the typesetting of structured
2
This is the year that Knuth’s definitive book on the subject, The TEXbook, was pub-
lished, but the system was technically operational before this time—version 1.0 was
released on December 3, 1983, the initial design for the system occurred in 1977, and
the first books typeset with early TEX were published by 1979.
3
See http://www-cs-faculty.stanford.edu/~knuth/taocp.html.
Chapter 15: Typesetting and Word Processing 373
documents. (LaTEX probably gets more day-to-day use than the plain TEX
format, but in my experience, each is useful for different situations.)
“TEX” isn’t pronounced like the name of a cowboy, nor “LaTEX” like a kind
of paint: the letters “T,” “E,” and “X” represent the Greek characters tau,
epsilon, and chi (from the Greek techne, meaning “art and science”). So the
last sound in “TEX” is like the last sound in “Bach,” and “LaTEX,” depending
on local dialect, is pronounced either “lay-teck” or “lah-teck.” Those who
become highly adept at using the system Knuth calls TEXnicians.
The collective family of TEX and related programs (including Metafont;
see Recipe 16.5 [Using Other Font Tools], page 403) are sometimes called
“TEX and friends,” and they are always kept in a directory named texmf. For
example, the supplementary files included with the bare TEX system are kept
in the /usr/lib/texmf directory tree.
The following recipes describe how to begin writing input for TEX and how
to process these files for viewing and printing. While not everyone wants or
even needs to write documents with TEX and LaTEX, these formats are widely
used—especially on Linux systems—so every Linux user has the potential to
encounter one of these files, and ought to know how to process them.
There are separate commands for processing TEX and LaTEX files, and they’re
not interchangeable, so when you want to process a TEX or LaTEX input file,
you should first determine its format.
By convention, TEX files always have a .tex file name extension. LaTEX in-
put files sometimes have a .latex or .ltx file name extension instead, but not
always—one way to tell if a .tex file is actually in the LaTEX format is to use
grep to search the file for the text “\document,” which every LaTEX (and not
TEX) document will have. So if the search outputs any lines that match, you
have a LaTEX file. (The regular expression to use with grep is “\\document,”
because backslash characters must be specified with two backslashes.)
⇒ To determine whether the file smith.tex is a TEX or LaTEX file, type:
Once you have produced a dvi output file with this method, you can do
any of the following with it:
• Preview it on the screen with xdvi; see Recipe 17.4.1 [Previewing a dvi
File], page 413.
• Print it with dvips or lpr; see Recipe 25.2.5 [Printing a dvi File],
page 515.
• Convert it to PostScript with dvips; see Recipe 25.3.2 [Preparing a dvi
File for Printing], page 520; then, you can also convert the PostScript
output to pdf or plain text.
⇒ To ensure that all of the cross references in lshort.tex have been gen-
erated properly, run the input file through latex once more:
$ latex lshort.tex RET
Hello, world
\end
Figure 15-1. A TEX “Hello, world.”
If you processed the input file shown in Figure 15-1 with tex, it would
output a dvi file that displayed the text “Hello, world” in the default TEX
font, on a default page size, and with default margins.
Figure 15-2 contains the same “Hello, world,” but for LaTEX.
\documentclass{article}
\begin{document}
Hello, world
\end{document}
Figure 15-2. A LaTEX “Hello, world.”
Even though the TEX example in Figure 15-1 is much simpler than the
L TEX example, LaTEX is generally easier to use “fresh out of the box” for
a
376 The Linux Cookbook, 2nd Edition
There are more complex template packages available on the net that you
might want to look at:
• The largest listing of LaTEX and TeX templates and style files (and other
related software and documentation) on the Internet is the searchable
TEX Catalogue Online
[http://www.ctan.org/tex-archive/help/Catalogue/hier.html].
6
The manuscript template requires that your system has the LaTEX style
file called manuscript.sty; most TEX distributions have this installed at
/usr/share/texmf/tex/latex/misc/manuscript.sty.
378 The Linux Cookbook, 2nd Edition
To view how the document will look when you print it, choose View DVI
from the File menu. This command starts the xdvi tool, which previews the
output on the screen. (For more on using xdvi, see Recipe 17.4.1 [Previewing
a DVI File], page 413).
To print the document, choose Print from the File menu. You can also
export it to LaTEX, PostScript, dvi, or plain text formats; to do this, choose
Export from the File menu and then select the format to export to.
NOTES: If you plan on editing the document again in LyX, be sure to save
the actual .lyx document file.
Chapter 15: Typesetting and Word Processing 381
7
See http://www.lyx.org/about/lgt-1.0/lgt.html.
382 The Linux Cookbook, 2nd Edition
There are several output formats groff can write to. To specify a format,
give it as an argument to the -T option. The following table lists the arguments
and describes the formats they specify.
ps PostScript
dvi dvi (“DeVice Independent”) format
X75 dvi preview in X at 75 dpi (no output file necessary)
384 The Linux Cookbook, 2nd Edition
⇒ To see which options should be used with groff on the file meintro.me,
type:
$ grog meintro.me RET
In this example, the uncompressed content of the file was sent to the stan-
dard output via zcat (see Recipe 10.6 [Concatenating Text], page 256). You
can use xdvi to preview the resultant dvi output, or dvips to print it.
The command options used for this file were determined by grog (as de-
scribed in the previous recipe).
NOTES: Two additional groff documentation files included in the same di-
rectory are a complete reference manual, meref.me.gz, and a guide to making
box-and-arrow diagrams with the pic extension, pic.ms.gz.
More recommended resources for learning groff can be found in See Ap-
pendix D [References for Further Interest], page 731.
Figure 15-3. The zones file.
To make a table from such a groff input file, use tbl and give the name
of the file as an argument. This command outputs the raw input text that
groff uses to typeset the table; to view it or save it to a file, pipe the output
to groff with the right argument to the -T option for the output format you
want, as described in Recipe 15.5.1 [Processing a groff File], page 383.
⇒ Here are two ways to use this.
• To preview the typeset table made from the file zones in a new X
window at 100 dpi, type:
$ tbl zones | groff -TX100 RET
• To output the typeset table made from the file zones in a PostScript
file called zones.ps, type:
$ tbl zones | groff -Tps > zones.ps RET
Chapter 15: Typesetting and Word Processing 387
The previous example text will produce a table that looks like Figure 15-4.
if you want to print or convert them, you have to uncompress them first (see
Recipe 8.4 [Using File Compression], page 196).
⇒ Here are two ways to use this.
• To peruse the compressed text version of the Linuxdoc-Tools guide,
type:
$ zless /usr/share/doc/linuxdoc-tools/guide.txt.gz RET
• To print a copy of the PostScript version of the Linuxdoc-Tools guide
to the default printer, type:
$ zcat /usr/share/doc/linuxdoc-tools/guide.ps.gz | lpr RET
The following recipes use the Linuxdoc-Tools package and demonstrate its
use with documents written in the LinuxDoc dtd.
<sect>Introduction
<p>Hello, world.
</article>
Figure 15-5. A LinuxDoc “Hello, world.”
In this example, linuxdoc writes a LaTEX input file from the sgml source
file, and then the latex tool processes the LaTEX file to make dvi output,
which is processed with dvips to get the final output: a PostScript file called
myfile.ps with a paper size of “U.S. letter” (8.5 inx11 in).
To make a pdf file from the PostScript file, you need to take one more
step and use ps2pdf, part of the gs (Ghostscript) package; this converts the
PostScript to pdf.
⇒ To make a pdf file from the PostScript file myfile.ps, type:
$ ps2pdf myfile.ps myfile.pdf RET
NOTES: For more information on using fonts in X, see the XFree86 Font De-
uglification howto (see Recipe 2.8.6 [Reading System Documentation and
Help Files], page 50).
Chapter 16: Using Fonts 397
• To list all the X fonts on the system whose names contain the text
“rea,” type:
$ xlsfonts '*rea*' RET
• To list all the bold X fonts on the system, type:
$ xlsfonts '*bold*' RET
NOTES: This is not a way to display the characters in a font; for that, use
xfd, described next. Furthermore, to browse through available X fonts, you
want to use xfontsel, as in the previous recipe.
with TEX, and the precise fonts installed will differ from system to sys-
tem. TEX fonts are typically stored in the /usr/share/texmf/fonts/ and
/usr/local/share/texmf/fonts/ directory trees.
To get a list of TEX fonts on your system, use locate to list files with a
.tfm extension. These are TEX font metric files. Not all of the TEX fonts have
a .tfm file, and not all of the .tfm files are usable fonts, but you can get a
good idea of the TEX fonts installed on your system with this method.
⇒ To list the available .tfm fonts on your system, type:
$ locate .tfm RET
NOTES: You may want to redirect the output to a file, or peruse it with less
in a terminal window of its own, while you use this output to display samples
of the fonts as described in the next recipe.
Some font files contain more than one height (or size) of the font. If a font
contains more than one encoding for different heights, give the height to use
as an argument to the -H option. (If you try to specify such a font without
the height option, consolechars will output a list of available sizes.)
Common console font heights include 8 (for 8x8 fonts), 14 (for 8x14 fonts),
and 16 (for 8x16 fonts).
⇒ To set the console font to the 8x8 size sc font, type:
$ consolechars -H 8 -f sc RET
The making of “fonts” (and even pictures) from the arrangement of ascii
characters is known as ascii art. The following recipes describe methods of
outputting text in these kinds of fonts.
The figlet filter outputs text in a given text font. Give the text to out-
put as an argument, quoting any text containing shell metacharacters (see
Recipe 3.1.3 [Quoting Reserved Characters], page 56).
⇒ To output the text “news alert” in the default figlet font, type:
$ figlet news alert RET
This command outputs the text in an ascii text font, as in Figure 16-2.
_ _
_ __ _____ _____ __ _| | ___ _ __| |_
| ’_ \ / _ \ \ /\ / / __| / _‘ | |/ _ \ ’__| __|
| | | | __/\ V V /\__ \ | (_| | | __/ | | |_
|_| |_|\___| \_/\_/ |___/ \__,_|_|\___|_| \__|
Figure 16-2. Output from figlet.
Fonts for figlet are kept in the /usr/lib/figlet directory; use the -
f option followed by the base name of the font file (without the path or
extension) to use that font.
To output the contents of a text file with a figlet font, use cat to output
the contents of a file and pipe the output to figlet.
⇒ To output the text of the file poster in the figlet bubble font, type:
$ cat poster | figlet -f bubble RET
The easiest way to print a long, vertical banner of text on a Linux system is
with the old unix banner tool.
Quote a text message as an argument, and banner sends a large, vertical
“banner” of the message to the standard output. The message itself is output
in a “font” composed of ascii text characters, similar to those used by figlet,
except that the message is output vertically for printing, and you can’t change
the font. To send the output of banner to the printer, pipe it to lpr.
⇒ Here are two ways to use this.
• To make a banner saying “Happy Birthday Susan,” type:
$ banner 'Happy Birthday Susan' RET
• To print a banner saying “Happy Birthday Susan” to the default
printer, type:
$ banner 'Happy Birthday Susan' | lpr RET
The default width of a banner is 132 text columns; you can specify a
different width by specifying the width to use as an argument to the -w option.
If you give the -w option without a number, banner outputs at 80 text columns.
⇒ Here are two ways to use this.
• To make a banner containing the text “Happy Birthday Susan” at
a width of 23 text columns, type:
$ banner -w 23 'Happy Birthday Susan' RET
Chapter 16: Using Fonts 403
The following table describes some of the other font tools available for Linux.
Console Font Editor The Linux Console Font Editor (cse), an older console
font tool for editing font characters on-screen.
DEB: cfe
RPM: cfe
WWW: http://lrn.ru/~osgene/
Debian Font A tool for configuring fonts on a Debian system.
Manager DEB: defoma
defoma-doc
psfontmgr
Fonter A console font editor.
DEB: fonter
WWW: ftp://metalab.unc.edu/pub/Linux/apps/misc/
FontForge A font editor that recognizes many formats, including
PostScript, TrueType, and OpenType.
DEB: fontforge
RPM: fontforge
WWW: http://fontforge.sourceforge.net/
Font Viewer A tool for viewing Adobe Type 1 and TrueType fonts.
DEB: gfontview
RPM: gfontview
WWW: http://gfontview.sourceforge.net/
404 The Linux Cookbook, 2nd Edition
IV. IMAGES
406 The Linux Cookbook, 2nd Edition
Chapter 17: Viewing Images 407
This command displays the image file in a new window, as in Figure 17-1.
Finally, right-click on the image window for a pop-up menu containing a few
of the most frequently-used commands; to choose one of these commands, drag
the mouse pointer over the command and release the right button. Commands
in the pop-up menu include Quit, which exits display, and Image Info, which
displays information about the image file itself, including the number of colors,
image depth, and resolution.
The following table describes some of the keyboard commands that can be
used when displaying an image in display.
The following recipes describe some special uses of display. It can also
be used to view images on the Web—see Recipe 33.4 [Viewing an Image from
the Web], page 651.
them in quotes. display makes thumbnails of the specified images, and dis-
plays them in a new window, which it calls a visual image directory.
⇒ Here are two ways to use this.
• To browse through the image files that have a .gif extension and
are in the /usr/doc/imagemagick/examples directory, type:
$ display 'vid:/usr/doc/imagemagick/examples/*.gif' RET
• To browse through all image files in the current directory, type:
$ display 'vid:*' RET
In the preceding example, only those files with image formats supported
by display are read and displayed.
NOTES: If the title bar indicates that there is more than one page to the
visual image directory, press SPACEBAR to advance to the next one (pressing
SPACEBAR on the last page wraps back to the beginning).
To open an image at its normal size, right-click the image and choose
Load; the thumbnail will be replaced by its full-size image. To return to the
thumbnail directory, press SPACEBAR.
Use zgv to view images in a virtual console (not in X). You can use zgv to
browse through the filesystem and select images to view, or you can give the
names of specific image files to view as arguments. It recognizes many image
formats, including gif, jpeg, png, pbm/pnm/ppm, tga, and pcx; one of its
nicest features is that it fills the entire screen with an image.
Chapter 17: Viewing Images 411
When you run zgv with no options, it displays image icons of any images
in the current directory, showing any subdirectories as folder icons. You can
also give the name of a directory as an argument in order to browse the images
in that directory.
⇒ Here are two ways to use this.
• To browse the images in the current directory, type:
$ zgv RET
• To browse the images in the /usr/share/gimp/scripts directory,
type:
$ zgv /usr/share/gimp/scripts RET
Use the arrow keys to navigate through the file display; the red border
around an image or directory icon indicates which image or subdirectory is
selected. Type RET to view the selected image or to change to the selected
directory.
You can manipulate the images you view in a number of ways—zoom the
image magnification in and out, change the brightness and color, and even
make automatic “slide shows” of images. The following table describes some
of zgv’s command line options.
Browsers are good for perusing files and directories, and they are equally good
at displaying images. You can browse local images in a Web browser running
in X just as you would browse any files (see Recipe 5.10 [Browsing Files and
Directories], page 157). If you want to view an image file while you are in X,
and you have a Web browser running, it can be a quick and easy way to do
it.
You can view images in this way using either a graphical browser (such as
Mozilla), or in a terminal window with the text-based browser Lynx, in which
case the image is displayed in a new window with a “helper” application.1
Exiting the helper application will bring you back to Lynx.
To view an image file in Mozilla or another graphical Web browser, specify
the full path name of the image file in the Location field of the browser. To
view an image file in Lynx, just give the full or relative path name of the
image as an argument, or type g while in Lynx to get a prompt where you
can then type the full path name.
⇒ Here are some ways to use this.
• To start Mozilla with the file /usr/share/doc/texmf/pdftex/
base/pic.png, type:
mozilla /usr/share/doc/texmf/pdftex/base/pic.png RET
• To view the file /usr/share/doc/texmf/pdftex/base/pic.png in
Mozilla, type the following in its Location field:
/usr/share/doc/texmf/pdftex/base/pic.png RET
1
The display tool is usually the default application set up for viewing images.
Chapter 17: Viewing Images 413
NOTES: The file: url given to Mozilla only has one preceding slash (point-
ing to the root directory) and not two, as in any http:// url.
NOTES: If the file you want to preview is compressed and has either a .gz or
.bz2 file name extension, you can still preview it with see (see Recipe 8.4.3
[Seeing What’s in a Compressed File], page 199).
To magnify the view of the document, left-click any of the buttons labeled
with a percentage, such as 17%; they magnify the view by that percentage.
⇒ To magnify the view by 33%, left-click the button marked 33%.
414 The Linux Cookbook, 2nd Edition
The following table lists the most important keystoke commands to use
while previewing with xdvi.
Press SPACEBAR to scroll down the page (and then advance to the next
one, if there is one), O to open a new file, and Q to exit.
Chapter 17: Viewing Images 415
NOTES: The keys just described work for either ghostview or gv, but today
many people prefer to use the newer gv, which was based on ghostview, but
has a better interface and can preview pdf files, too.
Xpdf
DEB: xpdf-common
xpdf-reader
RPM: xpdf
WWW: http://www.foolabs.com/xpdf/
Use xpdf to preview a pdf file. Give the name of the pdf file to preview as
an argument.
⇒ To preview the pdf file flyer.pdf, type:
$ xpdf flyer.pdf RET
To exit xpdf, press Q; use the two magnifying-glass buttons to zoom the
view closer in (+) or further out (-), and click on the left and right arrow
buttons to move to the previous and next pages, if any. You can also select
text with the mouse by clicking the first mouse button and dragging over the
block of text to select; this becomes plain ascii text in the X selection, which
you may paste into another window (like a text editor, for instance, or in an
xterm shell where you are using cat to redirect standard input to a file).
NOTES: You can also use gv to preview pdf files (see preceding recipe).
METHOD #1
Xpcd
DEB: xpcd
xpcd-gimp
RPM: xpcd
WWW: http://bytesex.org/xpcd.html
416 The Linux Cookbook, 2nd Edition
The xpcd tool is an X client for viewing and browsing collections of Kodak
PhotoCD images. To browse the images on a Kodak PhotoCD, mount the
cd-rom (see Recipe 24.4.1 [Mounting a Data cd], page 506), and then give
the mount point as an argument to xpcd.
⇒ To browse the images on the PhotoCD disc mounted on /cdrom, type:
$ xpcd /cdrom RET
The preceding example will open two new windows—a small xpcd com-
mand bar window, and a larger window containing thumbnails of all PhotoCD
images on the disc.
To open a copy of an image in a new window, left-click its thumbnail image.
When you do, xpcd will open the image at the second-smallest PhotoCD
resolution, 256x384; to view it at another size, right-click the image and choose
the size to view. Once the new window is drawn, you can right-click on this
new image to save it as a jpeg, ppm, or tiff format image.
To view an individual .pcd file with xpcd, give the name of the file as an
argument.
⇒ To view the PhotoCD file hawaii-001.pcd, type:
$ xpcd hawaii-001.pcd RET
NOTES: While development has been halted on xpcd, it is still a useful viewer,
and comes packaged with pcdtoppm, a PhotoCD conversion tool.
See Recipe 19.3 [Extracting PhotoCD images], page 445 for another recipe
for extracting PhotoCD images.
METHOD #2
To browse a PhotoCD archive, use display to view the overview.pcd file
associated with that archive, which is kept in the top directory of the archive
(for how to use display, see Recipe 17.1 [Viewing an Image in X], page 407).
⇒ To browse the images on the PhotoCD disc mounted on /cdrom, type:
$ display /cdrom/overview.pcd RET
To view a particular image in a PhotoCD archive, give the file name asso-
ciated with that image as an argument to display.
⇒ To view the twelfth image on the PhotoCD disc mounted on /cdrom,
type:
$ display /cdrom/images/img0012.pcd RET
Chapter 17: Viewing Images 417
Use animate, part of the ImageMagick suite, to view animations and to view
or make slide shows.
To view an animated image file, give the name of the file as an argument.
⇒ To view the animated image earth.gif, type:
$ animate earth.gif RET
When animate is through displaying all of the given images, it loops back
to the beginning. To set the amount of time to pause before starting over,
give a second argument to -delay, specified as “xnumber,” where number is
the number of seconds to pause before looping again.
⇒ To display a slide show of all the .jpeg files in the current directory,
displaying each image for the default 6/100ths of a second, and pausing
for one second before repeating, type:
$ animate -delay x1 *.jpeg RET
⇒ To display a full-screen backdrop slide show of all the files in the our-
hawaii-vacation directory, displaying each image for thirty seconds, and
pausing for one minute before repeating all over again, type:
$ animate -backdrop -delay 30000x60 our-hawaii-vacation/* RET
Aview Displays graphics as “ascii art.” This tool can read any
image format supported by the pbmplus utility suite, and
has fluid zoom in/out, along with all the rendering options
you’d expect from a world-class viewer.
DEB: aview
RPM: aview
WWW: http://aa-project.sourceforge.net/aview/
Aatv Displays television tuner output in any text terminal as
ascii characters.
DEB: aatv
WWW: http://n00n.free.fr/aatv/
ChBg Changes the X background image. Allows for slide shows
and other effects.
DEB: chbg
RPM: chbg
WWW: http://chbg.sourceforge.net/
Fbi Displays images on Linux framebuffer consoles.
DEB: fbi
RPM: fbi
WWW: http://bytesex.org/fbi/
Chapter 17: Viewing Images 419
I’ll use the image phoenix.jpeg, shown in Figure 18-1, in the examples
that follow to give you an understanding of how to use mogrify.
NOTES: You can also perform many of the image transformations described
in the following sections interactively with the gimp (see Recipe 18.3 [Editing
Images with the Gimp], page 434); another very useful package for both trans-
forming images and converting between image formats is the netpbm suite of
utilities (see Recipe 19.2 [Scanning Images], page 443).
METHOD #1
To resize an image but maintain its aspect ratio, so that the ratio between
the width and height stays the same, use mogrify with the -geometry option,
and give the ideal width and height values, in pixels, as an argument.
⇒ To resize phoenix.jpeg to 480x320 pixels, type:
$ mogrify -geometry 480x320 phoenix.jpeg RET
424 The Linux Cookbook, 2nd Edition
METHOD #2
To resize an image to a particular image size without necessarily preserving
its aspect ratio, use mogrify with the -geometry option, and append the
geometry values you give as an argument with a trailing exclamation point
(!).
⇒ To resize phoenix.jpeg to exactly 640x480 pixels, regardless of aspect
ratio, type:
$ mogrify -geometry 640x480! phoenix.jpeg RET
METHOD #3
You can also scale an image by specifying the width or height by percentage
with mogrify. To decrease by a percentage, give the value followed by a
percent sign (%). To increase by a percentage, give the value plus 100 followed
by a percent sign. For example, to increase by 25 percent, give “125%.”
Chapter 18: Editing Images 425
Use the -map option with a second file name as an argument to read the
color map (the set of colors) from the second image and use them in the first
image.
⇒ To change the colors in the file rainbow.jpeg to those used in the file
prism.jpeg, type:
$ mogrify -map prism.jpeg rainbow.jpeg RET
Use the -monochrome option to make a color image black and white.
⇒ To make the color image rainbow.jpeg black and white, type:
$ mogrify -monochrome rainbow.jpeg RET
There are a few methods for reading and writing annotations in an image
file. This practice is useful for adding a copyright statement to an image
or for annotating an image file with a url. Not all image formats support
annotations; jpeg is the most popular.
You won’t see the annotation when you view an image; it is added to the
image header in the file. You can, however, read image annotations with tools
that display information about an image file, such as display or the gimp.
Another method for outputting the annotation text is described below.
428 The Linux Cookbook, 2nd Edition
METHOD #1
Use wrjpgcom to write a comment in a jpeg file. Quote the comment as an
argument to the -comment option, and give the name of the input file as an
argument. The default is to write a new jpeg file to the standard output.
⇒ To annotate an image in the file map.jpeg with the text “Map not drawn
to full scale” and write it to a file warnmap.jpeg, type (all on one
line):
$ wrjpgcom -comment "Map not drawn to full scale"
map.jpeg > warnmap.jpeg RET
Use a Bash for loop to make the same annotation in a group of files (see
the Bash Info documentation for more information on this built-in).
⇒ To annotate all of the .jpg files in the current directory with the comment
“Image courtesy Rick Blaine,” writing to a new file with the same base
name but a .jpeg extension, type:
The previous example could also have been written on a single input line,
omitting the for loop, as follows:
for i in *.jpg; { wrjpgcom -comment "Image courtesy Rick
Blaine" $i `basename $i jpg`jpeg; } RET
METHOD #2
Use mogrify with the -comment option to annotate image files with a com-
ment. Give the comment in quotes as an argument to the option.
⇒ To annotate the image file phoenix.jpeg, type (all on one line):
$ mogrify -comment "If you can read this,
you're too close!" phoenix.jpeg RET
Chapter 18: Editing Images 429
METHOD #3
To read annotations in jpeg files, use the rdjpgcom tool—it outputs any
comments in the jpeg file whose file name is given as an argument.
⇒ To read any comments made in the image file phoenix.jpeg, type:
NOTES: In this example, three jpegs were read and output to a png file; to
specify the format to use in the output, give the appropriate file extension in
the output file name.
the two images on top of the larger, starting in the top left corner; if both
images are the same size, only the second image is visible.
⇒ To combine two images, ashes.jpeg and phoenix.jpeg, into a new file
picture.jpeg, type:
$ composite ashes.jpeg phoenix.jpeg picture.jpeg RET
You can specify the percentage by which to blend the two images with the
-dissolve option. Give the percentage to “dissolve” the first image into the
second as an argument to the option.
⇒ To combine the image files ashes.jpeg and phoenix.jpeg so that the
new image contains 70 percent of the first image dissolved into the second,
type:
$ composite -dissolve 70 ashes.jpeg phoenix.jpeg picture.jpeg RET
This command combines the two images and writes a new image file,
picture.jpeg, whose contents contain 70 percent of the first image.
NOTES: Use -dissolve 50 to blend the two source files equally.
This command converts the jpeg image phoenix.jpeg to png format and
writes it to a new file, phoenix.png.
When converting a file to jpeg format, be sure to use the -interlace
NONE option to make sure the resultant jpeg image is non-interlaced—unless,
of course, you want an interlaced image. An interlaced image is drawn in
multiple passes, and is often used on the Web where a reader may view the
Chapter 18: Editing Images 433
low-resolution image consisting of early passes before the entire image is down-
loaded. A non-interlaced image is drawn in one single pass.
⇒ To convert the pnm file pike.pnm to non-interlaced jpeg, while sharpen-
ing the image by 50 percent and adding both a 2x2 border and a copyright
comment, type (all on one line):
$ convert -interlace NONE -sharpen 50 -border 2x2
-comment 'Copyright 2008 Toby Smith' pike.pnm pike.jpeg RET
This command writes its output to the file pike.jpeg. Notice that the
options -border and -comment were previously described for the mogrify
tool. Some ImageMagick tools share common options, which is useful if you
are making multiple changes to an image file at once; only one tool is needed
for the job.
You can convert to and from any of the image formats recognized by Im-
ageMagick, including animations. To make an animation, give as arguments
the names of the files for the individual frames, in the sequence you want them
to appear, and give the name of the new file as the final argument. Formats
that support animations include miff and gif.
Use the -delay option to specify the delay, in hundredths of a second,
between frames.
⇒ To make an animated miff file, driving.miff, out of all the files
drive1.jpg, drive2.jpg, drive3.jpg, drive4.jpg, and drive5.jpg,
with a delay of a fifth of a second between frames, type (all on one line):
$ convert -delay 20 drive1.jpg drive2.jpg drive3.jpg
drive4.jpg drive5.jpg driving.miff RET
NOTES: Some image formats are lossy, which means some image information
is lost when you convert to it. For example, the jpeg format is a lossy format
that is usually used for photographic images. If you convert a file from its
source pnm format to jpeg and then back to pnm, the resultant pnm will not
be identical to the original source pnm.
To convert image files interactively, open the image in the gimp, and then
choose Save as from the File menu, and select the file type to use; see the
following recipe for more information.
434 The Linux Cookbook, 2nd Edition
If you plan on doing even the slightest or most occasional image editing, such
as applying filters or effects to an image or touching up, resizing, or cropping
digital photographs, you will want to take some time to familiarize yourself
with the gimp (“gnu Image Manipulation Program”).
It is the flagship image editor for Linux-based systems, an all-encompassing
image manipulation program that you can use to paint, draw, create, and edit
images in complex ways. You can also use it to convert image files, retouch
and edit photographic images, and browse collections of images.
The gimp comes pre-installed with hundreds of tools, filters, fonts, and
other goodies. Here is a partial list of its essential features:
• Contains a full suite of painting tools, including Brush, Pencil,
Airbrush, and Clone.
• Supports custom brushes and patterns.
• Includes a full suite of image selection, transformation, and manipulation
tools, including a gradient editor, color blending, and special effects.
• Includes animation support.
• Permits the use of layers and channels.
• Allows for large images, with their size being limited only by available
disk space.
• Provides high-quality font anti-aliasing.
• Offers full alpha-channel support.
• Supports command scripting.
• Permits multiple undo and redo, limited only by available disk space.
• Allows multiple images to be open simultaneously.
• Supports all popular image file formats, including jpeg, png, xpm, tiff,
tga, mpeg, ps, pdf, pcx, and bmp.
• Allows the easy addition of more than 100 plug-ins for new file formats
and new effect filters.
Chapter 18: Editing Images 435
The gimp runs under X and is started by running gimp or choosing it from
your window manager’s menu. Give the names of any image files to open as
arguments.
⇒ To start the gimp in the background from a shell prompt, type:
$ gimp & RET
When started, any image files you give as arguments are opened in their
own windows. The main gimp panel will open in a window of its own, as in
Figure 18-10.
Dia Drawing tool for simple charts and diagrams. Exports files
to eps (see Chapter 20 [PostScript], page 451).
DEB: dia
dia-common
RPM: dia
WWW: http://www.gnome.org/projects/dia/
Effectv Processes tv input through various special effects.
DEB: effectv
Electric cad system for designing images of electric circuits,
schematics, and the like.
DEB: electric
RPM: electric
WWW: http://tinyurl.com/3yzbf
Figurine Vector graphics editor, intended to be easier to pick up than
the classic Xfig (listed below), yet remaining compatible
with Xfig’s file format.
DEB: figurine
RPM: figurine
WWW: http://figurine.sourceforge.net/
Findimagedupes Performs a “visual diff” on two image files; given a set of
files, it finds similar or duplicate images.
DEB: findimagedupes
WWW: http://www.kudla.org/raindog/perl/
Gnuplot Robust, non-interactive function-plotting tool. Generates
charts and graphs from a data file and a formula (see
Recipe 29.8 [Plotting Data], page 575).
DEB: gnuplot
RPM: gnuplot
WWW: http://www.gnuplot.info/
Innovation3d 3d modeling program.
DEB: innovation3d
innovation3d-plugins
WWW: http://innovation3d.sourceforge.net/
438 The Linux Cookbook, 2nd Edition
Use import, part of the ImageMagick suite, to take a screen shot in X. import
can capture the entire screen, a single window, or an arbitrary rectangular
area, taking as an argument the name of the file to save to. As with other
ImageMagick tools, the image format of the output file depends on the file
extension you specify: .eps for eps, .tiff for tiff, .jpeg for jpeg, and so
on. (For a complete list, see Recipe 18.2 [Converting Image Files], page 432).
After you give the command, the mouse pointer changes to a cross-hairs
pointer. You then use the mouse to specify which window to take the shot of,
as follows:
• Left-click on a window to capture its contents.
• Left-click on the root window to capture the entire screen.
• Left-click and drag the mouse across an area of the screen to form a
rectangular selection outline; release the mouse button to capture the
selected area.
When you specify a window, import captures only the window’s contents;
use the -frame option to include the window manager frame in the image.
442 The Linux Cookbook, 2nd Edition
This command will run import five seconds after you type RET, which
should give you time to get the mouse pointer where you want it.
NOTES: The system bell rings once when the screen capture starts, and twice
when the captures finishes.
NOTES: You must have superuser privileges to access these files (see Appen-
dix A [Administrative Issues], page 699).
Take the screen shot from a virtual console other than the one you want to
take a shot of; if you try to take it from the same console you want to capture,
the command line you give will be included in the shot! (Kind of like having
your thumb in front of the lens while taking a photograph.)
Chapter 19: Importing Images 443
sane, “Scanner Access Now Easy,” is the de facto Linux scanner interface;
use it to scan an image with a scanner and save it to a file.
sane works with a wide array of scanning hardware, but
make sure the scanning hardware you want to use is compatible
by checking for it in the Linux Hardware Compatibility howto
[http://en.tldp.org/HOWTO/Hardware-HOWTO/] and in sane’s own list of
supported scanners [http://www.sane-project.org/sane-backends.html].
Once you have sane running, you can scan images with sane-aware ap-
plications like the gimp (see Recipe 18.3 [Using the gimp], page 434).
The following recipes describe the use of the command line scanimage tool
that comes with the sane package.
NOTES: As the acronym implies, getting a scanner to work on a Linux sys-
tem hasn’t always been smooth going. The sane interface is completely open,
and its developers are making sure that it is generalized enough to be imple-
mentable on any hardware or operating system.
NOTES: For all scanimage commands, specify the scanner device you want
to use by including the -d option with the device name.
Use scanimage to scan an image. Most scanners let you specify the x and y
values, in pixels, for the image size to scan, starting from the top-left corner
of the scanner bed. Give these coordinates as arguments to the -x and -y
options. Also, use the --resolution option to specify the scan resolution,
with the argument given in dpi (“dots per inch”). Common resolution values
include 72, 120, 204, 300, and 600 dpi; 72 dpi is the most popular resolution
for use on the Web or for viewing on screen, and 204 dpi is often used for
images that you want to send on a fax machine.
Scanned output is sent to standard output, so to scan an image to a file,
redirect the standard output.
scanimage outputs images in the pnm (“portable anymap”) formats, so
make sure that you have the netpbm package (installed on most Linux systems
Chapter 19: Importing Images 445
Use the code–mode option to specify the format of the output, followed
by one of the following arguments: “color” for color ppm, “gray” for pgm
grayscale, or “lineart” for black and white pbm. Each scanner has a default
mode; for most color scanners, the default mode will be “color.”
⇒ Here are two ways to use this.
• To make a 72 dpi scan of a color image 200 pixels wide and 100 pixels
tall, using the umax scanner from previous examples, and writing to
a file called scan.ppm, type (all on one line):
$ scanimage -d umax:/dev/sgb --resolution 72 -x 200 -y 100 >
scan.ppm RET
• To make a 300 dpi scan of a black and white image 180 pixels wide
and 225 pixels tall, using the umax scanner from previous examples,
and writing to a file called scan.pbm, type (all on one line):
$ scanimage -d umax:/dev/sgb --resolution 300 --mode lineart
-x 180 -y 225 > scan.pbm RET
NOTES: The command lines in this recipe are split across two lines because
they’re too long to fit on one, but type these commands on one long line.
Once the image has been scanned and written to a file, you can edit it just
as you would any image.
There are two methods to extract an image from a Kodak PhotoCD format
446 The Linux Cookbook, 2nd Edition
file1 (also known as pcd). If you are browsing the PhotoCD files with the
xpcd tool, then choose an image, extract a copy at the desired resolution, and
save it to a file as described in Recipe 17.5 [Browsing PhotoCD Archives],
page 415.
You can also use pcdtoppm on a pcd file directly to extract an image at
a given resolution and save it to a file in ppm format.2 Use the -r option to
specify the resolution to extract, given as a numeric argument from 1 (lowest
resolution) to 5 (highest); if this option is omitted, a value of 3 is assumed.
Also give as arguments the name of the pcd file to read from and the name
of the ppm file to write to.
⇒ To extract the highest resolution image from the file sharp.pcd and save
it to a pnm file named sharp.ppm, type:
$ pcdtoppm -r5 sharp.pcd sharp.ppm RET
1
This is a proprietary scanned-image format from Kodak, and it is currently a standard
for scanning film images to digital format.
2
On some systems, the command is hpcdtoppm, not pcdtoppm.
Chapter 19: Importing Images 447
METHOD #1
Enscript
DEB: enscript
RPM: enscript
WWW: http://www.iki.fi/~mtr/genscript/
ImageMagick
DEB: imagemagick
RPM: ImageMagick
WWW: http://www.imagemagick.org/
One way to make an image from some text is to convert the text to PostScript
(see Recipe 15.2 [Outputting Text to PostScript], page 359), and then use
convert to convert the PostScript to the image format of your choosing,
where you can crop and edit it as desired.
448 The Linux Cookbook, 2nd Edition
You can use echo to send the text to enscript, and pipe the output right
to convert. Use “0x0” as an argument to the -crop option to automatically
trim this image around the text.
⇒ To make a png image of the text “Amateur Radio History Page” in the
Times Roman Bold font at 42 points, type (all on one line):
$ echo "Amateur Radio History Page" | enscript -o - -B -f
"Times-Bold42" | convert -crop 0x0 - arhp.png RET
This command makes a png image file, arhp.png, as in Figure 19-1.
METHOD #2
If the text is displayed on the screen in X, use import to capture it as an
image, as described in Recipe 19.1.1 [Taking a Screen Shot in X], page 441.
METHOD #3
To make a bitmap image from some text, use the pbmtext filter. It takes any
text sent to it as input, and it outputs an image file in pbm format.
Chapter 19: Importing Images 449
This is useful for making image files of large texts, for purposes such as
including that text as an illustration. To send a compressed file to pbmtext,
use zcat (otherwise, the < redirection operator works fine).
⇒ To make a jpeg image containing the contents of the compressed
file /usr/share/state/us-constitution.gz, writing to a file named
constitution.jpeg, type (all on one line):
$ zcat /usr/share/state/us-constitution.gz | pbmtext |
convert - constitution.jpeg RET
GOCR Command line ocr tool that outputs plain text from scanned
images.
DEB: gocr
RPM: gocr
WWW: http://jocr.sourceforge.net/
gPhoto Imports images from digital cameras.
DEB: gphoto
RPM: gphoto
WWW: http://www.gphoto.org/
Grunch Merges partial scans together to form larger images.
DEB: grunch
WWW: http://www.radagast.org/~dplatt/
Gsumi Imports black-and-white images from pressure-sensitive input
devices, such as drawing tablets.
DEB: gsumi
Pencam Imports images from digital cameras that use the stv0680b-
001 chip.
DEB: pencam
WWW: http://stv0680-usb.sourceforge.net/
Streamer Captures images from video4linux devices.
DEB: streamer
RPM: xawtv-streamer
WWW: http://bytesex.org/xawtv/
Chapter 20: PostScript 451
20. PostScript
The PostScript programming language, designed and implemented in the early
1980s by John Warnock of Adobe Systems, is used to describe the way a
“page” should look. Pages are usually a physical sheet of paper (PostScript
is commonly used for sending documents to printer hardware), but they can
be any kind of output display.1 PostScript files are text files containing the
PostScript language commands for drawing images to be printed on pages.
Like plain text files, PostScript files are commonly found on the Internet
(and are used by commercial printers) because, as with plain text, they can be
shared across platforms and hardware without difficulty. The same PostScript
file can be output on a high-end display or printed on a low-end printer, to
the best of that hardware’s capability. PostScript is a compact and elegant
format.
While it’s possible to write directly in the PostScript language (and some
people have become adept at programming PostScript), so many tools and
applications convert files to and from PostScript that you don’t have to write
it yourself. See Recipe 15.2 [Outputting Text to PostScript], page 359, for a
way to convert plain text into PostScript.
gnu Ghostscript is a free interpreter of the PostScript language.2 It
comes with gs, a tool that is used to convert files from PostScript or pdf
to other formats. It’s usually used for printing to a non-PostScript printer
(see Recipe 25.3.1 [Preparing a PostScript File for Printing], page 518).
The ghostview tool is used to preview PostScript files on the screen (see
Recipe 17.4.2 [Previewing a PostScript File], page 414).
eps, or Encapsulated PostScript, is a file format that describes the contents
of a box within a page. eps files can be embedded in the page of a PostScript
file, and they are therefore commonly used when inserting an illustration into
a document (for example, all of the illustrations printed in the Cookbook
are eps format files). You can view and print eps files just as you would
PostScript files.
This chapter includes recipes for formatting and manipulating PostScript
files. Recipes are separated according to whether they work on the individual,
logical pages in a PostScript file (the numbered pages in the file that are not
necessarily the physical pages of output), and those that work on the entire
file as a whole.
1
PostScript was originally designed for the Apple LaserWriter printer; news was an old
unix windowing system by Sun Microsystems that used PostScript to draw the display.
2
It is also an interpreter of Adobe’s Portable Document Format (pdf) language.
452 The Linux Cookbook, 2nd Edition
Many of the tools used in this chapter come as part of Angus Duggan’s
psutils (“PostScript Utilities”) package. These tools can be used for other
purposes than those described in this chapter; see their respective man pages
for more details.
By default, dvips will output to the printer; to save the PostScript output
to a file, specify the file name to be used for output as an argument to the -o
option.
⇒ To output as PostScript the pages 137 to 146 of the file abstract.dvi,
and write them to the file abstract.ps, type:
$ dvips -pp137-146 -o abstract.ps abstract.dvi RET
Use psselect to select pages from a PostScript file; when you give an input
file, it outputs a new PostScript file containing the specified pages. Output is
sent to the standard output or to a file specified as a second argument.
Chapter 20: PostScript 453
Give the pages to select as arguments to the -p option; you can list single
pages and ranges of pages separated by commas. Give ranges as two numbers
separated by a hyphen; thus, “4-6” specifies pages four through six, inclusive.
If you omit the first number in a pair, the first page is assumed, and if you
omit the last number, the last page is assumed. Pages are written to the new
file in the order they are specified.
⇒ Here are some ways to use this.
• To select page 47 from the PostScript file newsletter.ps and output
it to the file selection.ps, type:
$ psselect -p47 newsletter.ps selection.ps RET
• To select the first ten pages, page 104, pages 23 through 28, and
page 2 from the file newsletter.ps and write them to the file
selection.ps, type:
$ psselect -p1-10,104,23-28,2 newsletter.ps selection.ps RET
• To select page 47 from the PostScript file newsletter.ps and output
it to the file selection.ps, type:
$ psselect -p47 newsletter.ps selection.ps RET
(In the second example above, page 2 is selected twice—first in the selection
of pages 1-10, and then later on its own.)
You can specify reverse ranges, with the higher page listed first in the
range, to output pages running backwards from that page toward the lower
page. You can also specify pages by their position relative to the last page in
the document. Do this by prefixing a number with an underscore (_), which
indicates that the given page number is counting backwards toward the first
page.
⇒ Here are some ways to use this.
• To select pages 30 to 25 from the PostScript file newsletter.ps and
output them to the file selection.ps, type:
$ psselect -p30-25 newsletter.ps selection.ps RET
• To select the last page from the PostScript file newsletter.ps and
output it to the file end-notes.ps, type:
$ psselect -p_1 newsletter.ps end-notes.ps RET
• To select the second-to-last through the tenth-to-last pages from
the PostScript file newsletter.ps and output them to the file
selection.ps, type:
$ psselect -p_2-_10 newsletter.ps selection.ps RET
454 The Linux Cookbook, 2nd Edition
If the file newsletter.ps in the last example contained only 12 pages, the
example is equivalent to running psselect with -p12-10.
Use the -e option to select all even-numbered pages, and use the -o option
to select all odd-numbered pages.
⇒ Here are two ways to use this.
• To select all of the even pages in the file newsletter.ps and write
them to a new file, even.ps, type:
$ psselect -e newsletter.ps even.ps RET
• To select all of the odd pages in the file newsletter.ps and write
them to a new file, odd.ps, type:
$ psselect -o newsletter.ps odd.ps RET
Use an underscore (_) alone to insert a blank page, and use -r to output
pages in reverse order.
⇒ Here are two ways to use this.
• To select the last ten pages of file newsletter.ps, followed by a
blank page, followed by the first ten pages, and output them to a
new file, selection.ps, type:
$ psselect -p_1-_10,_,1-10 newsletter.ps selection.ps RET
• To select the pages 59, 79, and 99 in the file newsletter.ps, and
output them in reverse order (with the 99th page first) to a new file,
selection.ps, type:
$ psselect -p59,79,99 -r newsletter.ps selection.ps RET
The same result as the last example could have been gotten by omitting
the -r option and just listing the three pages in the reverse order, like so:
$ psselect -p99,79,59 newsletter.ps selection.ps RET
Use psnup to print multiple PostScript pages on a single sheet of paper; give
as an option the number of pages to be combined (or put “up”) on each sheet.
⇒ To make a new PostScript file, double.ps, putting two pages from the
file single.ps on each page, type:
$ psnup -2 single.ps double.ps RET
To specify the paper size, give the name of a standard paper size as an
argument to the -p option: a3, a4, a5, b5, letter, legal, tabloid, statement,
executive, folio, quarto, or 10x14. You can also specify any height and width
with the -h and -w options; units can be specified in centimeters (followed by
“cm”) or inches (followed by “in”). If no size is specified, psnup assumes a
paper size of a4.
Use the -l option when pages are in landscape orientation (rotated 90
degrees counterclockwise from portrait orientation), and -r when pages are in
seascape orientation (rotated 90 degrees clockwise from portrait orientation).
Pages are placed in “row-major” layout in the output file, where logical
pages are placed in rows across the page. Use the -c option to specify a
“column-major” layout, where logical pages are placed in columns down the
page. Scale the size of the pages by giving a percentage to multiply the page
size by as an argument to the -s option; for example, -s .5 scales pages to
50 percent of their original size.
To draw a border around each page, specify the border’s width in points as
an argument to the -d option (if no width is specified, a value of 1 is assumed).
psbook reads the contents of the first, rearranges the pages, and then writes
the PostScript output to the second file.
⇒ To rearrange the pages of file newsletter.ps into a signature and write
it to the file newsletter.bound.ps, type:
$ psbook newsletter.ps newsletter.bound.ps RET
By default, psbook uses one signature for the entire file. If the file doesn’t
contain a multiple of four pages, it adds blank pages to the end.
To specify the size of the signature to use—in other words, the number
of pages that will appear on a single piece of paper—give the number as an
argument to the -s option. Signature size is always a multiple of four.
⇒ To rearrange the pages of file newsletter.ps into an eight-sided signature
and write it to newsletter.bound.ps, type:
$ psbook -s8 newsletter.ps newsletter.bound.ps RET
METHOD #1
Ghostscript
DEB: gs-common
gs
RPM: ghostscript
WWW: http://www.cs.wisc.edu/~ghost/
You can combine many PostScript files into one with gs. Use the -q,
-dNOPAUSE, and -dBATCH flags so that it works quietly and without pause,
and use “pswrite” as the device to write to, giving it as an argument to
the -sDEVICE= option.3 Specify the name of the output file with the special
-sOutputFile= option, and finally, specify the files to combine in the order
you want them combined.
⇒ To combine the PostScript files part1.ps, part2.ps, and part3.ps in
that order, writing to a new PostScript file program.ps, type (all on one
line):
$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pswrite
-sOutputFile=program.ps part1.ps part2.ps part3.ps RET
NOTES: If you plan on doing a lot of this, you can simplify things by putting
the following in a shell script (see Recipe 3.7 [Using Shell Scripts], page 84),
that you might call pscat:
#!/bin/sh
gs -q -dNOPAUSE -dBATCH -sDEVICE=pswrite -sOutputFile=$*
Then, call the script with the name of the file to write to as the first
argument, and following that, give the names of the files to combine in the
order you wish them to be combined.
3
To work on pdf files instead, use “pdfwrite” as the option.
458 The Linux Cookbook, 2nd Edition
METHOD #2
PSUtils
DEB: psutils
RPM: psutils
WWW: http://www.ctan.org/tex-archive/support/psutils/
Use psmerge to combine PostScript files into one. Give the names of the
files to be merged as arguments, and psmerge outputs them to the standard
output in the order given. You can also specify an output file name with the
-o option (don’t put any spaces between the file name and the option).
⇒ To merge the files slide1.ps, slide2.ps, and slide3.ps into a new
PostScript file, slideshow.ps, type:
$ psmerge -oslideshow.ps slide1.ps slide2.ps slide3.ps RET
To arrange the pages in a PostScript file to make booklets, rearrange the file
in a signature with psbook, use psnup to arrange the pages (two to a printed
page in landscape mode), and then use pstops to output first the odd and
then the even pages.
The trick to doing this properly is to first determine exactly what you need
to do, and then to calculate the proper measurements for use with pstops.
⇒ To make a booklet from the file newsletter.ps, do the following:
1. Rearrange the pages into a signature:
$ psbook newsletter.ps newsletter.signature.ps RET
Chapter 20: PostScript 459
Then, to print the booklet, send odd.ps to the printer, reload the printed
pages in the manual feed tray, and then send even.ps to the printer. This
prints the odd and even pages on opposite sides of the sheets.
⇒ To make a double-sized booklet on letter-sized paper in landscape orien-
tation from a file using letter-sized portrait orientation, type:
NOTES: If you will be doing a lot of this, you may want to have a look at the
ps2book utility, which is a script that aids in making booklets with psutils
[http://www.kis.uni-freiburg.de/~dobler/utils/ps2book.html].
To convert a PostScript file to pdf, use ps2pdf, which comes as part of the
Ghostscript package. Give as arguments the name of the PostScript file to
read from and the name of the pdf file to write to.
⇒ To write a pdf file sutra.pdf from the input file sutra.ps, type:
$ ps2pdf sutra.ps sutra.pdf RET
This command writes a new file in pdf format called sutra.pdf. The
original file, sutra.ps, is not altered.
NOTES: To make proper pdf conversions, make sure that you have
Ghostscript version 6.01 or higher installed; use the -v option with gs to
output the installed version.
To convert a PostScript file to plain text, use ps2ascii, which comes as part
of the Ghostscript package. Give as arguments the name of the PostScript file
to read from and the name of the text file to write to.
⇒ To make a text file, sutra.txt, from the input file sutra.ps, type:
$ ps2ascii sutra.ps sutra.txt RET
This command writes a text file called sutra.txt. The original file,
sutra.ps, is not altered.
V. SOUND 461
V. SOUND
462 The Linux Cookbook, 2nd Edition
Chapter 21: Playing and Recording Sound 463
A mixer program is used to adjust various audio settings such as volume and
recording levels, and it is also used for turning on or muting the microphone
or other input devices. You must use a mixer to adjust your audio settings
before you play or record sound.
Before recording, be sure to mute all channels but your input source—but
then don’t forget you’ve got them muted later, when you want to hear sound
from them!
alsa’s default mixer is called amixer, and the following recipes will show
its use. There are other mixers, and some of them are much easier to use
than amixer. My recommendation is to install aumix. See the end of this
chapter for other recommendations, including graphical mixers for use in X,
in Recipe 21.5 [Using Other Sound Tools], page 474.
464 The Linux Cookbook, 2nd Edition
The following table describes some of the important sound groups that
amixer lists.
To list the settings for only one group, use the ‘get’ option followed by
the name of the group you want to list. Group names are case sensitive—so
giving MIC specifies the microphone group, while Mic and mic are not valid
groups at all.
⇒ Here are two ways to use this.
• To output the microphone settings, type:
$ amixer get MIC RET
• To output the settings of the second pcm device, type:
$ amixer get PCM,1 RET
Chapter 21: Playing and Recording Sound 465
NOTES: You can have only one group selected for capture at a time, and when
you select a group as an input source for recording, you are simply turning
the microphone or other input on; recording does not occur until you use a
recording tool.
The play tool distributed with “SOund eXchange” (a sound file translation
tool) can recognize and play many audio formats, including ogg, wav, voc,
au, aiff, and snd format files, as well as audio cd-format files and various raw
binary formats. Just about the only common audio formats it can’t handle
are midi and mp3, which are discussed in the sections to follow. Give the
name of a file as an argument to play.
⇒ To play the file sousa.aiff, type:
$ play sousa.aiff RET
NOTES: Before you begin playing sound, make sure you’ve set the master
and pcm volume levels with the mixer (see Recipe 21.1 [Adjusting the Audio
Controls], page 463). The most common reason for no sound being produced
when you try to play sound is not having the volume turned up!
alsa comes with aplay, a tool for playing sound files that is similar to
play but does not recognize as many formats.
Use ogg123 to play Ogg Vorbis files, giving the name of the file as an argument.
⇒ To play the file track1.ogg, type:
$ ogg123 track1.ogg RET
Chapter 21: Playing and Recording Sound 467
By default, ogg123 sends to the standard sound device. You can specify a
sound device—useful on systems that have more than one device installed—
by using the -d option, followed by a special argument as described in the
following table.
Use the -k option to skip part of the beginning of the recording. Give the
number of seconds to skip as an argument to the option.
⇒ To play the file archive.ogg, beginning exactly one minute into the
recording and using the alsa driver, type:
$ ogg123 -k 60 -d alsa archive.ogg RET
To play files in random order, give the -z option. This is useful for when
you want to shuffle the tracks of an audio archive.
⇒ To play all of the .ogg audio files in the ~/audio/incoming directory,
shuffling the order of the tracks, type:
$ ogg123 -z ~/audio/incoming/*.ogg RET
METHOD #1
Playmidi
DEB: playmidi
RPM: playmidi
WWW: http://sourceforge.net/projects/playmidi/
If your sound card has a midi sequencer, use playmidi to play midi files; give
the name of the midi file to play as an argument.
⇒ To play the midi file copacabana.mid, type:
$ playmidi copacabana.mid RET
METHOD #2
Playmidi
DEB: playmidi
RPM: playmidi
WWW: http://sourceforge.net/projects/playmidi/
or
TiMidity++
DEB: timidity
RPM: timidity
WWW: http://www.onicos.com/staff/iz/timidity/
If you have a non-midi sound card, you can still play midi files by using
timidity, which converts the midi format into wav format, and then plays
it.
⇒ To play the midi file copacabana.mid on a non-midi sound card by con-
verting it to wav format, type:
$ timidity copa-cabana.mid RET
On some systems with non-midi sound cards, you can also use playmidi
with the -f option. This specifies that midi output is to be sent to the fm
synthesizer on the sound card, which in turn plays it using fm patches that
come with the playmidi distribution.
⇒ To play the midi file copacabana.mid on a non-midi sound card using
fm patches, type:
$ playmidi -f copacabana.mid RET
Chapter 21: Playing and Recording Sound 469
mod (“module”) files are tracked music files made by music software called
“trackers.” Popular trackers include SoundTracker and Impulse Tracker; use
mikmod to play audio files made with them. Supported formats include it,
mod, mtm, stm, s3m, ult, uni, and xm.
⇒ To play the mod file demo.it, type:
$ mikmod demo.it RET
When mikmod is playing, press F1 to show the help panel, or press Q to
exit.
There are many tools for playing mp3 files; some are listed at the end of this
chapter (see Recipe 21.5 [Using Other Sound Tools], page 474).
One such tool is mpg321; to use it to play an mp3 file, give the name of the
file as an argument.
⇒ To play the mp3 file lili-marleen.mp3, type:
$ mpg321 lili-marleen.mp3 RET
To “buffer” the audio, useful for when the system is running many processes
or otherwise has a lot of activity, give a buffer size, in kilobytes, as an argument
to the -b option. The default is 0 (no buffer); if you need this option, use a
size of at least 1024 kb (which is 1 mb), or about six seconds of mp3 audio.
NOTES: The mpg321 tool is a free software replacement of mpg123, another
command line mp3 player that is not free software.
The use of the mp3 format is waning now with the rise of Ogg Vorbis,
a format that has better audio quality, smaller files, and most importantly
470 The Linux Cookbook, 2nd Edition
of all is not patented, as the mp3 format is. Even outside the Linux world,
where mp3 still enjoys popularity, support for Ogg Vorbis is growing among
hardware vendors, radio stations, and audiophiles.
METHOD #1
Mpg321
DEB: mpg321
RPM: mpg321
WWW: http://mpg321.sourceforge.net/
To use mpg321 to play “streaming” mp3 audio from the Web, just give the
url of the mp3 stream as an argument.
⇒ Here are two ways to use this.
• To play http://example.net/broadcast/live.mp3 as an mp3
stream, type:
$ mpg321 http://example.net/broadcast/live.mp3 RET
• To play http://example.net/broadcast/live.mp3 as an mp3
stream with a 2 mb audio buffer, type:
$ mpg321 -b 2048 http://example.net/broadcast/live.mp3 RET
METHOD #2
Splay
DEB: splay
RPM: splay
WWW: http://splay.sourceforge.net/
Wget
DEB: wget
RPM: wget
WWW: http://www.gnu.org/software/wget/wget.html
To play streaming mpeg audio with an mp3 player that doesn’t take urls as
an option, first get the stream with wget using -O- to send it to the standard
output, and pipe this output to an mp3 player. Make sure the mp3 player is
Chapter 21: Playing and Recording Sound 471
set to read mpeg audio from standard input—with splay, this means giving
the special -M option to read from standard input and not a file.
⇒ To play the streaming mpeg audio that is broadcast at
http://vox.wclv.com/cgi-bin/swsend/tmp/source3, type (all on one
line):
$ wget -O- http://vox.wclv.com/cgi-bin/swsend/tmp/source3 | splay
-M RET
To save a copy of the audio to a file and listen to it while it’s being down-
loaded, just branch the pipeline with tee (see Recipe 3.2.5 [Redirecting Out-
put to More than One Place], page 69).
⇒ To to play the streaming mpeg audio that is broadcast at
http://voc.wclv.com/cgi-bin/swsend/tmp/source3, and save a copy
of the audio in a file named wclv.20051220.mp3, type (all on one line):
$ wget -O- http://voc.wclv.com/cgi-bin/swsend/tmp/source3 | tee
wclv.20051220.mp3 | splay -M RET
NOTES: Often when streaming mpeg audio is offered by a site, a link to a file
with an .m3u extension will be given as the address to use for listening. This
is actually not a link to the streaming audio itself, but to a file that contains
the url to which the actual streaming audio is being broadcast. To use this
link, first output the contents of this file to the standard output with wget
-O- followed by the url, and then select that url with the mouse so you can
paste it in the wget command that you pipe to splay, as demonstrated above
(see also Recipe 10.3 [Manipulating Selections of Text], page 253).
Use ogginfo to output information about Ogg Vorbis audio files. Give the
filespec of the files in question as arguments. For each file, it outputs the file
name, title, artist, album, track number, length in total seconds, and play
time in minutes and seconds.
⇒ To output information about the Ogg Vorbis audio file mystery.ogg,
type:
$ ogginfo mystery.ogg RET
Use mp3info to get information about an mp3 file, including title and artist.
Give the name of the file as an argument.
⇒ To output information on the mp3 file concerto.mp3, type:
$ mp3info concerto.mp3 RET
To record sound, first select an input device as a source for recording. Sound
cards may have mic and line in jacks, as well as connections to the cd drive,
all of which are sound inputs that can be used as recording sources. When
you select a device for capture, your recording will come from this source.
Chapter 21: Playing and Recording Sound 473
Recording occurs from the currently active input, if any, which must be set
with the mixer; unmute it and set its volume level before you begin recording.
(Be sure to turn the volume on your speakers all the way off, or you’ll get
feedback.)
To record audio to a file, use the rec tool. It can write many audio file
formats, either to a format you specify with the -t option, or by determining
the format to use based on the file name extension you give the output file (see
Appendix B [Conventional File Name Extensions], page 723). Type CTRL- C
to stop recording.
Give the name of the sound file to record as an argument; if a .wav file is
specified, it records a simple monaural, low-fidelity sound sample by default.
⇒ To record a simple wav sample from the microphone and save it to a file
called hello.wav, type:
$ rec hello.wav RET
This command begins an 8,000 Hz, monaural, 8-bit wav recording to the
file hello.wav, and it keeps recording until you interrupt it with CTRL- C.
While the default is to make a low-fidelity recording—8,000 Hz, monaural,
8-bit samples—you can specify that a high-fidelity recording be made. (Keep
in mind that high-fidelity recordings take up much more disk space.)
To make a stereo recording, use the -c option to specify the number of
channels, giving 2 as the argument. To make a 16-bit recording, give “w”
(“wide”) as the argument to the -s (“sample size”) option.
Set the recording sample rate by giving the samples per second to use as an
argument to the -r option. For cd-quality audio at 44,100 Hz, use -r 44100.
Finally, to record a file in a particular format, either give the name of the
format as an argument to the -f option, or use the traditional file name ex-
tension for that format in the output file name (see Appendix B [Conventional
File Name Extensions], page 723).
⇒ Here are two ways to use this.
• To make a high-fidelity recording from the microphone and save it
to a wav format file called goodbye.wav, type:
$ rec -s w -c 2 -r 44100 goodbye.wav RET
• To make a sound recording in the cd audio format and write the
output to a file called goodbye.cdr, type:
$ rec goodbye.cdr RET
NOTES: When you’re not recording sound, keep the inputs muted (see
Recipe 21.1.3 [Muting an Audio Device], page 465); this way, you can have a
474 The Linux Cookbook, 2nd Edition
Splay Command line mp3 player that can decode and play mpeg-
1 layer 1,2,3 and mpeg-2 layer 3 recorded audio. Based on
the older Maplay.
DEB: splay
RPM: splay
WWW: http://splay.sourceforge.net/
Xawtv-Tools Toolkit that includes tools for interactive recording of cd-
quality audio in a terminal, dumping the current mixer set-
tings to the standard output, and displaying the structure
of riff format files (both avi and wav).
DEB: xawtv-tools
RPM: xawtv
WWW: http://bytesex.org/misc.html
http://bytesex.org/xawtv/
XMMS Popular, comprehensive audio player for X, featuring dozens
of plug-ins, support for many sound formats (including Ogg
and mp3), and “skins” to change its look and feel; it can
use FreeAmp themes as well—see listing for zinf below.
Inspired by Winamp.
DEB: xmms
RPM: xmms
WWW: http://www.xmms.org/
Zinf Popular audio file player for X that can play Ogg and mp3
formats, and its graphical appearance can be changed with
“themes.” Formerly known as FreeAmp (the “Free Audio
Music Player”).
DEB: zinf
RPM: zinf
WWW: http://www.zinf.org/
476 The Linux Cookbook, 2nd Edition
Chapter 22: Audio Compact Discs 477
These recipes describe various ways to manipulate audio cds using the ele-
gant collection of command line tools found in cdtool toolkit. All of these
tools are actually symbolic links to a single program, cdtool; its functionality
depends on the name it is run with. Other cd audio tools, including X clients,
are listed in Recipe 22.4 [Using Other Audio Compact Disc Tools], page 484.
To begin with a particular track, give the number of the track as an argu-
ment.
1
Any drive that is capable of playing audio compact discs—a dvd drive, cd-rom drive,
or cdr or cdrw drive.
478 The Linux Cookbook, 2nd Edition
To end with a particular track, give the number of the track as a second
argument.
⇒ Here are two ways to use this.
• To play an audio cd, beginning with the first track and ending with
the fourth track, type:
$ cdplay 1 4 RET
• To play only the third track of an audio cd, type:
$ cdplay 3 3 RET
Use cdplay to start playback at the point where it was paused; to restart
the playback from the beginning, use cdplay with ‘x’ as an argument.
⇒ Here are two ways to use this.
• To restart a paused cd, type:
$ cdplay RET
• To restart a paused cd from the beginning, type:
$ cdplay x RET
Chapter 22: Audio Compact Discs 479
METHOD #1
Use cdinfo to display information about an audio cd, including its play status
and track times. With no options, it outputs the play status: “play” if the cd
is currently playing; “paused” if the cd is currently on pause; “no-status”
if the cd is not playing; and “nodisc” if no disc is in the drive.
⇒ For the current status of the audio cd in the cd drive, type:
$ cdinfo RET
In addition, cdinfo recognizes the following options:
METHOD #2
To show the lengths of all tracks on an audio cd in a directory-like format,
use cdir. This tool will also show titles and artist names, if known, but for
this to work, you must set up an audio cd database (see the cdtool man page
for details—Recipe 2.8.4 [Reading a Page from the System Manual], page 46).
480 The Linux Cookbook, 2nd Edition
$ cdir RET
unknown cd - 43:14 in 8 tracks
5:15.00 1
5:50.40 2
5:29.08 3
3:50.70 4
4:17.00 5
5:56.15 6
7:13.40 7
5:19.22 8
$
NOTES: This command will also eject a data cd, if the data cd is not currently
mounted (see Recipe 24.4 [Using Data cds], page 506).
Two tools used for sampling (sometimes called “ripping”) data from an audio
Chapter 22: Audio Compact Discs 481
cd are cdda2wav and cdparanoia. Both can sample single tracks or entire
disks. cdda2wav is the archetypal cd audio-sampling tool for Linux, and it
should be used when speed is more important than sound quality. cdparanoia
does various extra checks for the paranoid, and it should be used when an
absolutely perfect copy is necessary (at the expense of speed). cdda2wav is
perfectly capable of creating a digitally perfect audio sample under normal
conditions; cdparanoia is useful when your original cd has scratches (its
scratch-detection capability can attempt to “hold sync” across the scratch),
or when you are using a less-than-optimal-quality cd drive.
With cdda2wav, you specify the track number to be retrieved as an argu-
ment to the -t option; use the -x option to specify a cd-quality retrieval, and
give the name of the cd device with the -D option—unless you have multiple
cd drives installed, this is almost certainly going to be /dev/cdrom.
By default, files are written as wav format files; use the -O option followed
by “cdr” to write the files in cd audio format. cd audio format files are
useful for burning an audio cd containing the files as tracks (discussed in
the following section), and .wav files are useful for converting to Ogg format
(see Recipe 23.3.2 [Encoding an Ogg File], page 495). You can convert either
format to the other at a later time with sox—see Recipe 23.3 [Converting
Sound Files], page 493.
⇒ Here are two ways to use this.
• To copy track seven of an audio cd to a cd-quality wav file in the
current directory, type:
$ cdda2wav -t7 -d0 -x -D /dev/cdrom RET
• To copy all tracks on an audio cd to separate cd audio format files,
type:
$ cdda2wav -D /dev/cdrom -x -O cdr -d0 -B RET
For more reliable sampling, use cdparanoia. Give the range of audio tracks
to sample as an argument, from the first track to sample to the last; if you
give no arguments, it samples the entire disc. Use the -w option to specify
wav format output.
⇒ Here are some ways to use this.
• To sample the first through third tracks from a scratched audio cd
in the default cd drive using “paranoid” data verification, and write
the output as a raw audio-format file in the current directory, type:
$ cdparanoia 1-3 RET
482 The Linux Cookbook, 2nd Edition
• To sample only the third track of the audio cd using “paranoid” data
verification, and write the output to a wav format file in the current
directory, type:
$ cdparanoia -w 3-3 RET
• To sample the entire audio cd using “paranoid” data verification,
type:
$ cdparanoia -w -B RET
• To sample the entire audio cd using less-than-maximum “paranoid”
data verification, without checking for scratches, and saving each
song as a separate raw audio-format file in the current directory,
type:
$ cdparanoia -B -Y -X RET
NOTES: Sampling an entire audio cd can use a lot of disk space; most people
delete the .cdr or .wav files as soon as they make Oggs or burn an audio
cd-r from the data.
Use cdrecord to write (or “burn”) audio files to a blank cd-r disc. You will
need a cd-r drive2 and the audio files must be in cd-da cd audio format
(they usually have a .cdda or .cdr file name extension).
Specify the cd-r drive with the special “dev” argument, which is given in
this form:
dev=scsibus,target,lun
where scsibus is the number of the scsi bus (0 for the primary bus), target is
the scsi target id (usually a number from 1 to 6), and lun is its lun number
(almost always 0).
Use the speed argument to set the speed factor for writing data: give
“speed=2” to specify double speed or “speed=4” to specify quad speed.
Use the -dummy option to run with the drive laser turned off, so no actual
burning takes place; this is useful when you are first using a cd-r drive and
2
You can also use this tool with a cd-rw drive and write to a cd-rw disc.
Chapter 22: Audio Compact Discs 483
need to test your configuration to make sure you’ve got it right. Another
useful option is -v, which gives a more verbose message output.
Give the names of the audio files to burn, in the order that they should
appear on the disc, as arguments to the -audio option. The files are written
in cd-da cd audio format, and they should contain 16-bit stereo at 44,100
samples per second (the .cdr or x.cdda files meet this criterion).
⇒ Here are some ways to use this.
• To burn the file symphony.cdr to the disc in the cd-r drive whose
target id is 2 on the primary scsi bus, type:
$ cdrecord dev=0,2,0 -audio symphony.cdr RET
• To burn all the files in the current directory ending with a .cdr
extension at double speed to the cd-r drive whose target id is 2 on
the primary scsi bus, and give verbose output, type:
$ cdrecord dev=0,2,0 speed=2 -v -audio *.cdr RET
• To run a test burn of the file symphony.cdr to the disc in the cd-r
drive whose target id is 6 (lun 1) on the primary scsi bus, type:
$ cdrecord dev=0,6,1 -dummy -audio symphony.cdr RET
When you use wildcards for files, as in the second example above, the
shell expands the files in alphabetical order. To write a group of tracks in a
particular order without specifying all of their names as arguments, rename
them so that their names begin with numbers corresponding to the order
you want to write them in (see Recipe 5.5 [Moving Files and Directories],
page 144).
For example, if you have the three files morning-song.cdr, midday-
song.cdr, and evening-song.cdr, and you want to write them in that or-
der, rename the files to 01-morning-song.cdr, 02-midday-song.cdr, and
03-evening-song.cdr. Otherwise, if you specify them as *.cdr, the shell
will sort their names so that they will be written to cd-r in the order of
evening-song.cdr, midday-song.cdr, and morning-song.cdr—exactly the
opposite of what was intended!
To write a disc containing both data and audio tracks, first specify the file
for the data track (it should contain a filesystem image in either iso 9660 or
Rock Ridge format), and then follow it with the -audio option and the names
of the audio tracks to use. The resulting cd-r will be both mountable as a
data cd and playable on audio cd players (the first track on the disc, the data
track, will be skipped when playing the audio).
484 The Linux Cookbook, 2nd Edition
⇒ To burn the data track band-info, plus all the audio tracks in the current
directory that have a .cdda extension, to the cd-r drive whose target id
is 2 on the primary scsi bus, type:
$ cdrecord dev=0,2,0 band-info -audio *.cdda RET
NOTES: When writing an audio cd, you should have as few processes run-
ning as possible. If cdrecord has to pause even momentarily to let the system
shuffle other processes, the cd-r could be ruined! For this reason, it is ad-
visable to avoid switching between consoles—or between windows, if running
X—during the cd-r burning process.
The “Sound eXchange” tool, sox, is a sound sample translator. It reads sound
as files or standard input, and outputs the sound either to a file or standard
output, while translating in between. You can use sox to convert sound files
from one format to another or to process sounds with special effects. This
section describes some of the special effects you can apply to sound files with
sox.
Chapter 23: Editing Sound Files 489
When applying an effect, the original file is never altered. You must specify
an output file, or use a hyphen character (-) to indicate the standard output.
Specify the output format as an argument to the -t option. You can only
apply one effect with each sox command; thus, to add both echo and reverb
to a sound file, you would need to issue two sox commands.
The amount and levels applied for each effect will vary with every situation.
As such, consider the following recipes as guidelines only for using the options;
you will probably end up experimenting a bit to achieve your intended effect
for any particular sound file.
Almost all of the sound effects are applied by specifying the input and
output file arguments, followed by the name of the effect to use and any options
the effect takes (with notable exceptions, like the -v option for changing the
amplitude of a file).
NOTES: For more information on the sound effects sox can apply, see the
various files in /usr/doc/sox/, and read the sox man page (see Recipe 2.8.4
[Reading a Page from the System Manual], page 46).
Use sox with the stat option and -v to determine the largest possible value
that can be used before distortion or clipping occurs (it performs a statistical
analysis on the file and outputs a numeric value). This value comes in handy
when you want to raise a file’s volume as high as possible without ruining its
fidelity.
490 The Linux Cookbook, 2nd Edition
You can use this effect to raise or lower the pitch of a sound file. To do
this, specify the desired pitch as the argument to the -r option, and give this
option for the input file; then, specify the original sampling rate for the output
file as an argument to -r.
⇒ To slow the pitch of the sound in bell.wav, sampled at 44,100 Hz, and
write it to a new file called slowbell.wav, also at 44,100 Hz, type:
$ sox -r 30000 bell.wav -r 44100 slowbell.wav RET
In this example, the sound in bell.wav, sampled at 44,100 Hz, was played
at the slower 30,000 Hz. This was then resampled to the output file back to
the 44,100 Hz sampling rate, but the pitch now differs from the original.
NOTES: This last example makes a sound similar to some of the recordings
of the band Flying Saucer Attack. (You know who they are, don’t you?)
NOTES: The ‘echos’ effect works like ‘echo,’ but adds a sequence of echos to
the sound file.
Use sox for most sound-file conversions. Give as arguments the name of the
input file and the name of the output file to write to; use a file name extension
specifying the sound format for the output file (see Appendix B [Conventional
File Name Extensions], page 723).
⇒ To convert the file new.wav to an audio cd format file, type:
$ sox new.wav new.cdr RET
This command writes a new file, new.cdr, in the audio cd format; the
original file, new.wav, is not altered.
You may sometimes need to specify additional options, such as with raw
audio files where the sampling rate and other properties must be specified.
494 The Linux Cookbook, 2nd Edition
⇒ To convert all of the raw audio files in the current directory to audio CD
format files, type:
$ for i in *.raw RET
{ RET
sox -s -w -c2 -r 44100 $i -x $i.cdr RET
} RET
This command writes all of the .raw files to new files of the same name
but with a .cdr extension. You could then use cdrecord to burn an audio
cd with the .cdr files (see Recipe 22.3 [Writing an Audio Cd-r], page 482).
To convert a file to a particular format without using the standard exten-
sion, specify the format to write to with the -t option.
⇒ To convert the file new.wav to the audio cd format and write output to
a file named cd-single, type:
$ sox new.wav -t cdr cd-single RET
Mpg123
DEB: mpg321
RPM: mpg321
WWW: http://mpg321.sourceforge.net/
To convert an mp3 file to another format, use mpg321 (or another command
line mp3 player) to play the file to the standard output, and then use sox to
read the resultant raw audio and write it to another file with a specified input
format.
⇒ To convert the mp3 file remix.mp3d’ to a wav file remix.wav, type (all
on one line):
$ mpg321 -b 10000 -s remix.mp3 | sox -t raw -r 44100
-s -w -c 2 - remix.wav RET
NOTES: The process of making an mp3 file from a raw audio or wav format
audio file is called encoding (or sometimes “ripping”) an mp3 file; programs
Chapter 23: Editing Sound Files 495
that do this are mp3 encoders. This is not so much a recording process as it
is a conversion process: Existing audio is converted to mpeg audio format.
Unfortunately, the algorithm for encoding mp3s is patented, and all software
that uses it must pay a license fee. This restriction means that it is against
the law to write a software program to encode mp3 without licensing it. That
is the main reason why mp3 is now losing its popularity in favor of the Ogg
Vorbis audio format. As with many computing trends, this one has found its
early adopters in the Linux world.
Use oggenc to encode an Ogg Vorbis audio file. It takes an audio file as
an argument and writes a new file with the same base file name and an .ogg
extension. To specify a different file name, give the name to use as an argument
to the -o option.
⇒ To make an Ogg Vorbis file from the wav file interview.wav, type:
$ oggenc interview.wav RET
NOTES: The wav output can be further converted into other formats using
the traditional methods (for examples, see the previous recipe).
If you want to listen to the file as it’s being converted, you may do so by
giving an additional -d option for the audio system driver you have.
VI. PRODUCTIVITY
500 The Linux Cookbook, 2nd Edition
Chapter 24: Disk Storage 501
blocks available; the percent of the device used; and the name of the directory
tree the device is mounted on.
⇒ To see how much free space is left on the system’s disks, type:
$ df RET
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/hda1 195167 43405 141684 23% /
/dev/hda2 2783807 688916 1950949 26% /usr
/dev/hdb1 2039559 1675652 258472 87% /home/webb
$
This example shows that three filesystems are mounted on the system—the
filesystem mounted on / is at 23 percent capacity, the filesystem mounted on
/usr is at 26 percent capacity, and the filesystem mounted on /home/webb, a
home directory, is at 87 percent capacity.
$ du RET
8 ./projects/documentation
12 ./projects/source
4 ./projects/etc
24 ./projects
3 ./tmp
27 .
$
This example shows two subdirectories in the directory tree: projects and
tmp. The projects subdirectory contains three additional directories. The
Chapter 24: Disk Storage 503
amount of disk space used by the individual directories is the total on the last
line, 27 kb.
By default, output is in 1 kb blocks, but you can specify another unit to
use as an option: -k for kilobytes and -m for megabytes.
⇒ Here are two ways to use this.
• To output the disk usage, in kilobytes, of the /usr/local directory
tree, type:
$ du -k /usr/local RET
• To show the number of megabytes used by the file /tmp/cache, type:
$ du -m /tmp/cache RET
Use the -s option (“summarize”) to output only the last line containing the
total for the entire directory tree. This is useful when you are only interested
in the total disk usage of a directory tree.
⇒ Here are two ways to use this.
• To output only the total disk usage of the /usr/local directory tree,
type:
$ du -s /usr/local RET
• To output only the total disk usage, in kilobytes, of the /usr/local
directory tree, type:
$ du -s -k /usr/local RET
files on it—Linux may still be using the mounted files when you remove the
disk (see Recipe 2.1.2 [Turning Off the System], page 27).
The following sections show you how to format, mount, and unmount flop-
pies. On many systems, you need superuser privileges to do any of these
actions.
NOTES: For recipes describing the use of ms-dos (and Microsoft Windows)
formatted disks under Linux, see Recipe 26.1 [Using dos and Windows Disks],
page 525.
Once you have mounted a floppy, its contents appear in the directory you
specify, and you can use any file command on them.
⇒ Here are two ways to use this.
• To list the contents of the base directory of the floppy mounted on
/floppy, type:
$ ls /floppy RET
• To list the contents of the entire directory tree on the floppy mounted
on /floppy, type:
$ ls -lR /floppy RET
NOTES: You can copy files to and from the directory tree that the floppy is
mounted on, make and remove directories, and do anything else you could on
any other directory tree. But remember, before you remove it, you must first
unmount it.
NOTES: You can’t unmount a disk if your current working directory, the
directory you are in, is somewhere in that disk’s directory tree.3 In this case,
trying to unmount the disk will give the error that the /floppy filesystem is
in use; change to a different directory that isn’t in the /floppy directory tree,
and then you can unmount the disk.
Sometimes when you unmount a floppy, the light on the floppy drive will
go on and remain on for a few seconds after it has been unmounted. This
3
This is sometimes called being “under the mount point” of the disk.
506 The Linux Cookbook, 2nd Edition
This command makes the contents of the data cd available from the /cdrom
directory tree. You can use any Linux file command on the files and directories
on a data cd, but you can only write to one if it is a cdrw disc.
Like the /floppy directory, the use of the /cdrom directory is a standard
practice and convenient, but not necessary—you can mount disks in whatever
empty directory you like. (You could even, for example, mount discs from
the cd drive to /floppy and mount floppy disks to /cdrom, but why would
anyone do that!)
To mount a data cd to a specific directory, use mount and give as arguments
the name of the device file in ‘/dev’ corresponding to the cd drive, and the
name of the directory to mount to. This directory must already exist on the
filesystem, and it must be empty. If it doesn’t exist, use mkdir to create it
first (see Recipe 5.1.2 [Making a Directory], page 130).
Most Linux systems are set up so that the device file of the first cd drive
is /dev/cdrom, but the name of the device file may be different, especially if
you have a scsi cd-rom drive.
4
This works if your administrator has set up the cd drive filesystem for user access—see
Recipe A.6.3 [Letting Users Access Hardware Peripherals], page 718.
Chapter 24: Disk Storage 507
The contents of the disc in the cd drive will then be available in the
/usr/local/share/clipart directory tree, and you can then use the files
and directories on the data cd as you would any other files.
⇒ Here are some ways to use this.
• To peruse a directory tree graph of the data cd’s contents, type:
$ tree /usr/local/share/clipart | less RET
• To change to the root directory on the data cd, type:
$ cd /usr/local/share/clipart RET
• To list the contents of the root directory on the data cd, type:
$ ls /usr/local/share/clipart RET
NOTES: As with unmounting any kind of filesystem, make sure that none of
the files on the disc are in use, or else you won’t be able to unmount it. For
example, if the current working directory in a shell is somewhere inside the
/cdrom directory tree, you won’t be able to unmount the data cd until you
change to a different directory.
508 The Linux Cookbook, 2nd Edition
Chapter 25: Printing 509
25. Printing
The usual way to print on a Linux system is to send a print job to the printer
with lpr, as described in Recipe 25.1.1 [Sending a Print Job to the Printer],
page 510.
But you won’t always send a file straight to the printer—sometimes you
may want to add special things to it before you print, such as headers or
graphic trim. Or you might want to split a text file into pages and add a
header to the top of each page containing the file name and page number; all
of this is described in Chapter 13 [Formatting Text], page 305.
Sometimes you may need to convert or otherwise prepare a file so that it
can be printed on your particular printer, since not all print hardware can
print the same kinds of file formats. Recipes in this chapter show how to do
this, such as how to convert PostScript files so that they will print properly
on a non-PostScript printer (see Recipe 25.3 [Preparing Files for Printing],
page 518).
This chapter also shows how to format PostScript files for printing. To
convert plain text to PostScript and enhance it for printing, by adding fonts,
graphic headers, and the like, see Recipe 15.2 [Outputting Text to PostScript],
page 359.
This chapter isn’t in the files section of the book because you can print
things that aren’t in a file—for example, you can pipe the output of another
tool or series of tools to lpr, and it will spool that command output to the
printer. This usage is actually very common.
If you have more than one printer connected to your system, specify the
printer to send to as an argument to the -P option. (Printers have names just
as user accounts and hosts do, and it is the administrator’s privilege to name
them; the default printer is usually called lp, for “line printer.”)
⇒ To send the file nightly-report to the printer called statomatic, type:
$ lpr -P statomatic nightly-report RET
NOTES: The name of the lpr tool comes from “line printer,” which was the
kind of printer hardware in popular use back when this program was first
developed.
$ lpq RET
lp is ready and printing
Rank Owner Job Files Total Size
active groucho 83 cigar.ps 1739030 bytes
1st harpo 84 harp.ps 499 bytes
2nd chico 85 love.ps 45576 bytes
$
In this example, there are three jobs queued for the default printer—one by
user groucho, for the file cigar.ps, one by user harpo, for the file harp.ps,
and one by user chico, who has printed a file called love.ps.
The job by user groucho is the active job; this is the job that is currently
printing on the printer. The other jobs must wait until this file is finished
printing, and then they print in rank order.
As with lpr, you can specify the name of a printer as an argument to the
-P option.
⇒ To view the spool queue for the printer called statomatic, type:
$ lpq -P statomatic RET
To only list the jobs for a particular user, give the name of the user as an
argument.
⇒ To list the print jobs for user harpo, type:
$ lpq harpo RET
NOTES: When there are no print jobs, lpq outputs the text “no entries.”
When lprm cancels a job, it outputs the names of any print files that have
been dequeued and removed (a single print job is usually listed in two lines).
If you don’t have a print job to cancel, lprm will report nothing.
512 The Linux Cookbook, 2nd Edition
You can also cancel a print job by its job number. To do this, give as an
argument the number of the print job to remove.
⇒ To cancel print job 83, type:
$ lprm 83 RET
To cancel all of your print jobs in the spool queue, use a hyphen instead
of the number of a print job. This is good for when you’ve sent several jobs
to the printer but you want to cancel them.
⇒ To cancel all of your print jobs, type:
$ lprm - RET
NOTES: If you try to cancel an active job—one that has already been spooled
to the printer—don’t be alarmed if some pages still print; the printer probably
has some of the job in its internal print buffer. To stop the printing in a case
like this, take the printer offline, reset it, and then put it back online again
(the printer will usually have buttons for these commands on its front control
panel).
You can also specify the number of lines to output; do this by giving the
new number as a second argument. This is useful for writing some “dummy”
data to a file, when you need some.
⇒ To write a ripple pattern ten lines long, with 25 characters per line, to
the file testing, type:
$ lptest 25 10 > testing RET
To print only certain pages of a PostScript file, specify those pages with
514 The Linux Cookbook, 2nd Edition
psselect and pipe the output to lpr (see Recipe 20.1.2 [Extracting Pages
from a PostScript File], page 452). This is useful for when you have a very
large file to print and you want to send it to the printer in sections.
⇒ Here are two ways to use this.
• To print pages 1 through 100 from the file input.ps, type:
$ psselect -p1-100 input.ps | lpr RET
• To print four copies of pages 1 through 100 from the file input.ps,
type:
$ psselect -p1-100 input.ps | lpr -#4 RET
METHOD #1
Printing a Web page is usually done with Mozilla or another graphical Web
browser.
In Mozilla, select Print from the File menu, or type ALT- P while
Mozilla is displaying the page you want to print. You can choose paper size,
color, page order, and margins; you can also select the printer device, or print
the page to a PostScript file (see Recipe 33.1 [Using Mozilla], page 638).
This is the common method.
METHOD #2
To print the contents of a Web page with lpr, use lynx with the -dump
option to pass the contents directly to lpr, or optionally through other filters
or commands.
Chapter 25: Printing 515
NOTES: This is also a good method for sending the contents of a Web page
through any number of filters or pipelines in general.
METHOD #3
When in lynx, press P when on the page you want to print. This will bring
up a new page, giving the url of the page you were viewing and telling you the
number of lines it contains and the number of physical pages it makes when
printed. You will also be given four options: Save to a local file, Mail the
file, Print to the screen, and Print out on a printer attached to your
vt100 terminal. The last option will send it to the printer.
If you save to a local file, a plain text file will be written to the current
directory with the name you specify. You can then process and print that file.
You can print a dvi file directly with the dvips tool—omit the -o option
that is used to specify an output file, and it will send the PostScript output
directly to the spool queue of the default printer.
⇒ To print the dvi file list.dvi, type:
$ dvips list.dvi RET
516 The Linux Cookbook, 2nd Edition
The following table lists some of dvips’s options for controlling print out-
put.
NOTES: You can also print dvi files with lpr using the -d option.
METHOD #1
To print the current buffer in Emacs, choose Print Buffer from the Print
submenu, found on the Tools menu on the menu bar. Another option on
Chapter 25: Printing 517
the print submenu is Print Region, which just prints the text between point
and the mark (see Recipe 10.1.1 [Getting Acquainted with Emacs], page 232).
Both commands print the hardcopy output separated into pages, with headers
at the top of each page showing the file name and current page number.
METHOD #2
To generate and print a PostScript image of the buffer, use the ps-print-
buffer function, which is also available on the Print submenu. A related
function, ps-print-region, prints a PostScript image of the region. These
commands are useful for sending the text of a buffer to a PostScript printer.
⇒ To send the current Emacs buffer to the default printer as a PostScript
file, type:
ALT- X ps-print-buffer RET
METHOD #3
You can also run any of the aforementioned print functions by specifying them
with the ALT- X command. Additionally, the lpr-buffer and lpr-region
functions send the buffer and region to lpr without paginating the text or
inserting headers.
⇒ Here are some ways to use this.
• To print the current buffer with page numbers and headers, type:
ALT- X print-buffer RET
If you don’t have a PostScript printer, you can use Ghostscript, gs, to convert
PostScript to an output format that your printer understands.
Use the -? option to list the printers that the version of gs installed on
your system can write output for.
Chapter 25: Printing 519
$ gs -? RET
GNU Ghostscript 5.10 (1998-12-17)
...more output messages...
Input formats: PostScript PostScriptLevel1 PostScriptLevel2 PDF
Available devices:
x11 x11alpha x11cmyk x11gray2 x11mono lvga256 vgalib
t4693d8 tek4696 appledmp ccr lp2563 lbp8 lips3 m8510
oki182 okiibm la50 la70 la75 la75plus sxlcrt deskjet
djet500 laserjet ljetplus ljet2p ljet3 ljet4 declj250
cdeskjet cdjcolor cdjmono cdj550 cdj500 djet500c
hpdj uniprint epson eps9mid eps9high epsonc lq850
ap3250 ibmpro bj10e bj200 bjc600 bjc800 ljet3d faxg3
faxg32d faxg4 dfaxhigh dfaxlow pcxmono pcxgray pbm
pbmraw pgm pgmraw pgnm pgnmraw pnm pnmraw ppm ppmraw
pkm pkmraw tiffcrle tiffg3 tiffg32d tiffg4 psmono
psgray jpeg
...more output messages...
$
A typical gs installation can write to more than 100 different print devices,
including hp LaserJet 4 printers (“ljet4”), hp Color Deskjets (‘cdeskjet’),
and Group 4 fax (“tiffg4”). Newer versions of gs will have better support
for newer printers, so make sure that you have a recent version installed if you
have a new model printer.
gs takes the file to convert as an argument; give the device to write output
for as an argument to the -sDEVICE= option, and give the name of the file to
write to as an argument to the -sOutputFile= option.
Two additional options are commonly used: -dSAFER, which prevents the
accidental deleting or overwriting of files, and -dNOPAUSE, which turns off the
pause between pages.
When the conversion is complete, you will be at the gs prompt; type quit
to exit.
⇒ To convert the file tiger.ps to a format suitable for printing on an hp
Color Deskjet 500 printer, type (all on one line):
$ gs -sDEVICE=cdj500 -sOutputFile=tiger.dj -dSAFER
-dNOPAUSE tiger.ps < /dev/null RET
520 The Linux Cookbook, 2nd Edition
This command writes the output to a file, tiger.dj, which you can spool
as a print job with lpr to print it.
To convert a file from dvi format to PostScript, use dvips. It takes the file
to convert as an argument; give the name of the PostScript file to write to as
an argument to the -o option.
⇒ To convert the file abstract.dvi to PostScript, type:
$ dvips -o abstract.ps abstract.dvi RET
This command reads the dvi file abstract.dvi and writes a PostScript
version of it to the file abstract.ps; the original file is not altered.
To write only certain pages of a dvi file to the PostScript output, give the
page or pages as arguments to the -pp option.
⇒ Here are some ways to use this.
• To output only pages 14 and 36 from file abstract.dvi to a
PostScript file, ‘codeabstract.ps, type:
$ dvips -pp14,36 -o abstract.ps abstract.dvi RET
• To output pages 2 through 100 from file abstract.dvi to a
PostScript file, abstract.ps, type:
$ dvips -pp2-100 -o abstract.ps abstract.dvi RET
• To output page 1 and pages 5 through 20 from file abstract.dvi to
a PostScript file, abstract.ps, type:
$ dvips -pp1,5-20 -o abstract.ps abstract.dvi RET
Use the -P option with dvips to specify the printer name to write output
to—use this option to make output for non-PostScript printers. For exam-
ple, to convert TEX and LaTEX files to pdf, use dvips and give “pdf” as an
argument to the -P option.
⇒ To generate a pdf file from the dvi file abstract.dvi, type:
$ dvips -Ppdf -o abstract.pdf abstract.dvi RET
Ghostscript
DEB: gs-common
gs
RPM: ghostscript
WWW: http://www.cs.wisc.edu/~ghost/
There are at least two ways to convert and print a file that’s in Adobe’s
Portable Document Format (pdf), usually marked with a .pdf file name
extension.
The first way is to view the file in xpdf (the pdf file viewer), and then
left-click the printer icon. This won’t actually send the file to the printer, but
it writes a PostScript file in the same directory, with the same base file name
as the pdf file but with a .ps extension. You can then print this file with
lpr or convert it to another format (see Recipe 25.3.1 [Preparing a PostScript
File for Printing], page 518).
522 The Linux Cookbook, 2nd Edition
The second way is to use pdf2ps, part of the ‘gs’ package, to convert
the pdf file to PostScript (to then print the PostScript output as described
for xpdf above). pdf2ps takes two arguments: the name of the pdf file to
convert, and the name of the PostScript file to write to.
⇒ To convert the pdf file pricelist.pdf, type:
$ pdf2ps pricelist.pdf pricelist.ps RET
In the last example, you can then use gs to convert the file to a format your
non-PostScript printer understands (see Recipe 25.3.1 [Preparing a PostScript
File for Printing], page 518).
NOTES: A manual “page” can actually contain more than one physical page;
the output will have as many pages as necessary to print it.
There are two methods worth noting for preparing etexts for printing.
METHOD #1
Etext filter
WWW: http://dsl.org/comp/enscript/
Use the “etext” filter for enscript to convert an etext to PostScript. This
takes a plain text file written with etext conventions, including etext-style
italics (see Recipe 13.9 [Underlining Text], page 327), converts the italics, and
writes a PostScript file as output.
⇒ To convert the etext youth.txt to PostScript, type:
$ enscript -Eetext -B -f "Times-Roman12" -o youth.ps youth.txt RET
METHOD #2
Txt2html
DEB: txt2html
RPM: txt2html
WWW: http://txt2html.sourceforge.net/
This command writes a new file, essays.html, that you can then print
with a Web browser.
NOTES: You could also convert the text to LaTEX with txt2tex (see
Recipe 15.7 [Using Other Word Processors and Typesetting Systems],
page 391).
524 The Linux Cookbook, 2nd Edition
Chapter 26: Cross-Platform Conversions 525
⇒ To get a directory listing of the dos disk currently in the primary floppy
drive, type:
$ mdir a: RET
To copy a file from a dos disk, give the “drive letter” of the disk to copy
from, followed by the file name to copy, and no other arguments; mcopy will
copy the specified file to the current directory.
⇒ To copy the file resume.doc from the dos disk in the secondary floppy
drive to the current directory, type:
$ mcopy b:resume.doc RET
To copy all files from a dos disk, just give the “drive letter” without any
file names.
⇒ To copy all of the files and directories from the dos disk in the primary
floppy drive to the current directory, type:
$ mcopy a: RET
⇒ To format the floppy disk in the primary floppy drive so that it can be
used with ms-dos, type:
$ mformat a: RET
NOTES: If you want to use a floppy disk with your Linux system and don’t
need dos compatibility, don’t bother using this ms-dos format—the native
Linux format is much more efficient (see Recipe 24.3.1 [Formatting a Floppy
Disk], page 504). If you know how long a dos format takes, you’ll be amazed
at how much faster the Linux formatting is—it will be done so fast you’ll think
it didn’t even work!
Apple Macintosh computers use a filesystem called the “Hierarchical File Sys-
tem,” or hfs. If your kernel has support for the hfs filesystem, you can mount
disks from these systems by using mount and specifying “hfs” as an argument
to the -t option (see Recipe 24.3.2 [Mounting a Floppy Disk], page 504).
You can also use these disks with the hfsutils package, which contains
a set of tools for reading from and writing to hfs filesystems. The following
recipes describe the use of the individual tools in this package.
After you run this command, the other tools in the hfsutils package will
work on the Macintosh disk in the first floppy drive.
528 The Linux Cookbook, 2nd Edition
Give the name of a directory as a quoted argument to list just that direc-
tory.
⇒ To get a directory listing of the Desktop Folder directory in the currently
specified Macintosh disk, type:
$ hls 'Desktop Folder' RET
To copy a file from a Macintosh disk, give two arguments: the name of
the directory and the file to copy as a quoted argument, and the name of
the Linux target directory to copy to. Remember that macos uses the colon
character (:) as the separator on the path.
⇒ To copy the file Desktop Folder:Readme from the current Mac disk to
the current directory, type:
$ hcopy 'Desktop Folder:Readme' . RET
METHOD #1
Tofrodos
DEB: sysutils
RPM: tofrodos
WWW: http://www.uni-kassel.de/hrz/server/Software/dos2unix/
The fromdos and todos tools allow you to convert text files between dos and
Linux.
To convert a text file from dos to Linux, removing the “^M” newline char-
acters in the file, use fromdos. It converts the file you give as an argument,
removing the newline characters from the ends of all its lines.
To convert a text file from Linux to the convention used by dos and Win-
dows, use todos. It adds newline characters to the ends of all lines in the file
you give as an argument.
Chapter 26: Cross-Platform Conversions 531
NOTES: Both commands write directly to the files you specify. To make a
backup of the original file, use the -b option; before the conversion, this writes
a copy of each specified file with a .bak file name extension.
METHOD #2
Use the col filter to filter out carriage returns from text, as described in
Recipe 13.1.9 [Removing Carriage Return Characters], page 310.
⇒ To filter out the carriage returns from the file README.TXT, writing to a
new file called readme.txt, type:
$ col < README.TXT > readme.txt RET
METHOD #3
Another way to convert text from dos is to use the tr filter to delete the
carriage returns (see Recipe 13.4 [Transposing Characters in Text], page 316).
⇒ To filter out the carriage returns from the file dos-version.txt, writing
to the new file unix-version.txt, type:
$ tr -d '\r' < dos-version.txt > unix-version.txt RET
NOTES: To do the reverse of this—to convert text from unix to dos—I have
been told that simply opening the file in the dos text editor program called
edit, and then saving the file and exiting, will work. This will automatically
add the requisite carriage returns to the end of each line.
Use word2x to convert Microsoft Word files to a format you can read. It can
convert files to two different formats: LaTEX and plain text.
Convert to LaTEX when the layout of the original document, including its
formatting and font characteristics, is important. When you just need the
complete text of the document, convert it to plain text. word2x can send its
output to the standard output, so the latter conversion is useful for adding to
a pipeline.
Word files usually have a .doc or .DOC extension, which you don’t have
to specify. For example, if the Word file you want to convert is called
resume.doc, you can simply give resume as the source file. (But if there exists
another file named resume in the same directory, this trick won’t work).
If you don’t specify an output file, word2x writes its output to a file with the
same base file name and an appropriate extension for the output format. This
is useful for converting a lot of Word files in the same directory—specifying a
wildcard such as *.doc as the input and giving no output name will convert
them all.
You can also set the maximum line width to be used in the output file;
specify the width as an argument to the -w option.
The following recipes describe how to use word2x to convert Word files to
LaTEX and plain text format.
NOTES: While word2x does a pretty good job of conversion, it won’t convert
any pictures embedded in Word documents.
There are other ways to read or convert Word files; see Recipe 26.8 [Using
Other Cross-Platform Conversion Tools], page 535, for a list of other tools
you can use for this purpose.
This command writes a new file, resume.ltx, in the LaTEX format. You
can then view, print, or convert the file to other formats—see Recipe 15.3.3
[Processing a LaTEX File], page 374. The original resume.doc file is unaltered.
Chapter 26: Cross-Platform Conversions 533
⇒ To convert all of the .DOC Word files in the current directory to LaTEX
files with maximum line widths of 40 characters, type:
$ word2x -f latex -w 40 *.DOC RET
These commands convert the Word file resume.doc to text and output all
lines of that text, if any, that contain the string “linux” regardless of case.
The original resume.doc file is unaltered.
zip file compression takes one or more files and compresses them into a single
new file with a .zip extension. This is what most people new to Linux or unix
in general think of when they think of “file archives.” But in the unix world,
file archives and compression are separate tools, even though they usually go
hand in hand. We make compressed tar archives (see Recipe 8.5 [Manag-
ing File Archives], page 199). And then we can compress these archives, or
any other file, with gzip or bzip2 (see Recipe 8.4 [Using File Compression],
page 196).
When sending and receiving groups of files with people who use other
operating systems, the zip archive format is usually used. The zip and unzip
tools make and extract zip archives as done by the popular pkzip tools for
other operating systems.
The following recipes show how to use these tools.
When specifying a directory, if you give just the directory name, only that
directory (and not its contents) will be included in the archive. Specifying a
wildcard in a directory will include the files it contains and any subdirectory
names, but it will not travel into those subdirectories to include any files that
may be contained there. Use the ‘-r’ option to travel recursively into any
specified directories, thus including its entire contents.
⇒ To make a zip archive zippy.zip containing all files in the current direc-
tory, type:
$ zip zippy * RET
Chapter 26: Cross-Platform Conversions 535
If the current directory contains any directories, those directory names are
included in the zip archive, but not any of their contents.
⇒ To make a zip archive zippy.zip containing all files in the current direc-
tory, as well as all files in the addons directory, type:
$ zip zippy * addons/* RET
This command puts all files in the current directory in an archive called
zippy.zip, to which it also adds all files in the addons directory, but it does
not add the contents of any subdirectories that addons may contain.
⇒ To make a zip archive zippy.zip containing the entire addons directory
tree, type:
$ zip zippy -r addons/* RET
It is sometimes a good idea to take a look inside the zip archive first, to see
what you are getting into by unzipping—if a zip archive contains a hundred
files and you are not expecting them, it could be inconvenient to just unzip it
first.
That’s where the -t option comes in handy, and I use it all the time
before unzipping an archive for real. This just tests the files contained in the
archive to make sure that the archive file has not become corrupt. As unzip
runs through the tests, it lists each file in the archive. None of the files are
unzipped with this command.
⇒ To test the zip archive blueprints.zip for errors, thus listing all the
files it contains, type:
$ unzip -t blueprints.zip RET
27. Reminders
When you spend a lot of time working on the system, it can be very useful to be
reminded when you should be doing something else. You can have the system
do this for you, and this chapter tells you how. It describes software tools
that provide reminders of various kinds—clocks, calendars, address books,
and tools for tracking appointments.
$ date RET
Thu Jul 1 10:09:57 EDT 2004
$
The default format of the output is to display the day of the week; the
month name; the day of the month; the 24-hour time in hours, minutes, and
seconds; the time zone; and the year.
Use the -u option to output the current date and time in gmt (“Greenwich
Mean Time,” also known today as “Coordinated Universal Time”, or utc).
⇒ To output the current date and time in utc, type:
$ date -u RET
Thu, 1 Jul 2004 10:09:57 -0400
$
Use the -R option to output the date in the format described in rfc822
(see Recipe 11.4 [Word Lists and Reference Files], page 289): day of week
followed by day of month, month name, year, time, and time zone in numeric
format. This is the date format used in email messages.
⇒ To output the current date and time in rfc822 format, type:
$ date -R RET
Fri, 11 May 2001 11:10:29 -0400
$
538 The Linux Cookbook, 2nd Edition
You can also use the -d option to specify the precise fields to output, and
the order in which to output them. One useful example is given in the next
recipe; for more information, consult the date man page (see Recipe 2.8.4
[Reading a Page from the System Manual], page 46).
The date tool has many parameters for formatting the output, all of which
are preceded with +. They are sometimes useful for putting into scripts. The
following recipes describe a few.
NOTES: To ensure that the time on your system clock remains as accurate
as possible, your system administrator should install the chrony package; it
periodically adjusts the time on the system clock according to measurements
obtained from time service servers on the Internet via “Network Time Proto-
col.”
To output the number of days a particular date is into the year, use -d
with “'DD MMM ' +%j,” where DD is the day of the month and MMM is
the name of the month.
⇒ To output the numeric day of the year that 21 June falls on in the current
year, type:
This command outputs the number 172, which indicates that June 21st of
the current year is the 172nd day of the current calendar year.
Use the saytime command to output the current system time in an audible
message in a male voice. You must have a sound card installed on your system,
and it must be set up with speakers or some other output mechanism at an
appropriate volume level in order for you to hear it (see Recipe 21.1 [Adjusting
the Audio Controls], page 463).
⇒ To hear the current system time, type:
$ saytime RET
NOTES: If you’re feeling adventurous, you can record another voice—like your
own—and use that voice instead of the default voice; the sound files used are
Sun .au files, and they are kept in the /usr/share/saytime directory.
To output a calendar for a specific year, give just the year as an option.
540 The Linux Cookbook, 2nd Edition
⇒ To output a calendar for the current month with Julian dates, type:
$ cal -j RET
To output a calendar for a specific month, give both the numeric month
and year as arguments.
⇒ To output a calendar for the month of April 1945, type:
NOTES: When you display a calendar for a specific month and year, Emacs
fills in the current year in the minibuffer. In the previous example, the current
year was 2010, and BKSP was typed twice to erase the last two digits, which
were replaced with “00” to make it the year 2000.
$ calendar RET
6/16 Finish draft of book
Party at Jack's
Fri Lunch with Kim and Jim, 12:30
Mon Book manuscript due
$
Figure 27-1. Typical calendar output.
The following are recipes for writing your calendar files, including other
calendar files in your own calendar file, and for automating the delivery of
your reminders.
NOTES: The calendar tool was a one-time staple of unix systems, and re-
portedly first appeared in Version 7 of at&t unix. It was rewritten early
on for the bsd family of unix. Although this bsd derivative is a standard
inclusion on Debian systems, calendar isn’t yet standard on all Linux distri-
butions, and a source or binary of the tool can be difficult for users of other
distributions to locate. I advise those users to download the source files for
the Debian bsdmainutils package and to install calendar from there.
Emacs has its own equivalent to this tool, which it calls the “Diary.” For
more information on this feature, see the Emacs Info documentation (see
Recipe 2.8.5 [Reading an Info Manual], page 48).
Chapter 27: Reminders 543
Just about every common date style is recognized. For example, Figure
27-2 shows a listing of valid dates for the fourth of July.
7/4
July 4
4 July
Jul. 4
Jul 4
4 Jul.
4 Jul
Figure 27-2. Valid dates for the fourth of July.
Entries aren’t constrained to a single day, either; you can have entries for a
day of the week or for a certain month—“Mon” or “Monday” for every Monday;
“Jun” or “June” for the first day of every June. You can use an asterisk as
a wildcard: “*/13” reminds you of something on the 13th of every month.
When the date is omitted on a line, the date of the preceding appointment is
assumed.
For example, suppose you have a file called calendar in your home direc-
tory that looks like Figure 27-3.
If the current date is 16 June, a Friday, and you run calendar in your
home directory, you’ll get the same output as in Figure 27-1.
NOTES: In the preceding example, the entry for the party doesn’t have a date
on it—it used the date of the preceding entry, “6/16.”
To have calendar output dates from one of these files along with your
usual appointments, put the following line in your calendar file, where file is
the name of the particular calendar file you want to include:
#include <file>
#include <calendar.usholiday>
#include <calendar.birthday>
Figure 27-4. Includes for calendar.
Chapter 27: Reminders 545
For example, to output both U.S. holidays and famous births and deaths
when you run calendar, your calendar file would include the two lines given
in Figure 27-4.
NOTES: You can, of course, share your own calendar files with other users;
this is useful for making special calendars for a group or organization. If the
calendar file is in the current directory or /usr/share/calendar, you can just
give the file name; otherwise, give its full path name in the include statement.
⇒ To add to the cron schedule any new entries that are in the file crontab,
type:
$ crontab crontab RET
NOTES: The name of the command, crontab, is the same as the file it uses,
crontab.
“fields”; you can even cut and paste text into it from email, the Web, or other
windows (see Recipe 10.3 [Manipulating Selections of Text], page 253).
Mary Smith
14 Elm St
Centerville, New York
###
###
Figure 27-5. The rolo file.
There are several ways to find text in such a file. Suppose, for example,
you want to contact your friend Susan, and you need her telephone number.
⇒ To output the line in the file containing the text “susan,” regardless of
case, type:
This works nicely when the information you need is on the same line as
the information you search for—here, the name Susan is on the same line as
the telephone number; however, the output did not show the warning that
appears on the next line in the file. And what about when the term you
search for and the information you need are on adjacent lines?
Use the -C option with grep to output several lines of context before and
after matched lines.
548 The Linux Cookbook, 2nd Edition
⇒ To output the several lines around the line matching the text “Jenkins,”
type:
• To search for the next entry containing the text “New York,” regard-
less of case, type:
CTRL- S
You can repeat this keystroke as many times as you wish to show all entries
in the entire buffer with the text “New York” in them. Once you reach the
end of the buffer, type CTRL- S again to loop around to the beginning of the
buffer and continue the search from there. (The minibuffer will tell you when
you’ve reached the end of the buffer, and will remind you to type this if you
want to loop the search.)
NOTES: It’s also useful to peruse and search through these kinds of files with
less—see Recipe 14.11 [Searching the Text You’re Perusing], page 354.
The Insidious Big Brother Database is a contact manager tool for use with
Emacs. You can use it with Emacs email and news readers; it stores contact
information in records and allows you to search for records that match a
regular expression, as well as records whose particular fields match a regular
expression (see Recipe 14.3 [Matching Patterns of Text], page 335).
There are several ways to add a record to the database. Use the bbdb-
create function to manually add a record. (When you run this command,
bbdb prompts you to enter the relevant information for each field.) When in a
mail reader inside Emacs, type a colon (:) to display the record for the author
of the current message; if there is none, bbdb asks whether or not one should
be created.
⇒ Here are two ways to use this.
• To create a new bbdb record from scratch, type:
ALT- X bbdb-create RET
• To add a new bbdb record for the author of the current email message,
type:
:
Use the bbdb function to search for records—it takes as an argument the
pattern or regexp to search for.
⇒ To output records containing the text “scott” anywhere in the record,
type:
ALT- X bbdb RET scott RET
There are additional functions that let you narrow your search to a par-
ticular field: bbdb-name, bbdb-company, bbdb-net, and bbdb-notes, which
respectively search the name, company, email address, and notes fields.
⇒ To output records matching the regexp “*\.edu” in the email address,
type:
ALT- X bbdb-net RET *\.edu RET
Use the leave tool to remind yourself when you have to leave. Give as an
argument the time when you have to go, using the format of hhmm, where hh
is hours in 24-hour format and mm is minutes.
⇒ To remind yourself to leave at 8:05 p.m., type:
$ leave 2005 RET
When you run leave with no arguments, it prompts you to enter a time;
if you just type RET, leave exits without setting the reminder. This method
is good for adding leave to scripts or to your .bashrc, so that you can inter-
actively give a time to leave, if desired, when the script runs (see Recipe 3.7.3
[Using Shell Startup Files], page 86).
NOTES: leave will output a reminder on the terminal screen five minutes
before the given time, one minute before the time, at the time itself, and then
every minute subsequently until the user logs off.
⇒ For example, if your username on your local system is joe, to send yourself
an email reminder, you’d type:
NOTES: For more about using the mail tool, see Recipe 32.1 [Sending Mail],
page 612.
I am away from the University for the first week of February. I will
return on February 8th and will address your mail then. If your business
is urgent, please address Dr. Edwards, at [email protected].
Figure 27-6. The .vacation.msg file.
Then, edit another hidden file in your home directory called .forward, and
put the following line in it:
\cpeterson, "|/usr/bin/vacation cpeterson"
This will save a copy of all incoming mail in your inbox, and it will use
vacation to reply to any mails addressed to the username cpeterson; the
reply mail will be the one you wrote in .vacation.msg.
552 The Linux Cookbook, 2nd Edition
Then, when you return from vacation, just move the .forward file to
something else.
⇒ To move your .forward to .forward.not, type
$ mv .forward .forward.not RET
NOTES: You can leave the .vacation.msg file where it is, and edit it as
needed next time you are about to go away.
If you run vacation, it is a good idea to unsubscribe yourself from any
mailing lists before your absence. That way, you will avoid the embarrassment
of sending your message out to all the subscribers of a list whenever someone
posts a message to it.
This lists all the files that were last modified on September 11, 2001. Use
-anewer to list files were last accessed that day, and -cnewer to list files
that were last changed that day. Two temporary files are made with special
timestamps, /tmp/911 and /tmp/912.
The following table lists additional tools that can be used to generate re-
minders, including calendars and appointment managers.
28. Scheduling
Sometimes it is useful to specify a command or set of commands so that they
run not immediately, but at some other time. This chapter describes tech-
niques for handling this sort of function, as well as techniques for monitoring
commands that are currently running.
You can also give the time in minutes, hours, or days. To do this, follow
the argument with a unit, as listed in the following table.
s Seconds
m Minutes
h Hours
d Days
⇒ To announce the time in exactly five minutes, type:
$ sleep 5m; saytime & RET
1
The shell command separator; see Recipe 3.1.7 [Running a List of Commands], page 63.
556 The Linux Cookbook, 2nd Edition
$ at 17:05 RET
warning: commands will be executed using /bin/sh
at> mail chuck -s "IT'S TIME TO GO!" < /dev/null RET
at> CTRL- D <EOT>
job 5 at 2003-08-09 17:05
$
In this example, the username is chuck and the job number scheduled by
at is 5.
The at tool understands many time formats, from the month, day, and
year to the hour and minute (optionally given in military time, or followed
by “AM” or “PM”), and the special words “midnight,” “noon,” and “teatime”
(the last of which translates to 4 p.m.). You can use the suffixes “today”
or “tomorrow,” and you can use a “+” after a time followed by a number of
minutes, hours, days, or weeks—for example, “8pm + 2 days” means to run
two days from 8 p.m. tonight. So to run a command at a week from midnight,
use “midnight + 1 week.”
⇒ To schedule ~/bin/clean and ~/bin/tidy to run at 9 p.m. tomorrow,
type:
Instead of giving the commands from the standard input, you can specify
a list of commands to run from a file. To do this, give the name of the file as
an argument to the -f option.
⇒ To have the system run the commands in the file extra.work at midnight
tonight, type:
$ at -f extra.work midnight RET
NOTES: This method is not for running a command in your current shell, or
running a command at your terminal; to do either of these, see Recipe 28.1
[Delay Command], page 555.
If you want to run a job at some regular interval, use cron instead (see
Recipe 28.3 [Scheduling Commands], below).
possible value to the last possible value of the field, inclusive. Time and date
fields may also contain ranges of numbers, and individual numbers may be
given separated by commas.
To write comments in your crontab file, begin a lines with a hash sign (#);
the line will be ignored by the system. Blank lines are also ignored.
For example, a simple crontab file might look like Figure 28-1.
# Runs the 'bar' command at 1:23 in the morning on every day in June.
23 1 * Jun * bar
# Runs the 'foobar' command at half-past four and five p.m. every Monday
# through Wednesday whose day of the month is between 1 and 14.
30 16,17 1-14 * Mon-Wed foobar
Figure 28-1. A simple crontab file.
The following recipes show how to manage cron jobs.
NOTES: To remove only some of your cron jobs, or to change your cron
jobs, just revise your crontab file, deleting or revising the entries you want to,
and then add your cron table (as described in the previous recipe).
Chapter 28: Scheduling 559
This command will display the contents of the current directory in the
terminal you run it in, and it will continually update every two seconds. To
change the interval, give it as an argument to the -n option.
⇒ To watch the detailed contents of the current directory, updating by the
second, type:
$ watch -n 1 ls -l RET
NOTES: Sometimes you might find it nice to run your watch session in a
little xterm of its own. If you’re not in X, you might want to devote a console
terminal to it.
560 The Linux Cookbook, 2nd Edition
Chapter 29: Mathematics 561
29. Mathematics
Tools and techniques for dealing with numbers are the subject of this chapter:
listing them in sequence or randomly, calculating arithmetic, cryptography,
and converting between units. Larger applications, such as spreadsheets and
plotting tools, are also mentioned.
#!/bin/sh
echo $(( expression = $ ))
Figure 29-1. The calc script.
Once you install this script (see Recipe A.3.4 [Installing a Shell Script],
page 708), you can use it at the shell prompt to get the results of any simple
arithmetic calculation.
To do this, give the expression to evaluate as an argument to calc. Use an
asterisk (*) for a multiplication sign and a forward slash (/) for division; to
output the remainder, use a percent sign (%) instead of a slash. You can use
parentheses to group expressions—but when you do, be sure to quote them
(see Recipe 3.1.3 [Quoting Reserved Characters], page 56).
562 The Linux Cookbook, 2nd Edition
NOTES: This is a method for speed. It’s useful for quickly computing a simple
arithmetic equation at the shell prompt, but it has several drawbacks: It only
outputs whole integers; its operators are limited; and complex expressions
must be quoted. Still, if you’re at a shell prompt and need to know the
product of 12,342 and 587, I don’t think there’s a faster way. But for doing
anything more than the very simplest operations, see the next recipe, which
describes bc.
There are a great many calculators, for X or any terminal. One of the more
Chapter 29: Mathematics 563
$ bc RET
bc 1.06
Copyright 1991, 1992, 1993, 1994, 1997, 1998, 2000 Free Software
Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
42 * 17 RET
714
quit RET
$
$ bc RET
bc 1.06
Copyright 1991, 1992, 1993, 1994, 1997, 1998, 2000 Free Software
Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=20 RET
10 / 3 RET
3.33333333333333333333
quit RET
$
Use the -l option to start bc with a scale of 20, and with a number of
math functions loaded, as described in the following table.
The following table describes the symbols you can use to specify mathe-
matical operations.
To output the sequence from any one number to another, give those num-
bers as arguments.
⇒ Here are two ways to use this.
• To output the sequence of numbers from 9 to 0, type:
$ seq 9 0 RET
• To output the sequence of numbers from -1 to -20, type:
$ seq -1 -20 RET
Use the -w option to pad numbers with leading zeros so that they’re all
output with the same width.
Specify a separator string to be output between numbers as an argument to
the -s option; the default is a newline character, which outputs each number
in the sequence on its own line.
⇒ Here are two ways to use this.
• To output the sequence of numbers from 9 to 999, incrementing by
23, with numbers padded with zeros so that they’re all of equal width,
type:
$ seq -w 9 23 999 RET
• To output the sequence of numbers from 1 to 23, with a space char-
acter between each, type:
$ seq -s ' ' 1 23 RET
Use the units tool to convert a measurement from one measurement scale to
another. Give two quoted arguments: the value and the name of the units
you have, and the name of the units to convert to. It outputs two values: the
converted value in the new units, and how much of the original measurement
is equivalent to one of the new units.
568 The Linux Cookbook, 2nd Edition
In this example, the output indicates that there are about 1.7636981 ounces
in 50 grams, and that conversely, one ounce is about 0.56699046 times 50
grams.
The units tool understands a great many different kinds of units—from
Celsius and Fahrenheit to pounds, hectares, the speed of light, and a “baker’s
dozen.” All understood units are kept in a text file database; use the -V option
to output the location of this database on your system, and then peruse or
search through it to see which units your version supports.
⇒ To determine the location of the units database, type:
$ units -V RET
units version 1.55 with readline, units database in
/usr/share/misc/units.dat
$
METHOD #1
Use tr to encode some text in rot13, giving as arguments the set containing
the first 13 letters, in both uppercase and lowercase, and then as the second
set, the last 13 letters in both uppercase and lowercase.
⇒ Here are some ways to use this.
• To encode the contents of the file script in rot13, and output it to
the file secret.script, type:
$ tr [a-mn-zA-MN-Z] [n-za-mN-ZA-M] < script > secret.script RET
• To type some text and encode it in rot13, type:
METHOD #2
Bsd-games
DEB: bsdgames
RPM: bsd-games
WWW: http://www.ibiblio.org/pub/Linux/games/
Use the rot13 filter to encode text in rot13. It works in the same way as
tr, described previously.
Chapter 29: Mathematics 571
$ rot13 RET
Hello, world. RET
Uryyb, jbeyq.
CTRL- D
• To encode the current text selection in rot13, type:
$ rot13 RET
SHIFT- INS RET
This is a secret message. RET
Guvf vf n frperg zrffntr.
CTRL- D
NOTES: To insert the text selection with the mouse, press the middle mouse
button instead of SHIFT- INS.
METHOD #1
Use the same tr filter method to decode text encoded in rot13 that you
would use to encode in rot13.
⇒ Here are some ways to use this.
• To decode the rot13-encoded text in secret_message, sending the
decoded text to the standard output, type:
$ tr [a-mn-zA-MN-Z] [n-za-mN-ZA-M] < secret_message RET
• To decode the rot13-encoded text in secret.script, writing the
decoded text to a file named script, type:
$ tr [a-mn-zA-MN-Z] [n-za-mN-ZA-M] < secret.script > script RET
572 The Linux Cookbook, 2nd Edition
METHOD #2
Bsd-games
DEB: bsdgames
RPM: bsd-games
WWW: http://www.ibiblio.org/pub/Linux/games/
$ rot13 RET
SHIFT- INS RET
Guvf vf n frperg zrffntr. RET
This is a secret message.
CTRL- D
gnu Privacy Guard (gpg) is a public key encryption system. It is a free and
open replacement for pgp, “Pretty Good Privacy,”2 and is mostly compatible
with newer pgp versions.
Public key encryption works like this. Everyone who uses it first runs
the program in such a way as to get his own set of keys, which are strings of
numbers generated by a particular mathematical function built into the public
key encryption system. Two keys are made: a public key, which you make
public to anyone you want to send your encrypted data to, and a private key,
which only you have access to. Both are unique series of data, and they are
generated by a passphrase that you type when making the keys.
When the public key is processed by the gpg tool, it will output a unique
function and encode its input data in such a way that it cannot be decrypted,
except when gpg is called with the private key. People who use gpg make
their public keys available, so that anyone else who uses gpg can encrypt
some data for a particular person by using that person’s public key. Once
encrypted, nobody but the recipient—not even the sender—can decrypt the
data. Only by using the private key corresponding to a particular public key
can the text be decrypted.
So to begin using gpg, you must first generate your own set of keys. Do
this by running gpg with the special --gen-key option.
⇒ To generate your own set of keys, type:
$ gpg --gen-key RET
When you run this command, you will be asked to specify some things:
the algorithm used (dsa/ElGamal is recommended), the key length (longer
keys give more security at the expense of taking longer to compute; many
recommend no fewer than 2,048 bits, while an older standard is 1,024 bits),
some names and email addresses of individuals you would like to exchange
encrypted data with (you can always add more later), and finally a special
passphrase. This passphrase is what turns your private key in the encryption
lock: You will use it every time you wish to unlock anything encrypted for
you with your public key.
The passphrase ought to be at least 32 characters long, varied in its char-
acters (using numerals, symbols, and both uppercase and lowercase letters),
and it should be something that nobody else will be able to guess.
2
pgp, popularized in the early 1990s Internet rush, uses patented algorithms and thus
cannot be free software; gpg carries no such restrictions.
574 The Linux Cookbook, 2nd Edition
The keys will take some time to generate. To make your key available for
others, export it to an ascii file with both the -a and --export options.
⇒ To export your public key to a file named alice.key, type:
$ gpg -a --export > alice.key RET
You can make this data available to anyone you’d like to communicate with
via gpg—you can send it to someone via email, put it on a Web site, and so
on.
To begin to communicate securely with someone else via gpg, you will also
need to import his public key. Do this by using gpg with the --import option,
and giving as an argument a file containing his public key.
⇒ To import the public key for your friend Bill, which you have put in the
file bill.key, type:
$ gpg --import bill.key RET
This command puts your friend Bill on your keyring, which is the list of
recipients that gpg knows about and can encrypt for. Use the --list-keys
option to list the people on your keyring.
⇒ To list the keys gpg knows about, type:
$ gpg --list-keys RET
The gnuplot tool is a versatile program that can be used for data visualization,
making 2d and 3d graphs, and for plotting contours, surfaces, and functions.
It takes input in the form of a set of commands, either in a file or typed at the
gnuplot command prompt, and it outputs a plot for those commands. It can
read data from external text files and either display output in a new window
or write it to a PostScript file. Output styles are highly configurable.
This is a large program with many features that we won’t get into; the
following recipes will demonstrate a few ways to use gnuplot to plot simple
graphs. For more information on using gnuplot to plot data, consult its Info
documentation (see Recipe 2.8.5 [Reading an Info Manual], page 48).
interactively after running gnuplot, or they may be written to a file and called
as an argument.
For example, suppose you have a file temperature.data containing two
columns of text, delimited by tab characters, as in Figure 29-2.
January 68.9
February 68.7
March 69.0
April 70.2
May 72.0
June 73.4
July 74.3
August 75.8
September 74.6
October 73.8
November 71.8
December 70.1
Figure 29-2. The temperature.data file.
as month data for the graph’s x axis, and the second column as the data to
plot along the y axis, using the linespoints style.
⇒ To process the commands in temperature.gnuplot, type:
$ gnuplot temperature.gnuplot RET
This command starts gnuplot and runs the commands in the file
temperature.gnuplot. A new PostScript file, temps.ps, is written, which
looks like Figure 29-4. (While the printed illustration is in black and white,
the actual image created from this command has a red plot.)
This is very similar to the command file in the previous example, except
for the following differences: The title is changed; the command to turn off
the key is not printed; the name of the output file differs; and in the long
last plot line, columns two through three are each plotted against the first
column (the month names) in the input file, each with the linespoints style
as before, but each with its own label for the key.
⇒ To process the commands in temperature2.gnuplot, type:
$ gnuplot temperature.gnuplot RET
This command starts gnuplot and runs the commands in the file
temperature2.gnuplot. A new PostScript file, temps2.ps, is written, which
looks like Figure 29-7. (While the printed illustration is in black and white,
the actual image created from this command has colored plots.)
30. Amusements
NOTES: In the deb package, a list of original authors for all of the included
programs is at usr/share/doc/bsdgames/AUTHORS.
This command passes the contents of the file /etc/motd to the kraut filter,
whose output is then sent to standard output. The contents of /etc/motd are
not changed.
NOTES: Some of the dialect filters available include nyc, which gives a “New
Yawker” dialect to text, and newspeak, which translates what is really said
Chapter 30: Amusements 587
into the approved, politically correct language of the thought police, as de-
scribed in George Orwell’s novel, 1984. War Is Peace! Freedom Is Slavery!
Some sample text and the way it appears through the various filters is kept
in the file /usr/share/doc/filters/SAMPLES.
While all of the given filters are humorous, it is possible to write your own
filters to change patterns of text in its input for some serious purpose, such
as filtering text for a publication’s “house style.”
In this example, “9” was output indicating that the user typed nine words
(in a real typing test, you want to type for longer than that—at least a few
hundred words to get an accurate count). The dates listed before and after
the typing show that it took the user six seconds to type these nine words.
Use bc or any other calculator to divide the number of words by the time
in minutes (or seconds) it took to type them.
NOTES: You can test your typing in Emacs by running the time function
before and after your typing; then select the text that was typed and send it
to wc to get the number of words.
METHOD #1
Fortune
DEB: fortune-mod
fortune-min
RPM: fortune-mod
WWW: http://www.ibiblio.org/pub/Linux/games/amusements/fortune/
NOTES: This venerable program has been on unix systems for a long time,
and several types of specialized fortune databases are available. You can even
make your own fortune files, containing quotations of your own choosing—
these are made with the strfile command.
METHOD #2
In Emacs, you can get random quotations from Zippy the Pinhead, the comic
strip character. When you run the yow function, a Zippy quote is written to
the minibuffer.
⇒ To get a line from Zippy, type:
ALT- X yow RET
To limit the anagrams that are output to those containing a given string,
specify that string with the -c option.
⇒ To output only anagrams of the phrase “lakes and oceans” that contain
the string “seas,” type:
$ an -c seas 'lakes and oceans' RET
To print all of the words that can be made with some or all of the letters
in a given word or phrase, use the -w option. This outputs words that are not
anagrams, because anagrams must contain all of the letters of the other word
or phrase.
⇒ To output all of the words that can be made from the letters of the word
“seas,” type:
$ an -w seas RET
This command outputs all of the words that can be formed from all or
some of the characters in “seas,” including “see” and “as.”
NOTES: There are other tools for finding anagrams, but this one is the best.
Unfortunately, it isn’t widely available outside of the Debian distribution; if
you can’t locate a copy, you can always install the sources from the Debian
package (see Recipe 1.1.2 [Preparation of Recipes], page 3).
METHOD #1
To output all lines in a file that are palindromes, use this simple perl one-
liner, and substitute the name of the file to check for file:
perl -lne 'map { print if $_ eq reverse } split' file
590 The Linux Cookbook, 2nd Edition
This outputs all lines in file that are palindromes. To check for palindromes
in the standard input, specify - as the file name to check. This is useful at
the end of a pipeline.
⇒ To output all of the palindromes in the system dictionary, type:
$ perl -lne 'print if $_ eq reverse' /usr/dict/words RET
METHOD #2
To output all lines in a file that are palindromes, regardless of whitespace,
punctuation, and case, use the following one-liner instead of the one given in
Method #1:
perl -lne '{ $_ = lc; $_ =~ s/\W//g; $_ = reverse; print if $_ eq
reverse }' file
This outputs all lines in file that are palindromes (all whitespace and punc-
tuation will be removed, and all letters will be converted to lowercase).
⇒ To output all of the lines in the file riddles that are palindromes regard-
less of whitespace, punctuation, and case, type (all on one line):
$ perl -lne '{ $_ = lc; $_ =~ s/\W//g; $_ = reverse; print if $_
eq reverse }' riddles RET
METHOD #1
One method for finding crossword puzzle words is to peruse the system
dictionary file, /usr/dict/words, for words you are looking for. Use less
with the -p option to begin perusing at a certain point—such as a letter or a
word prefix.
⇒ Here are two ways to use this.
• To peruse the system dictionary, beginning at the first match for the
pattern “dog,” type:
$ less -pdog /usr/dict/words RET
• To peruse the system dictionary, starting at the word “cat,” type:
$ less -p"^cat" /usr/dict/words RET
In the last example, the system dictionary will load and begin at the word
“cat,” and that string will be highlighted in the text.
Chapter 30: Amusements 591
You can also use look to output all words that begin with a given string
(see Recipe 11.2.1 [Listing Words That Match a Pattern], page 283).
⇒ To list all words that begin with “anti,” type:
$ look anti RET
METHOD #2
Another method you can try for finding crossword puzzle words is grep the
dictionary for the pattern you need—if you know a word is so many characters
long, or has characters in certain positions, you can search for all words that
fit the pattern. Use the -i option to do a case-insensitive search.
⇒ Here are some ways to use this.
• To output all words in the system dictionary that are four characters
long, begin with the letter “z,” and end with an “a,” regardless of
case, type:
$ grep -i ’^z..a$’ /usr/dict/words RET
• To output all words in the system dictionary that are six characters
long, have the letter “e” in the second position, and have either an
“s” or an “o” in the fourth position, type:
$ grep -i '^.e.[so]..$' /usr/dict/words RET
NOTES: These methods are also good for Scrabble and other word games.
On some systems, /usr/share/dict/words is where the the system dic-
tionary is kept.
#!/bin/sh
count=`wc -l < $1`
half=`expr $count / 2`
middle=`awk ' if (length($0) > max) max = length($0)
END OFMT = "%.0f"
print max / 2' $1`
end=`expr $middle + 1`
head -$half $1|cut -b0-$middle > $1.1
tail -$half $1|cut -b0-$middle > $1.3
head -$half $1|cut -b$end-80 > $1.2
tail -$half $1|cut -b$end-80 > $1.4
paste -d "" $1.4 $1.3
paste -d "" $1.2 $1.1
rm $1.1 $1.2 $1.3 $1.4
Figure 30-1. The cutup file.
This script takes the name of a file as input and cuts it both horizontally
and vertically along the middle, rearranges the four sections to their diagonally
opposite corners, and then writes that cut-up to the standard output. The
original file is not modified.
⇒ To make a cut-up from a file called nova, type:
$ cutup nova RET
⇒ To output random text based on the text in the file nova, type:
$ dadadodo nova RET
This command will output passages of random text based on the text in
the file nova until it is interrupted by the user.
You can analyze a text and save the analysis to a file of compiled data; this
analysis can then be used to generate random text when the original input
text is not present. The following table describes this and other dadadodo
options.
VII. NETWORKING
596 The Linux Cookbook, 2nd Edition
Chapter 31: Communications 597
31. Communications
You will almost certainly want to go online or otherwise communicate with
other computer systems. Most systems today are sold with the necessary
hardware to connect to other systems, such as a modem or a network card.
You connect this hardware to the outside world via a telephone line or network
connection.
This chapter includes recipes for connecting your Linux system to the In-
ternet with an isp, using fax services, and making serial connections with a
modem.
For more information on this subject, see The Linux Network Administra-
tor’s Guide [http://metalab.unc.edu/mdw/LDP/nag/nag.html].
There are several ways to connect a Linux box1 to the Internet. Digital
Subscriber Line (dsl) service, cable modems, and dial-up connections with
isdn or analog modems are currently the most popular methods. Each of
these services has its own hardware and software requirements. Generally, you
get these services by subscribing to them from an Internet Service Provider,
or isp.
For up-to-date, detailed instructions for using these services on Linux-based
systems, the relevant howtos published by the Linux Documentation Project
[http://xtldp.org/] remain the definitive guides (see Recipe 2.8.6 [Reading
System Documentation and Help Files], page 50):
The following recipes show how to set up and use a ppp (“Point-to-Point
Protocol”) dial-up connection, long the de facto means of connecting a com-
puter to the Internet over a dial-up line.
ABORT BUSY
ABORT "NO CARRIER"
ABORT VOICE
ABORT "NO DIALTONE"
"" "\p\p+++\p\p"
"" "at"
"" "at"
OK "ath0"
"" atdt5551010,,
ost ppp
ogin smith
word \qsecret\q
Figure 31-1. A sample /etc/chatscripts/provider file.
In Figure 31-1, after eight lines of modem initialization strings, the modem
is instructed to dial the isp dial-up number, 555-1010. Some systems need one
or two commas after the number to signify pauses for the modem; only do
this if you can’t get a good connection with just the telephone number in this
space.
Next come the lines which show the prompts your isp is expected to send,
and the strings to give in response to them. Traditionally, only partial strings
are shown to match the prompts, in part because case for the various prompts
differs between systems. This is why the file has “ost,” “ogin,” and “word,”
Chapter 31: Communications 599
and not “host:,” “login:,” and “Password:,” which are typically the full
prompts you might expect.
The “host:” prompt is optional, and is used by some isps whose connection
line contains a choice of services from which you must make a selection before
entering your username and password (some isps offer slip and shell access
along with the standard ppp, for example). Customize this and the following
lines as instructed by your isp. If your isp does not have a “host” prompt,
then remove this line.
In this example, the username smith is sent as a response to the “login:”
prompt, and then the password of “secret” is sent for a password. The
password appears between two “\q” strings in this file, which—for security
purposes—instruct ppp to display question mark characters (?) instead of the
actual password in system log files or other places where an intruder might
see it.
Next, edit the file /etc/ppp/peers/provider so that it looks like Figure
31-2.
search .
nameserver nameserver address 1
nameserver nameserver address 2
Figure 31-3. The /etc/resolv.conf file.
2
On some newer ppp implementations, each of these words are not all on a single line,
but are each given on a line of their own.
600 The Linux Cookbook, 2nd Edition
For the two nameserver address values, use the ip address of the nameserver
machines, as given to you by your isp. The second is optional—most isps have
more than one designated nameserver as a backup in the event that the first
system becomes unavailable.
Make sure that your user account has membership to the dialout group;
otherwise, the superuser account will have to start and stop ppp, which is not
recommended (see Recipe A.6.3 [Letting Users Access Hardware Peripherals],
page 718).
Once you’ve done these things, you should be able to start and stop ppp
connections to the Internet. Complete documentation for setting up ppp is in
the /usr/share/doc/ppp directory.
NOTES: To make ppp automatically start when the system first boots, rename
the file /etc/ppp/no_ppp_on_boot to /etc/ppp/ppp_on_boot. (You must be
root, the superuser, to do this.)
If you ever accidentally run pon when a ppp connection is already estab-
lished (it happens), poff will not work as expected because there are multiple
ppp connections running. Use the -a option to stop all ppp connections.
⇒ To stop all ppp connections, type:
$ poff -a RET
Chapter 31: Communications 601
NOTES: You need to be a member of the adm group in order to view the log
file (see Recipe A.6.3 [Letting Users Access Hardware Peripherals], page 718).
31.2 Faxing
Efax
DEB: efax
RPM: efax
WWW: http://www.cce.com/efax/
If you have a Class 1 or 2 fax modem, you can send and receive fax (“fac-
simile”) messages with your Linux system. The following recipes show how
to do this with the efax package, which is designed for single user systems or
relatively simple fax configurations (more complicated tools for faxing exist,
but they are beyond the scope of this book).
To set up efax for faxing, edit the file /etc/efax.rc (you must be root to
do this). The important things to specify in this file are the value for “DEV,”
which is the device name in /dev of the fax or modem device (this should
almost always be “modem”), and the values for “FROM” and “NAME”—the fax
number and organization name to appear on outgoing faxes.
NOTES: Unless you have membership to the dialout group, you must ask
your system administrator for access to the modem hardware before you
can use it (see Recipe A.6.3 [Letting Users Access Hardware Peripherals],
page 718).
More information on faxing is contained in the Fax Server mini-HOWTO
(see Recipe 2.8.6 [Reading System Documentation and Help Files], page 50).
you must convert them to tiffg3 format first—see Recipe 31.2.4 [Converting
to and from Fax Format], page 604.
Use the -d option to specify the full path name of the fax device (usually
/dev/modem if you are using the modem connected to your system), and use
the -t option followed by a telephone number to specify the number to send
the fax to. To specify dtmf tone dialing, precede the phone number with
a “T”; specify pauses in the dialing sequence with a comma character (,)—
particularly useful for dialing out from a pbx or office phone system.
⇒ To fax a copy of the file resume.txt to the number 555-9099, using dtmf
tone dialing, type:
$ efax -d /dev/modem -t T555-9099 resume.txt RET
To send more than one file, specify them as arguments in the order they
are to be sent. You can also specify them with a wildcard character, but be
careful—they are sent in the order in which the shell expands the file names,
which is alphabetical order. If you have a lot of files that should be sent in
a particular order, rename them so their file names begin with the number
of the page they correspond to. But be sure to number them with the same
number of digits for each file—for example, if you have 11 files to fax, don’t
name them 1.fax, 2.fax, and so on, to 10.fax and 11.fax, because the shell
will expand them in the order of 1.fax, 10.fax, 11.fax, 2.fax, 3.fax, and
so on up to 9.fax. In this case, you would number them as 01.fax, 02.fax,
and so on, so that files 1 through 9 contain the same number of digits in their
names as do 10.fax and 11.fax.
⇒ To fax all of the files with the .fax extension in the current directory to
the number 555-9099, using dtmf tone dialing, type:
$ efax -d /dev/modem -t T555-9099 *.fax RET
Another way to do this is to make a text file containing the list of files
to fax, one file name per line, in the order you want them sent. If the files
you want to send are not in the current directory, be sure to write the file
names with path names relative to the current directory—so for example, if
you want to send the file header.fax, which is in your home directory, and
the current directory is ~/documents/faxes, the file should be specified as
~/header.fax.
⇒ To fax all of the files listed in the file fax.list to the number 555-9099,
dialing a 9 first to obtain an outside line, and using dtmf tone dialing,
type:
$ efax -d /dev/modem -t T9,555-9099 $(cat fax.list) RET
This command starts efax and sets up the modem to wait for an incoming
fax. After a fax is received, efax exits. You can stop efax before it receives a
fax by typing CTRL- C or by killing the efax job (see Recipe 3.3.5 [Stopping
a Job], page 73).
When a fax is received, it is written to a file in the current directory whose
base name consists of the current numeric date and a session number generated
by efax; each page is written to a separate file whose three-digit file extension
is the page number. The received fax files are in tiff Group 3 fax format; use
display to view them (see Recipe 17.1 [Viewing an Image in X], page 407), or
convert them to PostScript or another format for printing (see Recipe 31.2.4
[Converting to and from Fax Format], page 604).
This command uses all of the default settings for the efax package, which
you can configure. Old spool files are deleted and any recieved faxes are mailed
to you.
If you need to set more switches on efax and don’t wish to type this every
time you want to set up the fax machine, you can write a shell script to do more
and save it in a file called faxon, as in Figure 31-4. Put it in your personal bin
directory (see Recipe C.1 [Using a Directory for Personal Binaries], page 727).
Each time a fax is received and then saved, efax restarts, waiting for another
fax. A session log is written to the file faxlog in your home directory.
#!/bin/sh
while :
do
trap break 2;
efax -d /dev/modem -kZ -w -iS0=1 2>&1 >> ~/faxlog;
done
Figure 31-4. The faxon file.
Should an incoming facsimile message arrive, efax will receive it and write
the message in files in the current directory, with a file name convention as
described previously; then efax restarts, ready to receive another fax. Type
CTRL- C to stop the script and exit efax.
METHOD #1
Use efix to convert (or “fix”) files for faxing; it will convert a file you want
to fax to the tiffg3 format. You can also use it to convert received fax files
to another format that you can view or print. The efix tool writes to the
standard output, but you can redirect its output to a file to save it.
To convert a file for faxing, type efix followed by the name of the file to
convert, and redirect standard output to the file you want to contain your fax
image. efix can read plain text, pbm, and tiff files.
⇒ To convert the file chart.pbm for faxing, type:
$ efix -i pbm chart.pbm > chart.fax RET
This command converts a copy of the file chart.pbm to the tiffg3 fax
format, writing it to a file called chart.fax. The original pbm file is not
altered.
METHOD #2
To convert a received fax file to a PostScript file that you can then pre-
view (see Recipe 17.4.2 [Previewing a PostScript File], page 414) or print (see
Recipe 25.1.1 [Sending a Print Job to the Printer], page 510), use efix with
the -o ps option.
⇒ To convert 19990325.001, a received fax file, to a PostScript file, type:
$ efix -o ps 19990325.001 > received.ps RET
This command converts the fax file into PostScript, and writes the output
to a file called received.ps. The original fax file is not altered.
METHOD #3
Ghostscript
DEB: gs-common gs
RPM: ghostscript
WWW: http://www.cs.wisc.edu/~ghost/
To convert a PostScript file to fax format, use gs and specify “tiffg3” as the
output device to write to.
606 The Linux Cookbook, 2nd Edition
⇒ To convert the PostScript file resume.ps to fax format, type (all on one
line):
$ gs -q -sDEVICE=tiffg3 -dSAFER -dNOPAUSE
-sOutputFile=resume.fax resume.ps < /dev/null RET
This command writes a copy of the file resume.ps to the file resume.fax
in tiffg3 format, which you can then send as a fax. The original PostScript
file is not altered.
NOTES: For more on using gs, see Recipe 25.3.1 [Preparing a PostScript File
for Printing], page 518.
METHOD #4
teTeX
DEB: tetex-base
tetex-bin
tetex-doc
tetex-extra
RPM: tetex
WWW: http://www.tug.org/teTeX/
Use dvi2fax to convert a dvi file made from TEX into ‘tiffg3’ format for
faxing.
It takes as options either ‘-hi’ for high resolution, outputting at 204x196
dpi (the default), or ‘-lo’ for low resolution, outputting at 204x98 dpi.
Give as an argument the name of the dvi file to convert; giving the ‘.dvi’
extension is optional.
⇒ To convert the file ‘proposal.let.dvi’ to low resolution fax-format files,
type:
$ dvi2fax -lo proposal.let RET
Each page of input is written to its own file, numbered in order and with
a ‘.fax’ extension.
Use Minicom to dial out with the modem and connect with another system,
such as when you want to connect to a bbs (“Bulletin Board System”). It’s
a serial communications tool for X or the console; it resembles some of the
communications tools of the dos world, such as Telix and Procomm.
Type minicom to run Minicom. When Minicom starts, you will be given a
connection screen, which looks like Figure 31-5.
Figure 31-5. The minicom connection screen.
The bottom line contains a status bar showing a message describing how to
get help, the current modem settings (in this case, 57,600 bps, 8 data bits, no
parity, one stop bit), whether or not cursor keys work (the mysterious “NOR”
message), the version of the program (“1.82”), the kind of terminal emulation
currently set (“VT102”), and whether or not an online connection is currently
established.
To get a help menu, type CTRL- A z while in the connection screen; from
the help menu, you can press P to set the communications parameters, T to
set the terminal settings, O to configure minicom, or D to enter the dialing
directory.
To dial a number from the connection screen, type ATDT followed by the
number to dial.
608 The Linux Cookbook, 2nd Edition
When you type RET, Minicom will begin dialing the number; type any key
to interrupt the dialing and hang up the line. Once connected, type CTRL- A
h to hang up the line, or type CTRL- A x to hang up the line and exit the
program.
NOTES: Minicom isn’t really a way to connect your system to the Internet;
to do that, you normally start a ppp connection, as described earlier in this
chapter.3
3
Technically, you can use Minicom to dial a computer that is connected to the Internet,
like a local Free-Net system, but your access to the net will be restricted within this
Minicom window; with a traditional Internet connection such as ppp, your whole system
has direct access to the net, including your Web browsers, email software, and other
networking tools.
Chapter 31: Communications 609
32. Email
1
Everyone outside of the unix world probably calls one of these an “email app” or email
program.
2
On many Linux systems, Mail is a synonymous name for this tool. And on some unix
systems such as aix, the name of the tool is mailx; Linux provides that name as an
additional synonym.
612 The Linux Cookbook, 2nd Edition
The text you type on the Subject: line is displayed as the subject of your
email message, and the lines of text you type after that are the body text
of the message. Various styles for sending email exist; some mimic paper
correspondence, with a salutation, closing, and signature, whole others give
just a signature, and still others omit all three. Email isn’t always for proper
letters; sometimes it isn’t elevated beyond the telegram or memo pad, used
only for the rapid transmission of brief informal messages.
Various commands available when composing email are described in
Recipe 32.1.5 [Composing a Mail], page 616.
Type CTRL- D on a line alone to end the message. Then, mail prompts
for Cc: addresses—a “carbon copy” of the email message is sent to any ad-
dresses you give here, if any. Separate multiple addresses with commas, or
just type RET if there are none.
When you type, mail just reads the standard input like any other com-
mand line tool, so there’s little direct editing capability in this basic email
service—use CTRL- U to erase the current line, and CTRL- C CTRL- C
(that is, CTRL- C pressed twice) to cancel your input and abort the message
altogether.
That’s it! No bells, no whistles—but no time-wasting excess, either.
Chapter 32: Email 613
This command sends an email message to the user mrs on the local system.
The email message itself is empty, but the subject is a short note asking
whether user mrs will be attending a party.
NOTES: Besides being good for sending mail to users that you might share
your system with, mail is useful for sending yourself mail, as a way to give
yourself a reminder at your terminal (see Recipe 27.6.2 [Sending Yourself
Email Reminders], page 550).
3
Technically, you still are giving the email address, since email addresses take the form
of username@hostname; when hostname is omitted, the localhost is assumed.
614 The Linux Cookbook, 2nd Edition
METHOD #1
To send a directory of files with a mua, you can put a copy of the directory
in an archive (see Recipe 8.5 [Managing File Archives], page 199), gzip the
archives, and then mail that compressed archive file as an attachment. This
is how it’s normally done.
METHOD #2
GNU Shar Utilities
DEB: sharutils
RPM: sharutils
WWW: http://www.gnu.org/software/sharutils/sharutils.html
You can also create a long pipeline to send the directory through the mail:
Put a copy of the directory in a compressed archive with tar, and pipe the
output of tar to uuencode, which encodes binary files into ascii text that
can be transmitted over mail in a plaintext message. Then, pipe that encoded
text to mail.
⇒ To mail a copy of the ~/proj/latest directory tree to
[email protected], type (all on one line):
$ tar -czf - ~/proj/latest | uuencode latest.tar.gz |
mail -s "Here is the latest" [email protected] RET
METHOD #1
Lynx
DEB: lynx
RPM: lynx
WWW: http://lynx.browser.org/
To send a Web page as an annotated text file, pipe the output of the Lynx
Web browser with the -dump option to mail (see Recipe 33.2 [Using Lynx],
page 643). Since the output is plain text, you don’t have to encode it before
you mail it.
⇒ Here are two ways to use this.
• To send a mail to the address [email protected] with the contents
of http://gutenberg.net/etext98/rmnis10.txt, type (all on one
line):
$ lynx -dump http://gutenberg.net/etext98/rmnis10.txt | mail
[email protected] RET
• To send a mail to the address [email protected] with the con-
tents of http://gutenberg.net/etext98/rmnis10.txt and with a
subject of “Some Reminiscences,” type (all on one line):
$ lynx -dump http://gutenberg.net/etext98/rmnis10.txt |
mail -s "Some Reminiscences" [email protected] RET
METHOD #2
Wget
DEB: wget
RPM: wget
WWW: http://www.gnu.org/software/wget/wget.html
To send the html source of a Web page, use wget to retrieve the source, using
the -q option to suppress messages and sending to the standard output by
giving “-” as an argument to the -O option; pipe this to mail (see Recipe 33.5
[Getting Files from the Web], page 653).
⇒ Here are two ways to use this.
• To send a mail to the address [email protected] with the contents
of http://gutenberg.net/etext98/, type (all on one line):
$ wget -q -O - http://gutenberg.net/etext98/ |
mail [email protected] RET
616 The Linux Cookbook, 2nd Edition
CTRL- C CTRL- C Abort the current message and exit mail without
sending it.
CTRL- U Erase the current line and move the cursor to the
beginning of the line.
There are also a few special commands that you may use while composing
the body of the message. They’re known as tilde escapes because you specify
them by typing a tilde character (~).
The following table lists some of these commands and describes their func-
tions.
$ mail RET
Mail version 8.1 6/6/93. Type ? for help.
"/var/spool/mail/m": 3 messages 3 new
>N 1 mrs Mon Sep 6 17:29 13/345 "Re: A modest proposal"
N 2 Ray Tue Sep 7 04:20 15/694 "Latest news"
N 3 lisa@example Tue Sep 7 09:35 19/869 "Re: Hello"
&
In this example, the user has three messages waiting—one from mrs, one
from Ray, and one from [email protected].
The mail prompt is an ampersand character (&); from there, you can read,
delete, reply to, and save messages.
When you type RET at the “&” prompt, mail outputs the next unread
message to the screen. You can also type a number to output that message.
⇒ Here are two ways to use this.
• To read the next unread message in mail, type:
& RET
• To read message number three in mail, type:
& 3 RET
There are two ways to exit mail: Type q to exit mail and apply the
deletion commands you have given, if any, to your inbox; type x to exit mail
and revert the state of your inbox to how it was before you ran mail.
⇒ To exit mail and revert your inbox to its state before you started mail,
type:
& x RET
You can always get help by typing ? at the prompt; it gives a list of available
mail commands. The following recipes describe some of them.
NOTES: By default, only you (and, as always, the superuser) have access to
read your inbox. While there are tools available (such as mail, and the other
muas) to read this file in special ways, you can also view this file like any
other text file (see Chapter 9 [Viewing Text], page 211).
You can specify a range of messages or the particular message number to start
with; give - or + to display the previous or next 18 messages, respectively.
⇒ Here are some ways to use this.
• To list the headers of 18 messages, beginning with the current mes-
sage, type:
& headers RET
• To list the headers of the next 18 messages, type:
& h + RET
• To list the headers of messages 101 through 200, type:
& h 101-200 RET
NOTES: This command only works for messages marked for deletion in the
current mail session. Once you exit mail, any mail marked for deletion is
permanently removed and cannot be undeleted.
620 The Linux Cookbook, 2nd Edition
When you reply to a mail, use the keyboard commands for composing your
message as described in Recipe 32.1.5 [Composing Mail], page 616.
Rather than use a Web browser to read mail, if you’d like to run a mua
(including the mail tool) and use it to read Internet email, then you will want
to run fetchmail. It fetches your mail from your isp’s pop server, and puts it
where it belongs in your local mail spool directory, right in your inbox. Then
you can read your mail from a local mua.
Configuration is done via .fetchmailrc, a hidden file in your home di-
rectory. Then you just need to set up fetchmail so that it runs, with the
proper options, whenever your Internet connection is started, and that it stops
running whenever your Internet connection is stopped. (With ppp, this is fa-
cilitated by placing shell scripts in the /etc/ppp/ip-up.d and /etc/ppp/ip-
down.d directories.)
You can use fetchmailconf, bundled in a separate package, to help con-
figure your setup as described above.
⇒ To configure fetchmail, type:
$ fetchmailconf RET
METHOD #1
You can view your mail folders in less or edit them in a text editor, although
the folder will appear as one long scroll containing all of the messages the
folder contains.
⇒ To view the mail folder ~/Mail/rachel in less, type:
$ less ~/Mail/rachel RET
METHOD #2
You can view a mail folder in mail by specifying it as an argument to the -f
option; it will appear the way your inbox would appear when running mail
with no options.
⇒ To view the mail folder ~/Mail/rachel in mail, type:
$ mail -f ~/Mail/rachel RET
METHOD #3
Elm
RPM: elm
WWW: http://www.instinct.org/elm/
You can view a mail folder in elm (see Recipe 32.7 [Using Other Mail User
Agents], page 631) by giving its name as an argument to the -f option. As
with mail, the folder will appear the usual way your inbox appears in elm.
⇒ To view the mail folder ~/Mail/rachel in elm, type:
$ elm -f ~/Mail/rachel RET
If you save your mail messages in a lot of separate folders, you can view a
sorted list of all messages from all files by using cat in conjunction with elm.
Concatenate all the folders into one with cat, and then view that file in elm
as you would view any folder.
⇒ To view the contents of all of the email folders in your ~/Mail directory,
type:
$ cat ~/Mail/* > allmessages RET
$ elm -f allmessages RET
NOTES: To view a list showing who all the messages in a folder are from, use
frm; see Recipe 32.4.4 [Seeing Who Your Mail Is From], page 626.
The biff tool notifies you when new mail arrives by printing the header and
first few lines of a mail message.
To turn biff on, use y as an option. To turn biff off, so that you stop
being notified when new mail arrives, use n as an option. Unlike most tools,
biff options don’t take a hyphen.
⇒ To turn biff on, type:
$ biff y RET
Some people put the preceding line in their .bashrc file so that biff
is always set on in all of their shells (see Recipe 3.5.6 [Changing the Shell
Prompt], page 80).
Typing biff alone with no options will tell you whether biff is set to y
or n.
⇒ To see what biff is set to, type:
$ biff RET
A companion tool, xbiff, works only in the X Window System (you can
use the regular biff in X, too).
When you start xbiff, it draws a window containing a mailbox that looks
like Figure 32-1. When mail arrives, xbiff rings the system bell, the window
icon reverses color, and the mailbox flag goes up, as in Figure 32-25
NOTES: The original version of biff was named after a dog. In the early
1980s at a uc Berkeley computer lab, a girl would bring her dog, Biff, in
with her when she went to use the computers. Biff was known for barking at
the mailman whenever he came to deliver the day’s mail. Biff was also very
popular with all of the bsd unix hackers at Berkeley, and when one of them
5
Noah Friedman has an alternate set of “Spam” images you can use, available from
http://www.splode.com/~friedman/software/packages/index.html.
Chapter 32: Email 625
wrote a mail notification tool, he thought of Biff and the mailman—hence the
name. (Biff, the dog, died in August 1993.)
Use the messages tool, distributed with Elm,6 to count the number of mail
messages in a folder or file. Give the name of a mail folder as an argument;
with no arguments, it counts the mail you have waiting in your inbox.
6
On Debian systems, messages comes with the gnu Mailutils package.
626 The Linux Cookbook, 2nd Edition
METHOD #1
Elm
DEB: mailutils
RPM: elm
WWW: http://www.instinct.org/elm/
Use frm, distributed with Elm,7 to output a list of sender names and subjects
for your mail. Give the name of a mail folder as an option; with no options,
frm reads your inbox.
⇒ Here are two ways to use this.
• To output a list showing sender names and subjects of your incoming
mail, type:
$ frm RET
• To output a list showing sender names and subjects of the mail in
the file ~/email/saved, type:
$ frm ~/email/saved RET
METHOD #2
The from tool works in similar fashion to frm, but it does not output subject
lines; instead, it outputs the names of senders and the time that messages
were received.
7
On Debian systems, from comes with the gnu Mailutils package.
Chapter 32: Email 627
Use vrfy to determine whether or not a given email address works. This is
useful when you are unsure of whether or not you have the right email address
for someone. If the address works, vrfy outputs a message indicating that
the recipient exists; if the address is not valid, vrfy outputs a message saying
that the user is unknown.
⇒ To verify that the email address [email protected] is valid, type:
$ vrfy [email protected] RET
Use the -f option to specify a text file containing email addresses; vrfy
attempts to verify all email addresses contained in the file.
⇒ To verify all of the email addresses contained in the file net-legends-faq,
type:
$ vrfy -f net-legends-faq RET
NOTES: vrfy relies on the remote system to get this information; in these
days of the heavily corporatized Internet, an increasing number of sites no
longer supply this kind of information to the general public. However, it’s
still useful enough to be worth mentioning.
METHOD #1
To search the text of a mail archive, use grep in the usual way (see Chapter 14
[Searching Text], page 333).
628 The Linux Cookbook, 2nd Edition
METHOD #2
Use a text viewer or editor to peruse mail archives and search for text, as
described in Chapter 9 [Viewing Text], page 211, and Chapter 10 [Editing
Text], page 231.
A good way to search through mail archives is by subject; the less tool is
particularly useful because search terms are highlighted.
⇒ To highlight all of the subject lines in the current file you are perusing in
less, and move the cursor to the next one, type:
/^Subject:.* RET
METHOD #1
Metamail
DEB: metamail
RPM: metamail
WWW: http://bmrc.berkeley.edu/~trey/emacs/metamail.html
To read a mail attachment, write the message to a file and then run metamail
Chapter 32: Email 629
with the file name as an argument. metamail lists each attachment and
prompts you to decide whether it should display the attachment, write it to
a file, or skip it.
To read a mail attachment, type:
$ mail RET
Mail version 8.1 6/6/93. Type ? for help.
"/var/spool/mail/m": 1 messages 1 new
>N 1 Photo Dept. Mon Feb 12 14:37 231/10980 "New Images"
& w1 image.mail RET
"image.mail" [New file]
& x RET
$ metamail image.mail RET
In this example, the mail tool was used to open the inbox and write the
message to a file called image.mail; then, metamail was run with the file
name as an argument.
METHOD #2
Nmh
DEB: nmh
RPM: nmh
WWW: http://www.nongnu.org/nmh/
Use mhshow to view the contents of an email message with mime attachments.
Give the name of the file containing the message as an argument to the -
file option. This command shows first the headers of the mail, and then
all remaining parts of the message in turn. For any portion that cannot be
displayed on the screen, you will be given an option to write it to a file.
⇒ To view the contents of the multipart mail message stored in the file
~/Mail/inbox/1, type:
$ mhshow -file ~/Mail/inbox/1 RET
To send a file as an email attachment, use metasend. It prompts for the values
to use in the To:, Subject:, and CC: header fields, plus the following for each
mime attachment: its Content-type:, which describes the kind of data the
attachment contains; the file name; and the type of encoding to use, if any
(usually one is recommended).
⇒ To mail the jpeg file dream.jpeg in the current directory to the address
[email protected], type:
$ metasend RET
To: [email protected] RET
Subject: The image you requested RET
CC: RET
Content-type: image/jpeg RET
Name of file containing image/gif data: dream.jpeg RET
Do you want to encode this data for sending through the mail?
1 -- No, it is already in 7 bit ASCII
2 -- Yes, encode in base64 (most efficient)
3 -- Yes, encode in quoted-printable (less efficient, more readable)
4 -- Yes, encode it using uuencode (not standard, being phased out)
2 RET
Do you want to include another file too (y/n) [n] ? n RET
Delivering mail, please wait... Mail delivery apparently succeeded.
$
The following table lists values to use in the mime Content-type: field for
various kinds of files.
A signature file (often pronounced “dot sig,” and written as .sig) is a text
file containing text that you want to appear at the end of email messages and
other online postings. They are generally unfashionable now, but this will
explain how to use one anyway.
Sometimes, people put their name, email address, and a small quote, or a
piece of ascii art (such as text written in a figlet font—see Recipe 16.4.1
[Outputting Horizontal Text Fonts], page 401) in the file. Once the World
Wide Web became popular, many people started including the url of their
home page in their ‘.sig.’
You create your signature file in a text editor, just like any other text file.
Name the file ‘.signature’ or ‘.sig,’ and keep it in your home directory.
Be sure to keep your .sig at most four lines in length—to use any more
is considered very bad form. A first line consisting only of two hyphens and
a space character (-- ) is sometimes used; many applications recognize this
string as the beginning of a .sig when processing messages.
If you want to use more than one signature, use sigrot to “rotate” your
various signatures—every time you run sigrot, it selects one of the signature
files you keep in your .sigrot directory and writes it to .signature. To
change your .signature every time you log in, you would run sigrot in your
.bash_login file (see Chapter 3 [The Shell], page 53).
DEB: balsa
RPM: balsa
WWW: http://www.balsa.net/
Elm Menu-driven mua that was popular in the early 1990s
among experienced users—it has some interesting features,
including ways to send mail in batch mode to many ad-
dresses at once, and comes with a tool to send memoran-
dums as email messages. Interest in Elm has waned consid-
erably over the years, and most novices are advised to try
Mutt instead.
RPM: elm
WWW: http://www.instinct.org/elm/
Chapter 32: Email 633
DEB: gnus
RPM: gnus
WWW: http://gnus.org/
MEW Emacs mail and news facility developed in Japan, “Messag-
ing in the Emacs World” has many features for handling
mail in complex ways.
DEB: mew
RPM: mew
WWW: http://www.mew.org/
634 The Linux Cookbook, 2nd Edition
DEB: emacsen-common
RPM: emacs-21
WWW: http://www.emacs.org/
Mozilla Mail Familiar email interface of this popular Web browser. Works
in the X Window System and is favored by newbies.
DEB: mozilla-browser
RPM: mozilla
WWW: http://www.mozilla.org/
Chapter 32: Email 635
DEB: mutt
RPM: mutt
WWW: http://www.mutt.org/
Nmh Rand Mail Handling system, mh; not a single application for
mail, but a collection of small tools for manipulating mail
folders and messages, installed in /usr/bin/mh. It should
appeal to those who excel at building complex commands
from combinations of simple tools and operators. nmh is
the new “Mail Handling” system, containing rewrites and
improved versions of the mh tools. Most Linux systems will
install this over the old mh.
DEB: nmh
RPM: nmh
WWW: http://www.nongnu.org/nmh/
636 The Linux Cookbook, 2nd Edition
DEB: vm
RPM: vm
WWW: http://www.wonderworks.com/vm/
Wanderlust mua for Emacs designed to facilitate reading your mail on
multiple computers.
DEB: wl
RPM: wl
WWW: http://www.gohome.org/wl/
Chapter 33: The World Wide Web 637
1
Some people pronounce it as “earl,” while others insist that it can only be “yoo-are-ell.”
638 The Linux Cookbook, 2nd Edition
When most people think of browsing or surfing the Web, they think of doing
it graphically—and the mental image they conjure is usually that of the fa-
mous Netscape browser. Most Web sites today make heavy use of graphic im-
ages, and commercial Web sites are usually optimized for Netscape-compatible
browsers—many of them are not even accessible with other browsers. That
means you’ll want to use this application for browsing this kind of Web site.
The version of Netscape’s Navigator browser that was released as free,
open source software in 1998 to much fanfare is called Mozilla.2 It includes
a browser (Mozilla Navigator), mua and newsgroup reader (Mozilla Mail),
Web page editor (Mozilla Composer), and contact manager (Mozilla Address
Book). When first released, the Mozilla application was a “developer’s only”
release, but it has long reached a state where it is ready for general use.
The following recipes will help you get the most out of using Mozilla.
2
Netscape’s browsers, from its earliest Navigator release to its later Communicator series,
were always referred to internally at the company as Mozilla; this was a slangy pun on
the name Mosaic, which had been the first popular graphical Web browser in the early
1990s—Netscape’s goal had been to make a “Mosaic killer.”
3
This term is mine. Mozilla calls it a home page, but this is confusing because that term
chiefly refers to the main page of a person or organization’s published Web site.
Chapter 33: The World Wide Web 639
A typical Mozilla window looks like Figure 33-1, in which the home page
of the Library of Congress [http://www.loc.gov/] is loaded.
follow it, replacing the main contents of the browser window with the contents
of that link.
The right mouse button opens a special options menu, whose contents de-
pend on the context of the mouse pointer. If you right-click when the pointer
is on a link, you will be presented with several options for handling the link,
including opening it in a new window, bookmarking it, and displaying its
properties. If you right-click when the pointer is on an image, you will be pre-
sented with options for handling the image, including viewing it (the browser
display the image as its own “page”), saving it to a file, and bookmarking it.
If you right-click when the pointer is on whitespace, plain text, or somewhere
else on the page, you will be presented with options for handling the current
page, including bookmarking it, viewing its html source or page information,
reloading it, and saving it.
Navigation
ALT- Go back to the last url you visited
(continued)
Window Operations
CTRL- W Close current Mozilla window.
NOTES: These keys may not have the desired effect in some window managers;
if they don’t work for you, try using the CTRL key instead of the ALT key.
642 The Linux Cookbook, 2nd Edition
One nice feature for Emacs fans is that you can use Emacs-style keystrokes
for cursor movement in Mozilla’s dialog boxes (see Recipe 10.1.3 [Using Basic
Emacs Editing Keys], page 237).
METHOD #1
To open a link in a new Mozilla window, middle-click the link. Opening
multiple links in their own windows saves time when you are doing a lot of
“power browsing.”
METHOD #2
To open a new Mozilla window whose contents will be your Mozilla start page,
type CTRL- N.
As of this writing, the venerable Lynx is still the standard Web browser for use
on many Linux systems; it was also one of the first Web browsers available for
general use.4 It doesn’t display graphics, but it’s a good interface for reading
hypertext.
Type lynx to start it. If a start page is defined, it will load (see Recipe 33.7
[Setting Up a Start Page], page 658.
To open a url, give it as an argument.
⇒ To view the contents of the url http://www.whitehouse.gov/, type:
$ lynx http://www.whitehouse.gov/ RET
The following Lynx recipes include tips and hints for using Lynx in various
ways.
Navigation within a
Document
Move up (backward) through links in the current
document.
PgDn or CTRL- F or Scroll down (forward ) to the next screen in the cur-
SPACEBAR or + rent document.
(continued)
Information and Help
K Display a complete list of keystroke commands.
= Display information about the current document
(like all documents displayed in Lynx, type to
go back to the previous document).
\ Toggle between rendered html and source display
of current page.
Use the Print to local file option to save either the rendered content or
the html source file of a Web page in Lynx.
⇒ Here are two ways to use this.
• To save the rendered content of the Web page displayed in Lynx, do
the following:
1. Type P (the print option) to open the print options page.
2. Select Print to local file and press RET.
• To save the html source of the Web page displayed in Lynx, do the
following:
1. Type \ to view the source.
2. Type p to open the print options page.
3. Select Print to local file.
646 The Linux Cookbook, 2nd Edition
When you type this command, Lynx loads a new page containing a list of
all links (called references) contained in the page you were viewing. This list,
reminiscent of the old Internet Gopher service, is good for viewing the links
on pages that contain “hidden” links, such as some image links. It’s also good
for making an html annotated list of links that a page contains; do this by
saving the link page, as described in the previous recipe.
⇒ To print the pure text of the previous url in a Times Roman font, with
underscores translated into italics and a line width of 40 characters type
(all on one line):
$ lynx -dump -width=40 -nolist -underscore
http://sc.edu/fitzgerald/winterd/winter.html | enscript -B
-Eetext -f "Times-Roman12" RET
NOTES: To peruse the plain text of a url with its html tags removed and no
formatting done to the text, see Recipe 33.9.2 [Converting html], page 663.
You can also use the -dump option to print a Web page (see Recipe 25.2.4
[Printing a Web Page], page 514), or to pass some file from the Web to another
command, such as passing a wav audio file to the sox audio processing tool.
It’s common to combine this with the options for saving to a file, so that
you can retrieve an annotated text copy of a file from a site that normally
requires registration.
⇒ To save the url http://www.example.com/archive/ as an annotated
text file, mynews, type (all on one line):
$ lynx -dump -number_links -auth=guest:guest
http://www.example.com/archive/ > mynews RET
NOTES: The username and password argument you give on the command line
will be recorded in your shell history log (see Recipe 3.4 [Using Your Command
History], page 74), and it will be visible to other users on the system should
they look to see what processes you’re running (see Recipe 2.7.2 [Listing All
of a User’s Processes], page 42).
If you have friends who send you mail in html format that you cannot
conveniently read with your mua, this little-known tip will make you happy.
⇒ To view a selection of html source code as rendered text, do the following:
1. Select the source code to render by left-clicking and dragging the
mouse pointer over it (see Recipe 10.3 [Manipulating Selections of
Text], page 253).
2. Start Lynx in a terminal so that it reads from standard input:
$ lynx -stdin RET
3. Paste the text in the terminal that is running Lynx, by clicking the
middle mouse button in that terminal.
4. End the input to Lynx by typing CTRL- D in that terminal.
When you do this, Lynx will render and display the html code.
NOTES: Lynx will still be running after it displays the code, and you will
then have to type Q to quit and exit Lynx. Alternately, include the -dump
option to have Lynx display the rendered html to its standard output and
then immediately exit.
Whenever you have html code coming out of a stream, you can pipe it to
lynx -stdin -dump to display the rendered code to the standard output.
This technique is also good for testing out arbitrary selections of html
code.
⇒ To browse the files in the /usr/share/doc directory with lynx, using the
mouse, type:
$ lynx -use_mouse /usr/share/doc RET
You can get the Web in Emacs. Currently it’s quite slow, but it may have
its uses. To do this, use w3-mode. Its features are many—just about the
only things you may miss are ssl support (although this may be coming) and
JavaScript and Java support (well, you may not miss it, but it will make some
sites a bit hard to use). It can handle frames, tables, stylesheets, and many
other html features.
Figure 33-2. w3-mode in Emacs.
⇒ To load w3-mode in Emacs, type:
ALT- X w3 RET
To open a url in a new buffer, type CTRL- O and, in the minibuffer, give
the url to open (leaving this blank opens the w3-mode home page). Middle-
click a link to follow it, opening the url in a new buffer.
650 The Linux Cookbook, 2nd Edition
The last example opens the w3-mode home page in a buffer of its own, as
in Figure 33-2.
The following table describes some of the special commands for use when
in w3-mode.
ALT- TAB Insert the url of the current document into another
buffer.
METHOD #1
Lynx
DEB: lynx
RPM: lynx
WWW: http://lynx.browser.org/
You can view an image on the Web by giving the url of the image as an
argument to lynx (see Recipe 33.2 [Using Lynx], page 643). The image will
be displayed with whatever “helper” application is set up to show images via
lynx.
⇒ To view the image at the url ftp://garbo.uwasa.fi/garbo-
gifs/garbo01.gif, type:
$ lynx ftp://garbo.uwasa.fi/garbo-gifs/garbo01.gif RET
METHOD #2
ImageMagick
DEB: imagemagick
RPM: ImageMagick
WWW: http://www.imagemagick.org/
Libwww-perl
DEB: libwww-perl
RPM: perl-libwww
WWW: http://ftp.ics.uci.edu/pub/websoft/libwww-perl/
If you just want to view an image file from the Web, you don’t have to use a
Web browser at all—instead, you can use display, giving the url you want to
view as an argument. It uses GET (sometimes get), part of the libwww-perl
package, to fetch the url.
This method is especially nice for viewing your favorite webcam image, for
viewing images on ftp sites, or for putting in scripts—you don’t have to start
a browser, log in, or type any other commands at all.
Chapter 33: The World Wide Web 653
The -remote option opens the image in a display window that’s already
running; you can use this method to view an image that changes often—such
as a webcam image—and automatically refresh the display with the latest
image. To do this, first run display in the background, and then run watch
(see Recipe 28.4 [Watching a Command from Time to Time], page 559). Give
the number of seconds between reloads as an argument to the -n option,
and give display with the -remote option and the image url as a quoted
argument as the command to be watched.
⇒ To view the image at the url
http://waquarium.otted.hawaii.edu/coralcam/ccam.jpg, updating
it with the latest image from the webcam every 30 seconds, type:
Use wget, “Web get,” to download files from the World Wide Web. It can
retrieve files from http or ftp urls. It keeps the file’s original timestamp, it’s
654 The Linux Cookbook, 2nd Edition
smaller and faster to use than a browser, and it shows a visual display of the
download progress.
To retrieve an html file from the Web and save it as rendered text, use
Lynx instead—see Recipe 33.2.4 [Sending Text from the Web to Standard
Output], page 646.
The following subsections contain recipes for using wget to retrieve infor-
mation from the Web. For more examples of things you can do with wget,
consult its Info documentation (see Recipe 2.8.5 [Reading an Info Manual],
page 48).
NOTES: In order for the -c option to have the desired effect, you should run
wget from the same directory as it was run previously, where that partially-
retrieved file should still exist.
of how long it takes. Finally, use the -o option with a file name as an argument
to write a progress log to the file—examining it can be useful in the event
that something goes wrong during the archiving; once the archival process is
complete and you’ve determined that it was successful, you can delete the log
file.
⇒ To mirror the Web site at http://www.example.org/, giving up to three
retries for retrieving files and putting error messages in a log file called
mirror.log, type:
$ wget -m -t3 http://www.example.org/ -o mirror.log RET
Use the -A option to specify the exact file name extensions to accept—
for example, use -A txt,text,tex to only download files whose names end
with .txt, .text, and .tex extensions. The -R option works similarly, but
specifies the file extensions to reject and not download.
⇒ To download only the files ending in a .gz extension and only in the given
directory /~jim/papers/ at example.org, type (all on one line):
$ wget -m -r -l1 --no-parent -A.gz
http://www.example.org/~jim/papers/ RET
This command writes the server response headers to standard output and
saves the contents of http://google.com/ to a file in the current directory
whose name is the same as the original file.
Many Web browsers have a “history” function that keeps a listing of the sites
you visit, and the time and date of your visit, but none are as good as the
browser-history tool. If you presently keep a weblog (or “blog”) in order to
remember good links you find, you won’t have to do that anymore, once you
install this tool.
Use browser-history to maintain a history log of all the Web sites you
visit.
Chapter 33: The World Wide Web 657
You start it in the background, and each time you visit a url in a Web
browser (as of this writing, it works with the Netscape, Arena, and Amaya
browsers, but not Mozilla), it writes the name and url to its current history
log, which you can view at any time.
⇒ To start browser-history every time you start X, put the following line
in your .xsession file:
browser-history &
Past history logs have the year, month, and week appended to their file
name, and they are compressed (see Recipe 8.4 [Using File Compression],
page 196). If you are viewing them in a browser, you should just be able
to give the file name as an argument without uncompressing them—most
browsers handle this automagically.
NOTES: If you have a start page, you’ll find it useful to add a link on it to
your current history log file, ‘~/.browser-history/history-log.html’ (see
Recipe 33.7 [Setting Up a Start Page], on the next page).
This command searches all your logs from the year 2000 for the text
“Confessions” in it, and outputs those lines.
658 The Linux Cookbook, 2nd Edition
NOTES: For more about zgrep, see Recipe 14.7.2 [Matching Lines in Com-
pressed Files], page 349.
METHOD #1
Mozilla
DEB: mozilla-browser
RPM: mozilla
WWW: http://www.mozilla.org/
To define a start page in Mozilla, define the Home Page in the Mozilla
Preferences... menu.
⇒ To change the default start page in Mozilla to your own start page at
http://localhost/start/, do the following:
1. Choose Preferences... from the Edit menu on the menu bar.
2. Left-click in the Location box.
3. Replace its contents with the start page you want:
http://localhost/start
4. Left-click the OK button.
NOTES: In Mozilla, the start page loads whenever you start it with no argu-
ments, click on the Home button, or type ALT- HOME.
Chapter 33: The World Wide Web 659
METHOD #2
Lynx
DEB: lynx
RPM: lynx
WWW: http://lynx.browser.org/
NOTES: Linux distributions often predefine the Lynx start page to the home
page of the distribution. On Debian systems, for example, the start file comes
defined as the Debian home page [http://www.debian.org/].
METHOD #1
To output a list of urls in text, one per line, use grep with the -o option,6
and give as an argument the regular expression to match urls. To search a
text file, give the name of the file as the second argument.
⇒ Here are some ways to use this.
• To output a list of all the urls contained in the file /etc/lynx.cfg,
type (all on one line):
$ grep -o
'\(\(\(http\(s\)\?\|ftp\|gopher\|telnet\|news\):\/\/\|mailto:\).[^
SPACEBAR ,; CTRL- V TAB<">]*[^ SPACEBAR
.,; CTRL- V TAB<">]\)' /etc/lynx.cfg RET
• To output a list of all the urls contained in the text of the url
http://news.example.com/, type (all on one line):
$ lynx -dump -nolist http://news.example.com/ | grep -o
'\(\(\(http\(s\)\?\|ftp\|gopher\|telnet\|news\):\/\/\|mailto:\).[^
SPACEBAR ,; CTRL- V TAB<">]*[^ SPACEBAR
.,; CTRL- V TAB<">]\)' RET
• To output a list of the urls contained in the html source file of
http://news.example.com/, type (all on one line):
$ wget -q -O - http://news.example.com/ | grep -o
'\(\(\(http\(s\)\?\|ftp\|gopher\|telnet\|news\):\/\/\|mailto:\).[^
SPACEBAR ,; CTRL- V TAB<">]*[^ SPACEBAR
.,; CTRL- V TAB<">]\)' RET
METHOD #2
To output a list of urls in text, one per line, use sed with the following
command line. To search a text file, give the name of the file as an argument.
⇒ Here are some ways to use this.
• To output a list of all the urls contained in the file /etc/lynx.cfg,
type (all on one line):
$ sed -n
's/.*\(\(\(http\(s\)\?\|ftp\|gopher\|telnet\|news\):\/\/\|
mailto:\).[^ SPACEBAR ,; CTRL- V TAB<">]*[^
SPACEBAR .,; CTRL- V TAB<">]\).*/\1/p' /etc/lynx.cfg RET
6
Available in gnu grep version 2.5 and newer.
Chapter 33: The World Wide Web 661
• To output a list of all the urls contained in the text of the url
http://news.example.com/, type (all on one line):
$ lynx -dump -nolist http://news.example.com/ | sed -n
's/.*\(\(\(http\(s\)\?\|ftp\|gopher\|telnet\|news\):\/\/\|
mailto:\).[^ SPACEBAR ,; CTRL- V TAB<">]*[^
SPACEBAR .,; CTRL- V TAB<">]\).*/\1/p' RET
METHOD #1
Mozilla
DEB: mozilla-browser
RPM: mozilla
WWW: http://www.mozilla.org/
Use Mozilla Composer to write html. It is one of the most popular wysiwyg
html editors. You can launch Composer while in Mozilla by selecting it from
the Window menu or by typing CTRL- 4.
662 The Linux Cookbook, 2nd Edition
METHOD #2
Bluefish
DEB: bluefish
RPM: bluefish
WWW: http://bluefish.openoffice.nl/
METHOD #3
GNU Emacs
DEB: emacsen-common
emacs21
RPM: emacs
WWW: http://www.emacs.org/
Emacs (see Recipe 10.1 [Using Emacs], page 232) has a major mode to facili-
tate the editing of html files called html-mode.
⇒ To start html-mode in a buffer, type:
ALT- X html-mode RET
NOTES: When you’re editing an html file in an Emacs buffer, you can open
the same file in a Web browser in another window—Web browsers only read
Chapter 33: The World Wide Web 663
and don’t write the html files they open, so you can view the rendered doc-
ument in the browser as you create it in Emacs. When you make and save a
change in the Emacs buffer, reload the file in the browser to see your changes
take effect immediately.
For usability, html image source tags should have HEIGHT and WIDTH pa-
rameters, which specify the dimensions of the image the tag describes. By
specifying these parameters in all the image tags on a page, the text in that
page will display in the browser window before the images are loaded. Without
them, the browser must load all the images before any of the text on the page
is displayed.
Use imgsizer to automatically determine the proper values and insert
them into an html file. Give the name of the html file to fix as an argument.
⇒ To add HEIGHT and WIDTH parameters to the file index.html, type:
$ imgsizer index.html RET
METHOD #1
Unhtml
DEB: unhtml
WWW: http://linux.maruhn.com/sec/unhtml.html
To simply remove the html formatting from text, use unhtml. It reads from
the standard input (or a specified file name), and it writes its output to
standard output.
664 The Linux Cookbook, 2nd Edition
NOTES: When you remove the html tags from a file with unhtml, no further
formatting is done to the text. Furthermore, it only works on files, and not
on urls themselves.
METHOD #2
Lynx
DEB: lynx
RPM: lynx
WWW: http://lynx.browser.org/
Use lynx to save an html file or a url as a formatted text file, so that
the resultant text looks like the original html when viewed in lynx. It can
also preserve italics and hyperlink information in the original html. See
Recipe 33.2.4 [Sending Text from the Web to Standard Output], page 646.
One thing you can do with this lynx output is pipe it to tools for spacing
text, and then send that to enscript for setting in a font. This is useful
for printing a Web page in typescript “manuscript” form, with images and
graphics removed and text set double-spaced in a Courier font.
⇒ To print a copy of the url http://example.com/essay/ in typescript
manuscript form, type (all on one line):
$ lynx -dump -underscore -nolist http://example.com/essay/ | pr -d
| enscript -B RET
NOTES: In some cases, you might want to edit the file before you print it,
such as when a Web page contains text navigation bars or other text that
you’d want to remove before you turn it into a manuscript. In such a case,
you’d pipe the lynx output to a file, edit the file, and then use pr on the file
and pipe that output to enscript for printing.
Chapter 33: The World Wide Web 665
METHOD #3
Html2ps
DEB: html2ps
RPM: html2ps
WWW: http://www.tdb.uu.se/~jan/html2ps.html
Use html2ps to convert an html file to PostScript; this is useful when you
want to print a Web page with all its graphics and images, or when you want
to convert all or part of a Web site into pdf. Give the urls or file names
of the html files to convert as options. Use the -u option to underline the
anchor text of hypertext links; specify a file name to write to as an argument
to the -o option. The defaults are to not underline links and to write to the
standard output.
⇒ Here are two ways to use this.
• To print a PostScript copy of the document at the url
http://example.com/essay/ to the default printer, type:
$ html2ps http://example.com/essay/ | lpr RET
• To write a copy of the document at the url
http://example.com/essay/ to a PostScript file submission.ps
with all hypertext links underlined, type:
$ html2ps -u -o submission.ps http://example.com/essay/ RET
Use weblint to validate the basic structure and syntax of an html file. Give
the name of the file to be checked as an argument, and weblint outputs any
complaints it has about the file to standard output, such as whether or not IMG
elements are missing ALT descriptions, or whether nested elements overlap.
⇒ To validate the html in the file index.html, type:
$ weblint index.html RET
666 The Linux Cookbook, 2nd Edition
METHOD #1
Analog
DEB: analog
RPM: analog
WWW: http://www.analog.cx/
The most popular tool in use for analyzing Web logs is analog, which produces
a comprehensive set of reports, including the following:
• The top words people used in search engines to find your site.
• The referrers, which are pages with links that the requesting computers
followed to get to your pages.
• The top organizations of the computers that requested your pages.
• The operating systems of the computers that requested your pages.
• The most popular directories on your site.
• The most popular files on your site.
Give the filespec for the log files to analyze as an argument to analog.
This command reads the log file you give and it outputs the reports to the
standard output. Output is in html format; either pipe it to the standard
input of a Web browser to view it or redirect it to a file to save it. Log files
have to be in a log format that analog can recognize, such as the format used
by the popular Apache Web server; they can also be compressed.
⇒ Here are some ways to use this.
• To view an analysis of ~/web/logs/2005/www.20050408.gz, a Web
log file, type:
$ analog ~/web/logs/2005/www.20050408.gz | lynx -stdin RET
Chapter 33: The World Wide Web 667
METHOD #2
You can also grep your log files. If the log files follow a standard format, you
can use cut to cut out fields you are not interested in, thus outputting the
desired fields. This is useful in doing things like finding the number of unique
domains that have visited a certain directory or page of yours, which you pass
to cut via grep.
⇒ To list the number of unique domains that have visited your reviews
page, based on your logs in the ~/private_html/logs/2006 directory,
type (all on one line):
$ grep reviews ~/private_html/logs/2006/* | cut -f2 -d':' |
cut -f1 -d' ' | sort -u | wc -l RET
NOTES: If any of the log files are compressed, use zgrep or use grep with
the -z option.
login:
To disconnect from the system, follow the normal procedures for logging
out from the system you are connected to (for how to do that on a Linux
system, see Recipe 2.2.2 [Logging Out of the System], page 31).
⇒ To disconnect from a remote Linux system, type:
$ CTRL- D
Connection closed.
In the preceding example, the first shell prompt was on the remote system,
and the second prompt was on the local system; coincidentally, the prompts
were the default on both systems—a dollar sign ($).
Once you are connected to a remote system with telnet, everything you
type in the terminal is sent to the remote system until you are disconnected
from that system. It is sometimes useful to temporarily escape back to the
local shell on your local system, and you can do that by typing the escape
character, which is a key sequence that is interpreted by telnet before it
reaches the remote system. The default escape character is the sequence
CTRL- [ .
When you type that, you are brought to the telnet command prompt,
where you can do a number of useful things, including temporarily suspend the
connection or terminate the connection entirely—both of which are described
in the following recipes.
faraway-system$ CTRL- [
telnet> z RET
[2]+ Stopped telnet
$
To return to the remote system, bring the telnet job back into the fore-
ground (see Recipe 3.3.3 [Putting a Job in the Foreground], page 73).
Chapter 34: Other Internet Services 673
$ fg RET
faraway-system$
In the two preceding examples, the shell prompt of the remote system is
“faraway-system$.” (You don’t have to type the escape character at a shell
prompt, though; you can type it regardless of what program is running on the
remote system.)
faraway-system$ CTRL- [
telnet> q RET
Connection closed.
$
Once connected and logged in, use the cd and ls commands to change
directories and to list files on the remote system.
It is standard practice for public systems to have a /pub directory on their
ftp host that contains all the files and goodies available to the general public.
⇒ To change to the /pub directory on the remote system and look at the
files that are there, type:
The current directory of the local system is, by default, the directory where
you ran the ftp command. To change directories on your local system, use
lcd; it works just like the cd command, but it changes the local directory.
⇒ To change to the parent directory of the current directory on the local
system, type:
NOTES: The mget command works like get but allows wildcards; as with
mput, you will be prompted to verify each file unless you use the prompt
command first to turn this off.
places—the Net is not the safe haven it was a decade ago, and in practice, few
sites allow telnet access anymore.
The following recipes describe how to use the openssh implementation of
the famous ssh (“Secure Shell”) protocol. openssh includes the contemporary
replacements for older rlogin, rsh, and rcp secure-connection tools.
NOTES: The first time you use one of these tools to connect with a remote
system, you may get a message telling you that the “host key” was not found
in the list of known hosts, and asking whether or not to continue with the
connection—answer “yes.”
Welcome to arctic.example.org!
[ernie@arctic ~]
In this example, the username ernie made a ssh connection to the system
arctic.example.org, on which his password is “snowshoe.” The “~ $” is the
shell prompt on that system, where he can run commands until he exits by
either running the exit command or by typing CTRL- D at a shell prompt.
If your username on the remote system differs from your username on your
local system, use the -l option to specify a different username.
678 The Linux Cookbook, 2nd Edition
Welcome to arctic.example.org!
$ scp local_html/index.html
arctic.example.com:public_html/index.html RET
[email protected]'s password: snowshoe RET
index.html 100% |*****************************| 2365 00:00
$
In this example, the user has a username of ernie on both systems; the
progress of the copy is displayed on the screen before scp exits.
Use the -r option to copy an entire directory tree.
Chapter 34: Other Internet Services 679
In the last example, the user’s local username on arctic differed from his
username on scout.
NOTES: Use the -v option for a verbose display; this will display information
about the file transfer process as it happens.
Newsgroups are named and organized by hierarchies, which can have any
number of branches. Each branch is delineated by a period character (.); for
example, the comp.os.linux newsgroup is part of the comp.os branch of the
comp hierarchy.
The following table lists the “Big Eight” Usenet hierarchies and gives ex-
amples of some newsgroups in each one.
comp Computing
news:comp.os.linux.advocacy,
news:comp.text.tex
humanities Humanities
news:humanities.music.composers.wagner
misc Miscellaneous
news:misc.consumers.frugal-living
news Newsgroups relating to Usenet itself
news.newusers.questions
rec Recreation
news:rec.music.marketplace.vinyl,
news:rec.food.cooking
sci Science
news:sci.math, news:sci.cognitive
soc Social groups and cultures
news:soc.culture.usa,
news:soc.college
talk Talk and chit-chat
news:talk.environment,
news:talk.politics.guns
There are many other hierarchies, but these eight are technically the only
newsgroups considered to be part of Usenet proper. While netnews is the term
for the collection of all newsgroups including those in Usenet, these terms are
often used interchangeably.
The “alternative” hierarchy, alt, is perhaps the most popular hierarchy
of all—just about every subject you might want to discuss (and a good deal
that you probably wouldn’t) has an appropriate newsgroup here. It even has
a place for non sequiturs.
Chapter 34: Other Internet Services 681
There are also hierarchies for topics concerning certain geographical ar-
eas: For example, the cmh. hierarchy is for topics pertaining to the greater
Columbus, Ohio metropolitan area; seattle is for the city of Seattle, Wash-
ington. So, while cmh.forsale pertains to items posted for sale in the greater
Columbus area, seattle.forsale is for items posted for sale in and around
Seattle. Hierarchies can exist also for certain organizations; for example, the
gnu hierarchy is for newsgroups concerning the gnu Project, and bit is for
newsgroup redistributions of the popular Bitnet listserv mailing lists.
The following recipes describe tools for reading and posting articles to
netnews.
Gnus Very powerful and feature-full newsreader for use in Emacs; can be
used to read mail, too.
DEB: gnus
RPM: gnus
WWW: http://gnus.org/
Knews Graphical newsreader for use in X whose features include the display
of article threads in a graphical tree and options for reading news
over slow connections.
DEB: knews
RPM: knews
WWW: http://www.matematik.su.se/~kjj/
Mozilla Newsreader built into the Mozilla browser (historically, commercial
News Web browsers had mail and newsreaders built into them, and that
capability remains in the Mozilla browser.)
DEB: mozilla-browser
RPM: mozilla
WWW: http://mozilla.org/
682 The Linux Cookbook, 2nd Edition
NN Older (and very popular) newsreader that was designed for reading
the most news in the minimal amount of time; its motto is “No
News is good news, but nn is better.”
DEB: nn
RPM: nn
WWW: http://www.nndev.org/
PAN gnome newsreader designed for speed and is meant to be easy for
beginners.
DEB: pan
RPM: pan
WWW: http://pan.rebelbase.com/
News Suite of small tools for use in X that facilitates the reading and com-
Peruser posing of news articles when you’re offline, by downloading batches
of news when your system is online.
DEB: peruser
WWW: http://ibiblio.org/pub/Linux/system/news/readers/
SLRN Optimized for use over slow connections (like home dial-up connec-
tions). Based on rn, one of the oldest newsreaders.
DEB: slrn
RPM: slrn
WWW: http://www.slrn.org/
Use nngrep to find newsgroup names that match a pattern. This is useful for
finding groups on a particular topic.
⇒ To output a list of all newsgroups that match the pattern “society,”
type:
$ nngrep society RET
To get a listing of all users who are currently logged in to a given system, use
finger and specify the name (or numeric ip address) of the system, preceded
with an at sign (@).
This gives a listing of all the users who are currently logged in on that
system. It doesn’t give out each person’s .plans, but the output includes how
long each user has been idle, where he is connected from, and (sometimes)
what command he is running. (The particular information that is output
depends on the operating system and configuration of the remote system.)
⇒ To output the users who are currently logged in to the system
ap.example.org, type:
In this example, the host bfi.org was pinged and a total of three pings
were sent and received before the user typed CTRL- C to interrupt it. As
long as these ping lines are output, you know that the other machine is
connected to the Internet (or at least to the same network that your localhost
is connected to).
You really don’t need to analyze the information on each line of a ping
message—the only useful information is the number at the end of the line,
which tells you how many milliseconds it took to go out to the Internet, touch
or “ping” that host, and come back.4 The quicker the better—pings that are
four or five digits long (or greater) mean a slow connection between the two
machines. When you interrupt the ping, some statistics are output, including
the minimum, average, and maximum number of milliseconds it took to ping
4
“I named it after the sound that a sonar makes, inspired by the whole principle of
echo-location,” said the original author of ping, Mike Muss. He died in an automobile
accident in November 2000.
686 The Linux Cookbook, 2nd Edition
the given host. In the previous example, the high was 190 and the low was
159.9 milliseconds, with an average of 170.1 milliseconds to make the trip.
NOTES: If your own system is not online, ping will report that either the
network is unreachable or that the host isn’t found.
METHOD #1
To get the ip address of a host, ping the host in question; this will output the
ip address of the host in parentheses (see Recipe 34.6.1 [Determining Whether
a Host is Online], page 685).
METHOD #2
Use host to get the ip address of the host whose name you give as an argument.
⇒ To get the ip address of linart.net, type:
$ host linart.net RET
NOTES: Depending on how the remote host is set up, this method may not
work.
Chapter 34: Other Internet Services 687
METHOD #3
Use dig, the “domain information groper” tool, to get the ip address of a
host. Give a hostname as an argument to output information about that
host, including its ip address, in a section labeled ANSWER SECTION.
⇒ To find the ip address of the host linart.net, type:
METHOD #1
Use host to get the hostname of the system whose ip address you give as an
argument.
⇒ To get the hostname of 127.0.0.1, type:
$ host 127.0.0.1 RET
NOTES: Depending on how the remote host is set up, this method may not
work.
METHOD #2
To find the hostname for a given ip address, use dig with the -x option.
Give an ip address as an argument to output information about that address,
including its hostname in a section labeled ANSWER SECTION.
688 The Linux Cookbook, 2nd Edition
In this example, dig output that the fqdn corresponding to the given ip
address was metalab.unc.edu.
NOTES: This command also outputs the names of the nameservers that han-
dle the given domain—this is useful to get an idea of where a particular Web
site is hosted.
METHOD #1
Use write to write a message to the terminal of another user. Give the
username you want to write to as an argument. This command writes the
message you give, preceded with a header line indicating that the following is
a message from you, and giving the current system time. It also rings the bell
on the user’s terminal.
⇒ To send the message “Wake up!” to the terminal where user sleepy is
logged in, type:
The other user can reply to you by running write and giving your username
as an argument. Traditionally, a user ended a write message with -o, which
indicated that what he was saying was “over” and that it was now the other
person’s turn to talk. When a user believed that a conversation was completed,
he would end a line with “oo,” meaning that he was “over and out.”
METHOD #2
A similar command, wall, writes a text message to all other users on the local
system. It takes a text file as an argument and outputs the contents of that
file; with no argument, it outputs what you type until you type CTRL- D on
a line by itself. It precedes the message with the text “Broadcast message
from username” (where username is your username) followed by the current
system time, and it rings the bell on all terminals it broadcasts to.
⇒ Here are two ways to use this.
• To output the contents of /etc/motd to all logged-in terminals, type:
$ wall /etc/motd RET
690 The Linux Cookbook, 2nd Edition
• To output the text “Who wants to go out for Chinese food?” to all
logged-in terminals, type:
$ wall RET
Who wants to go out for Chinese food? RET
CTRL- D
$ mesg RET
is n
$
In the preceding example, mesg indicated that messages are currently dis-
allowed to be written to your terminal.
Use talk to interactively chat in realtime with another user. Give the user-
name (or email address) of the user you want to chat with as an argument;
a message will be sent to that user’s terminal, indicating that a connection
Chapter 34: Other Internet Services 691
is requested. If that person then runs talk, giving your username as an ar-
gument, you will both be connected in a talk session—the screen will clear,
and then what you type will appear on the top of the screen; what the other
user types will appear at the bottom of the screen.
⇒ To request a chat with the user [email protected], type:
$ talk [email protected] RET
Figure 34-1. Beginning a talk session.
You can then type, and what you type will appear on both your screen
and that user’s screen; that user, in turn, can also type—even while you are
typing—and what that user types appears on the other half of both screens,
as in Figure 34-2.
692 The Linux Cookbook, 2nd Edition
Figure 34-2. A talk session in progress.
It is convention to indicate that you are done saying something by typing
RET RET, thus bringing the cursor down past a blank line on your half of
the screen. Some users, once they have typed down to the bottom of their
part of the screen during the course of the conversation, type RET repeatedly
to “clear” their half of the screen, thus bringing the cursor back to the top of
a blank half.
Type CTRL- C to end a talk session.
When you type, both users see the characters appear in realtime; my first
demonstration of the interactive nature of the Internet, back in 1991, was
when I had a live, real-time chat with a user in Australia, on the other side of
the globe from me—the magic felt that day still remains whenever I run this
command!
NOTES: A similar command, ytalk, allows simultaneous connection between
multiple users, and it contains other features as well; it is generally considered
to be the superior successor of talk, but it is not yet available or standard on
all unix-based systems.
There are several irc networks, each with its own servers and tens of
thousands of users; to “go on” irc, you use an irc client program to connect
with an irc server. Like cb radio, irc networks have channels, usually based
on a particular topic, which you join to chat with other users in that channel
(you can also send private messages to other users).
The following table lists some of the irc clients available for Linux.
other users in realtime. Since then, many free software chat tools have been
written that use the icq protocol.
One nice feature of icq is that you can maintain a “buddy list” of email
addresses, and when you have an icq client running, it will tell you whether
or not any of your buddies are online. But unlike talk, you can’t watch the
other user type in realtime—messages are displayed in the other user’s icq
client only when you send them.
The following table lists some of the free software icq clients currently
available.
aol’s Instant Messenger (aim) is similar to write, made to work over the
Internet—it sends a message to the terminal of a user, and with the “buddy
list” feature, it tells you whether or not your friends are online. Initially, aim
and similar services had proprietary formats, but now there are various free
software tools to use with aim (though you still must register with aol’s aim
site to use them), and there other new im services too.
The following table describes some of the various im tools now available
for Linux.
Chapter 34: Other Internet Services 695
APPENDICES
698 The Linux Cookbook, 2nd Edition
Appendix A: Administrative Issues 699
has a proprietary interface that only works with a certain non-free operating
system.
To find out whether your hardware will work under Linux, try the following:
1. Read the Linux Hardware Compatibility HOWTO (see Recipe 2.8.6
[Reading System Documentation and Help Files], page 50), an up-to-date
list of hardware that is compatible with Linux.
2. Search for it on the two sites that provide reviews and information about
hardware that works with Linux, http://www.linuxhardware.net/ and
http://www.linuxhardware.org/.
3. Search the Internet—particularly Usenet news and the linux.com site—
for information on the hardware you intend to buy. Read any trouble
reports people may have written about getting it to work with Linux, so
that you won’t be writing the next one about it.
METHOD #1
Use date with the -s option to set the system date. Give as an argument
the time and date to use—the system date is set to this date the moment the
command is run. Quote long-format dates.
⇒ Here are two ways to use this.
• To set the system date to noon on March 4, 1994, type:
# date -s "Mar 4 12:00 1994" RET
• To set the system date to 4:15 p.m., type:
# date -s 16:15 RET
In the second example above, the day, month, and year are not set, and
remain at the value they had before this command was run.
METHOD #2
Use one of the following tools to set the system date and time to that given
by remote hosts on the Internet. This is good for keeping your time adjusted
with various public time servers, such as the ones run by the United States
Navy.
Appendix A: Administrative Issues 701
NOTES: Use caution with this command. If you erase the mbr on a disk that
you rely on for booting, you won’t be able to boot with it until you write a
new, bootable image on that mbr.
Appendix A: Administrative Issues 703
You can follow the now argument with a quoted message that will be dis-
played on all terminals of all users currently logged in.
⇒ To immediately shut down and halt the system, and send a warning
message to all users, type:
# shutdown -h now "The system is being shut down now!" RET
To shut down the system in a certain number of minutes, give that number
of minutes prefaced by a plus sign (+).
⇒ To shut down and halt the system in five minutes, type:
# shutdown -h +5 RET
This command cancels any pending system shutdown and displays the mes-
sage, “Sorry, I hit the wrong key!” on all the terminals of anyone logged
in.
NOTES: If the shutdown process has advanced to the point where all terminals
are stopped, you won’t be able to run this command.
This command will put you in a root shell on the console, where you can
run e2fsck or do whatever it is you intended to do. In the example, the root
user has the simple password of “abracadabra.”
To exit the shell, type CTRL- D; depending on what you did, you may
wish to reboot again with CTRL- ALT- DEL.
your system, and then make is run with either install or all as an argument,
depending on what the package’s particular documentation instructs.
⇒ To compile and install a software package from its source directory, you
generally type:
# ./configure RET
... configuration messages ...
# make install RET
... compilation messages ...
... installation messages ...
#
When you install source packages on your system, you are said to be in-
stalling local software—the files are kept in the /usr/local directory tree.
Binaries are placed in /usr/local/bin, libraries in /usr/local/lib, man
pages in /usr/local/man, and documentation in either /usr/local/doc or
/usr/local/share/doc.
Recipe 7.5 [Finding Where a Program Is Located], page 185). For example, if
perl is located on your system at /usr/bin/perl, you will have to edit the
first line in this script so that it matches that actual location.
If you try to execute this script, and the system reports an error finding
the file, you’ll have to change that first line to correspond to the location of
the perl binary on your system. The which tool will output this location.
⇒ To find out where perl is installed on your system, type:
# which perl RET
NOTES: If the output of the which command returns nothing, that means
that the perl program is not installed on your system at all; in that case, you
should install the perl software in order to run the script.
deb is the native package format on Debian systems. These packages are
available on the Web from http://packages.debian.org/.
There are a number of tools available for deb package management. Tra-
ditionally, dselect, where you select packages from a menu, was the tool for
installing and removing software from the system. Its interface is unique, it
so requires study. Proper usage is, unfortunately, an acquired skill.3 Admin-
istrators who are installing a new system are urged to run through dselect
and reboot at least a few times, so that all essential packages and their de-
pendencies are installed.
The dpkg tool is Debian’s primary command line package manager tool
(in fact, dselect is just a front-end interface to it), and it can be used on
3
Even its man page makes note of this: “The dselect package selection interface is con-
fusing or even alarming to the new user.”
710 The Linux Cookbook, 2nd Edition
its own at the command line. This is what will be described in the following
recipes. Methods using the newer apt-get tool, part of Debian’s “Advanced
Package Tool” system, will also be described; apt-get is preferred by most
experienced users.
NOTES: All of the following actions can also be done with the dselect ap-
plication, but that method will not be described.
To list a particular package, give its name. To search for a pattern among
installed packages, pipe the output of dpkg -l to grep.
⇒ Here are two ways to use this.
• To determine whether or not the gimp package is installed, type:
# dpkg -l gimp RET
• To list all installed deb packages with “gimp” in their names, type:
# dpkg -l | grep gimp RET
METHOD #1
To install a deb package with dpkg, give the name of the package file to install
as an argument with the -i option.
⇒ To install the deb file gimp1.2_1.2.3-2_i386.deb, type:
# dpkg -i gimp1.2_1.2.3-2_i386.deb RET
METHOD #2
To obtain and install a package with apt-get, use the install option and
give the base name of the package as an argument.
Make sure your Debian distribution is ready when you run this command.
If you are installing from cd-rom, put the first Debian cd-rom disc in your
cd drive; if installing via Internet, make sure that your system is online.
⇒ To obtain and install the proper file for the hello deb package, type:
# apt-get install hello RET
NOTES: Should there be any dependences, or should the package conflict with
others already installed, an action will be presented to fix this, and you will
be prompted to confirm or abort the operation.
METHOD #1
To upgrade a deb package with dpkg, just install it again with the -i option; if
the package file you are installing is newer, Debian will automatically upgrade;
if it is older, it will automatically downgrade.
712 The Linux Cookbook, 2nd Edition
METHOD #2
Use apt-get to upgrade either single packages or the entire system.
To upgrade a single package with apt-get, just install it again with the
install option, and follow that with the name of the package to upgrade.
⇒ To upgrade the hello package, type:
# apt-get install hello RET
This command will upgrade the hello package to the most current version
available on your Debian distribution source, if there is one greater than the
version already installed on your system. If additional packages must be up-
graded first, in order for this new package upgrade to function properly, this
command will fetch and upgrade those packages, too. Before downloading
any packages, apt-get will show the list of packages that will be installed,
replaced, or otherwise changed, and it will wait for confirmation first.
To bring your entire Debian system up to date, use the apt-get tool with
the following command arguments. First, use the update argument to update
your system’s list of available software packages. Then run apt-get again,
using either the upgrade argument to upgrade all of the installed packages
to their most recently available versions, or use the dist-upgrade argument
when a new version of the Debian system is announced, to upgrade to that
new version.
⇒ Here are two ways to use this.
• To upgrade all of the software on your system to their most recent
versions, type:
This removes the package but keeps any configuration files. Use the
--purge option to completely eliminate everything related to a package, in-
cluding all configuration and setup files.
⇒ To purge the gimp1.2 package, type:
# dpkg --purge gimp1.2 RET
NOTES: If purging a package will break dependencies, dpkg will not let you
do it. You can force it, though; to get a list of “force” options, run dpkg with
the ‘--force-help’ option.
⇒ To peruse all of the files that are part of the gimp1.2 package, type:
# dpkg -L gimp1.2 RET
rpm, the rpm Package Manager,4 is the native package format of the Red
Hat distribution, as well as many other popular Linux distributions, including
Mandrake and SuSE.
You can obtain rpm packages on the Web from http://rpmfind.net/ and
http://freshrpms.net/, both searchable package databases.
Management of rpm packages is done with the command line rpm tool; the
following recipes describe its use.
4
Like gnu, this is a recursive acronym.
Appendix A: Administrative Issues 715
To list a particular package, use rpm with the -q option, and give the
package name.
⇒ To see if the gimp package is installed, type:
# rpm -q gimp RET
If a package has unmet dependencies, rpm will not install it; it also won’t in-
stall a package if a current or newer version is installed. Use -i in conjunction
with the --nodeps flag to install a package even if it has unmet dependencies.
⇒ To install the gimp-1.2.3-9.i386.rpm package, regardless of unmet de-
pendencies, type:
# rpm -i --nodeps gimp-1.2.3-9.i386.rpm RET
If other packages depend on the package, rpm won’t erase it; use --nodeps
to override this behavior.
⇒ To remove the gimp package, regardless of any dependencies, type:
# rpm -e --nodeps gimp RET
NOTES: By default, the name of the user’s home directory will be the same
as the username. So, for example, the user mary will have a home directory
of /home/mary.
# uptime RET
3:34pm up 4:31, 4 users, load average: 0.01, 0.05, 0.07
#
To get a list of the times and dates when the system was recently rebooted,
give ‘reboot’ as an argument to last (see Recipe 2.6.4 [Listing the Last Time
a User Logged In], page 41).
⇒ To output a list of times when the system was rebooted, type:
# last reboot RET
METHOD #1
The file /proc/cpuinfo contains information about the central processing
unit of the system, including its make and model, and its speed in MHz. Use
cat to output the contents of this file.
⇒ To display information about the system’s cpu, type:
# cat /proc/cpuinfo RET
NOTES: This requires that the special /proc filesystem is installed, but this
has been a Linux standard for some time.
720 The Linux Cookbook, 2nd Edition
METHOD #2
You can also use gnu uname to output the cpu processor type of the system
(such as i686, powerpc, etc.); specify this with the -m option.
⇒ To output the cpu processor type of the system, type:
# uname -m RET
The -a option is useful; it outputs all information about the system that
it can, including os name and release number, cpu type, plus the version date
and number of the operating system and the machine’s hostname.
⇒ To output all of the uname information for the system you are on, type:
# uname -a RET
/etc/debian-version Debian
/etc/fedora-release Fedora
/etc/mandrake-release Mandrake
/etc/redhat-release Red Hat
/etc/SuSE-release SuSE
/etc/slackware-version Slackware
⇒ To output the distribution version on a Fedora system, type:
# cat /etc/fedora-release RET
722 The Linux Cookbook, 2nd Edition
Appendix B: Conventional File Name Extensions 723
File types indicate the type of data in the file, generally one of text, image,
audio, or binary. You can always use file to determine what kind of data a file
contains (see Recipe 8.1.1 [Determining a File’s Type and Format], page 187).
The following table lists typical file name extensions (the part of the file
name following the last dot) used for certain file types, identifies what type of
file the extension is used for, and describes the particular format.
In your own bin, you can put scripts and tools of your own devising.
They will be executable by you, but by no other users on the system. To
make a file executable by all users, the superuser will have to put the file in
/usr/local/bin, the system-wide local directory for binaries.
NOTES: The current shell won’t recognize any changes you make in your
.bashrc; you’ll have to run it by hand the first time, or just exit and start a
new shell.
728 The Linux Cookbook, 2nd Edition
AWK
Robbins, Arnold D., The gnu Awk User’s Guide, Free Software Founda-
tion, 1997. [http://gnu.org/software/gawk/manual/]
Dselect
GROFF
IRC
Caraballo, David, and Joseph Lo, The IRC Prelude, Web site, 2000.
Excellent introduction to irc for first-timers.
[http://irchelp.org/irchelp/new2irc.html]
PERL
Kuhn, Bradley M., Picking Up Perl, Web site, 2002. A good but unfin-
ished perl tutorial. [http://www.ebb.org/PickingUpPerl/]
PostScript
SED
Bonzini, Paolo, The seder’s Grab-Bag, Web site, 2002. A useful collec-
tion of sed information including a faq and many example scripts.
[http://sed.sourceforge.net/grabbag/]
Pement, Eric, Handy One-Liners for sed, Web site, 2003. A single page
listing many useful commands for editing and processing text.
[http://www.student.northpark.edu/pemente/sed/
sed1line.txt]
Pizzini, Ken, sed, a Stream Editor, Free Software Foundation, 1998.
[http://www.gnu.org/software/sed/manual/sed.html]
Hahn, Jane, LaTEX for Everyone, PTR Prentice-Hall Inc., 1993. A won-
derful book for those who want to use the power of TEX for type-
setting correspondence, papers, articles, and reports.
Knuth, Donald E., The TEXbook, Addison-Wesley, 1984. The original TEX
book, written by the author of TEX.
Oetiker, Tobias, et al., The Not So Short Introduction to LaTEX, Web
site, 1999. A recommended introduction to using LaTEX.
[ftp://ctan.tug.org/tex-archive/documentation/lshort/]
Robbins, Arnold, “What’s GNU: Texinfo,” Linux Journal, issue 6, Octo-
ber 1994. An introductory tutorial.
[http://www.linuxjournal.com/article.php?sid=2840]
Underwood, Rebecca, et al., LaTEX and BibTEX Tutorials and Assign-
ment, Web site, 1996. A good LaTEX tutorial that shows
how to typeset an article. Available online in dvi format.
[http://www.soe.ucsc.edu/~karplus/80k/latex-tutorial-
new.dvi]
Finseth, Craig A., The Craft of Text Editing, Springer-Verlag and Co.,
1991. The theory of text editing; a technical description of the
technology of text editors.
[http://www.finseth.com/~fin/craft]
Hauben, Michael and Ronda Hauben, Netizens: On the History and
Impact of the Net, ieee Computer Society
Press, 1997. A thorough social history of the net,
with much material on unix history throughout.
[http://www.columbia.edu/~hauben/netbook/]
Kernighan, Brian W. and Rob Pike, The Unix Programming Environ-
ment, Prentice Hall Computer Books, 1984. Describes the
tools philosophy of unix and what it affords programmers.
[http://cm.bell-labs.com/cm/cs/upe/]
Salus, Peter H., A Quarter Century of UNIX, Addison-Wesley, 1994. A
complete history of the unix operating system.
Walker, A.N., The UNIX Environment, John Wiley and Sons Ltd., 1984.
A pleasant tour of the system; the fact that it is taken on such
dated equipment only demonstrates the tenacity of the tools.
Appendix D: References for Further Interest 737
Program Index
atrm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 audacity . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
& . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72, 118 aumix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
&& . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 aview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
&> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69, 98
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63, 144 B
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
| . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 backgammon . . . . . . . . . . . . . . . . . . . . . . . . . 583
|| . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 balsa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
> . . . . . . . . . . . . . . . . . . . . . . . . . . 68, 258, 276 banner . . . . . . . . . . . . . . . . . . . . . . . . . 402, 583
>> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68, 258 basename . . . . . . . . . . . . . . . . . . . . . . . 143, 148
< . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67, 449 bash . . . . 42, 53, 54, 62, 74, 77, 85, 90, 148,
2> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 343
9wm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 battlestar . . . . . . . . . . . . . . . . . . . . . . . . . 584
bbdb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
bc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114, 562
A bcd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
abbrev-mode . . . . . . . . . . . . . . . . . . . . . . . . 242 bg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
abiword . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 biff . . . . . . . . . . . . . . . . . . . . . . . . . . . 624, 690
addgroup . . . . . . . . . . . . . . . . . . . . . . . . . . . 718 bitchx. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
adduser . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 bitmap . . . . . . . . . . . . . . . . . . . . . . . . . 118, 436
adventure . . . . . . . . . . . . . . . . . . . . . . . . . . 583 blackbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
aee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 blender . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
afterstep . . . . . . . . . . . . . . . . . . . . . . 117, 120 bluefish . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
alias . . . . . . . . . . . . . . . . . . . . . . . . . 83, 84, 87 boggle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
amaya . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 browser-history . . . . . . . . . . . . . . . . . . . . 656
amixer . . . . . . . . . . . . . . . . . . . . . . . . . 463, 474 bunzip2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
an . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 bye . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
analog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 bzip2 . . . . . . . . . . . . . . . . . 196, 197, 198, 407
animate . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
antiword . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
aplay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 C
apropos . . . . . . . . . . . . . . . . 44, 67, 68, 69, 72 caesar . . . . . . . . . . . . . . . . . . . . . . . . . 569, 584
apt-get. . . . . . . . . . . . . . . . . . . . 709, 711, 712 cal . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256, 539
arena . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 calc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . 583 calendar. . . . . . . . . . 541, 542, 543, 544, 545
ascii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 can . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
asclock . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 canfield . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
ash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 cat . . . . . 153, 163, 190, 216, 217, 226, 256,
aspell . . . . . . . . . . . . . . . . . . . . . . . . . 278, 280 260, 294, 305, 327, 343, 401, 442, 566,
at . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556 586, 587, 719, 720
atc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 catdoc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
aterm . . . . . . . . . . . . . . . . . . . . . . . . . . 114, 117 ccal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
atq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 cd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132, 133
740 The Linux Cookbook, 2nd Edition
hls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 L
hmount . . . . . . . . . . . . . . . . . . . . . . . . . 527, 528 last . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41, 719
host . . . . . . . . . . . . . . . . . . . . . . . . . . . 686, 687 latex . . . . . . . . . . . . . . . . . . . . . . 374, 377, 390
hostname . . . . . . . . . . 36, 37, 38, 54, 63, 671 le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
hpcdtoppm . . . . . . . . . . . . . . . . . . . . . . . . . . 446 leave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
html-mode . . . . . . . . . . . . . . . . . . . . . . . . . . 662 less . . . . . 44, 45, 50, 69, 75, 183, 193, 211,
html2ps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 218, 222, 223, 227, 228, 287, 297, 306,
327, 346, 354, 399, 464, 546, 548, 590,
hunt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
622, 628, 646, 663
licq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
I links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
idraw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
imgsizer . . . . . . . . . . . . . . . . . . . . . . . . . . . 663 linuxdoc . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
ln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
import . . . . . . . . . . . . . . . . . . . . . 441, 447, 448
locate . . . . . . . . . . . . . . . . . . . . . . 10, 171, 399
info . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48, 517
logout . . . . . . . . . . . . . . . . . . . . . . . . . . . 31, 63
input mode . . . . . . . . . . . . . . . . . . . . . 246, 328 look . . . . . . . . . . . . . . . . . . 226, 283, 286, 590
ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 lpq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
insert mode . . . . . . . . . . . . . . . . . . . . 246, 248 lpr . . . . . 195, 309, 370, 374, 510, 512, 513,
insert-mode . . . . . . . . . . . . . . . . . . . . . . . . 234 514, 515, 517, 521, 522
ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 lpr-buffer . . . . . . . . . . . . . . . . . . . . . . . . . 517
isearch-backward . . . . . . . . . . . . . . . . . . . 352 lpr-region . . . . . . . . . . . . . . . . . . . . . . . . . 517
iso-accents-mode . . . . . . . . . . . . . . . . . . . 240 lprm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
ispell . . . . . . . . . . . . . . . . . . . . . 277, 278, 280 lptest. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
ls . . . . . 36, 83, 84, 133, 136, 140, 153, 166,
168, 182, 184, 504
lsh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
J lynx . . . . . 37, 114, 158, 287, 350, 412, 514,
jabber. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695 515, 615, 643, 659, 663, 666
lyx . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378, 379
jed . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232, 267
LyX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
jobs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
joe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 M
m4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
magicfilter . . . . . . . . . . . . . . . . . . . . 518, 703
K mail . . . . 545, 550, 611, 612, 613, 614, 616,
617, 619, 622
kill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
konsole . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 mailx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
korganizer . . . . . . . . . . . . . . . . . . . . . . . . . 553 man . . . . . . . . . . . . . . 44, 46, 62, 228, 358, 522
kraut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586 mc . . . . . . . . . . . . . . . . . . . . . . . . . 157, 191, 223
ksh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 mcedit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Program Index 743
mcopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 O
mdel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 oclock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
mdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525 od . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221, 222
members . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 ogg123 . . . . . . . . . . . . . . . . . . . . . 466, 467, 495
menu-bar-mode . . . . . . . . . . . . . . . . . . . . . . 235 oggenc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
mesg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690 ogginfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 625 oleo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
metamail . . . . . . . . . . . . . . . . . . . . . . . . . . . 628 overwrite-mode . . . . . . . . . . . . . . . . 234, 238
metasend . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
mf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
mformat . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 P
mhshow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629 pan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
micq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694 passwd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
mikmod. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 paste . . . . . . . . . . . . . . . . . . . . . . . . . . 322, 592
mille . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 patch . . . . . . . . . . . . . . . . . . . . . . . . . . 192, 196
minicom . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606 pbmtext . . . . . . . . . . . . . . . . . . . . . . . . 447, 448
miscfiles . . . . . . . . . . . . . . . . . . . . . . . . . . 290 pcdtoppm . . . . . . . . . . . . . . . . . . . . . . . 416, 445
mkdir . . . . . . . . . . . . . . . . . . . . . . 130, 131, 727 pd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
mkisofs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504 pdf2ps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
mlterm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 pdksh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
mogrify . . . . . . . . . . . 421, 422, 425, 427, 429 pdmenu . . . . . . . . . . . . . . . . . . . . . . . . . . . 91, 93
monop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 perl . . . . . . . . . . . . . . . . . . . . . . . . . . . 351, 589
montage . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430 phantasia . . . . . . . . . . . . . . . . . . . . . . . . . . 585
more . . . . . . . . . . . . . . . . . . . . . . . . . . . 211, 346 pig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
morse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 ping . . . . . . . . . . . . . . . . . . . . . . . . . . . 685, 686
mount . . . . . . . . . . . . . . . . . . . . . . 504, 506, 529 plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
mozilla . . . . . . . . . . . 160, 224, 412, 638, 661 play . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
mp3info . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 player. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
mpg321 . . . . . . . . . . . . . . . . . . . . . 469, 470, 494 playmidi . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
mtools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525 plog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
multi-gnome-terminal . . . . . . . . . . . . . . 115 plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
mutt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634 poff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
mv . . . . . . . . . . . . . . . . . 65, 144, 146, 148, 153 pom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
pon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
powershell . . . . . . . . . . . . . . . . . . . . . . . . . 115
N ppmquant . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
nano . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 ppt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
netpbm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 pr . . . . . . . . . . . . . . . . 297, 307, 308, 312, 663
newspeak . . . . . . . . . . . . . . . . . . . . . . . 371, 586 primes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
nl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 print-node . . . . . . . . . . . . . . . . . . . . . . . . . 517
nn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681 ps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41, 42, 73
nngrep. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682 ps-print-buffer . . . . . . . . . . . . . . . . . . . . 517
number . . . . . . . . . . . . . . . . . . . . . . . . . 568, 584 ps-print-region . . . . . . . . . . . . . . . . . . . . 517
nyc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586 ps2book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
744 The Linux Cookbook, 2nd Edition
X Y
yes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65, 151
X11R6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
yow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
xae . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
ytalk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
xbiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
xcal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
xcalc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
xcdroast . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
Z
xclock . . . . . . . . . . . . . . . . . . . . . 101, 102, 105 zcat . . . . . . . . . . . . . . . . . . . . . . . 257, 385, 449
xcolors . . . . . . . . . . . . . . . . . . . . . . . . 103, 118 zgrep . . . . . . . . . . . . . . . . . . . . . . 349, 656, 657
xcoral. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 zgv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
xdm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27, 98 zicq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
xdvi . . . . . . . . . . . . . . . . . . . . . . . 374, 399, 413 zinf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
xedit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 zip . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533, 534
xemacs . . . . . . . . . . . . . . . . . . . . . . . . . 233, 273 zless . . . . . . . . . . . . . . . . . . . . . . . 50, 198, 211
xfd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 zsh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Concept Index 747
Concept Index
Automated Readability Index (ari) . . . 289 binary files, matching lines in . . . . . . . . . 350
automatic appointment delivery . . . . . . 545 bindings, key . . . . . . . . . . . . . . . . . . . . . . . . 237
automatically answering a command bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
prompt . . . . . . . . . . . . . . . . . . . . . . . . . . 65 bit bucket . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
AutoTrace . . . . . . . . . . . . . . . . . . . . . . . . . . 436 BitchX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
Aview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418 Bitmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
awk . . . . . . . . . . . . . . . . . . . . . . . . 85, 365, 734 bitmaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Ayttm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694 Bitnet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
black and white, transforming color images
to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
B BlackBox . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
backgammon . . . . . . . . . . . . . . . . . . . . . . . . 583 Blender . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
background and history of linux . . . . . . . 15 blog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
background jobs . . . . . . . . . . . . . . . . . . . . . . 70 Bluefish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
background, putting a job in the . . . . . . . 72 body size . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
backspace underlines . . . . . . . . . . . . . . . . . 329 Boggle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
backspace underlining . . . . . . . . . . . 226, 327 Bonzini, Paolo. . . . . . . . . . . . . . . . . . . . . . . 735
backups, making. . . . . . . . . . . . . . . . . . . . . 200 booklet, arranging a PostScript document
Balsa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632 in a . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
bang . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 booklets, printing . . . . . . . . . . . . . . . . . . . . 371
Banner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 books and guides, Linux . . . . . . . . . . . . . 733
banners, outputting text . . . . . . . . . . . . . 402 books, unix and Linux history . . . . . . . . 736
Barcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 boot disk . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
base file name . . . . . . . . . . . . . . . . . . . . . . . 129 boot floppy, making a . . . . . . . . . . . . . . . . 702
Bash . . . . 10, 30, 36, 53, 112, 143, 146, 148, booting up . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
188, 192, 207, 231, 254, 365, 428, 478, borders, adding to images . . . . . . . . . . . . 429
561, 565, 603 Bortzmeyer, Stéphane . . . . . . . . . . . . . . . . 734
basic commands and concepts . . . . . . . . . 27 Bourne shell . . . . . . . . . . . . . . . . . . . 53, 85, 92
bass, adjusting . . . . . . . . . . . . . . . . . . . . . . 463 Bourne, Steve . . . . . . . . . . . . . . . . . . . . . . . . 53
Battlestar . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 Brahms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
bbs, connecting to a . . . . . . . . . . . . . . . . . 606 Browne, Christopher B. . . . . . . . . . . . . . . 358
bell character . . . . . . . . . . . . . . . . . . . . . . . . 80 browser history, keeping a . . . . . . . . . . . . 656
Bell Labs . . . . . . . . . . . . . . . . . . . . . . . . . 15, 16 browser history, searching through your
bell, margin . . . . . . . . . . . . . . . . . . . . . . . . . 112 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
bell, visual . . . . . . . . . . . . . . . . . . . . . . . . . . 113 browser history, viewing your . . . . . . . . . 657
Berkeley Systems Distribution . . . . . . . . . 16 browsing files . . . . . . . . . . . . . . . . . . . . . . . . 157
Biff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624 browsing image collections in X . . . . . . . 409
Big Eight hierarchies . . . . . . . . . . . . . . . . . 680 browsing images in a console . . . . . . . . . 410
Bill of Rights . . . . . . . . . . . . . . . . . . . . . . . . 291 browsing PhotoCD archives . . . . . . . . . . 415
binaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705 browsing the Web . . . . . . . . . . . . . . . . . . . 637
binaries, using a directory for personal bsd . . . . . . . . . . . . . . . . . . . . . 16, 92, 245, 542
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727 Buckyballs . . . . . . . . . . . . . . . . . . . . . . . . . . 580
binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 buddy list . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
binary files, listing text in . . . . . . . . . . . . 228 buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
750 The Linux Cookbook, 2nd Edition
files, getting from the Web . . . . . . . . . . . 653 files, writing text to . . . . . . . . . . . . . . . . . . 258
files, giving more than one name . . . . . . 152 files, zipping . . . . . . . . . . . . . . . . . . . . . . . . 534
files, hidden . . . . . . . . . . . . . . . . . . . . . . . . . 138 filespec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
files, including text from other . . . . . . . . 261 filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
files, linking . . . . . . . . . . . . . . . . . . . . . . . . . 152 Filesystem Hierarchy Standard . . . . . . . 129
files, listing in sorted order . . . . . . . . . . . 139 filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
files, listing recursively . . . . . . . . . . . . . . . 140 filter, defined . . . . . . . . . . . . . . . . . . . . . . . . 586
files, listing the misspellings in . . . . . . . . 276 filter, outputting text through ax . . . . . 371
files, making empty . . . . . . . . . . . . . . . . . . 130 filtering out duplicate lines of text . . . . 319
files, managing . . . . . . . . . . . . . . . . . . . . . . 187 finances, managing . . . . . . . . . . . . . . . . . . 580
files, matching lines in many . . . . . . . . . . 348 Findimagedupes . . . . . . . . . . . . . . . . . . . . . 437
files, moving . . . . . . . . . . . . . . . . . . . . . . . . 144 finding all files that match a pattern . . 171
files, naming . . . . . . . . . . . . . . . . . . . . . . . . 129 finding anagrams in text . . . . . . . . . . . . . 588
files, owning . . . . . . . . . . . . . . . . . . . . . . . . . 166 finding crossword puzzle words . . . . . . . 590
files, pasting columns of text from separate finding directories . . . . . . . . . . . . . . . . . . . 182
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 finding files . . . . . . . . . . . . . . . . . . . . . . . . . 171
files, perusing multiple text . . . . . . . . . . . 215 finding files by multiple criteria . . . . . . . 179
files, perusing the differences in a group of finding files in a directory tree . . . . . . . . 172
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 finding files in a directory tree by access
files, preparing for printing . . . . . . . . . . . 518 time . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
files, previewing print . . . . . . . . . . . . . . . . 413 finding files in a directory tree by change
files, printing . . . . . . . . . . . . . . . . . . . . . . . . 509 time . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
files, read-only. . . . . . . . . . . . . . . . . . . . . . . 169 finding files in a directory tree by
files, reference . . . . . . . . . . . . . . . . . . . . . . . 289 modification time . . . . . . . . . . . . . . . 176
files, removing . . . . . . . . . . . . . . . . . . . . . . . 149 finding files in a directory tree by name
files, removing interactively . . . . . . . . . . . 150 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
files, removing those with strange names finding files in a directory tree by owner
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
files, removing without verification . . . . 151 finding files in a directory tree by size . . 174
files, renaming . . . . . . . . . . . . . . . . . . . . . . . 144 finding files in directory listings . . . . . . . 182
files, renaming multiple . . . . . . . . . . . . . . 147 finding matches for word games . . . . . . . 588
files, searching more than plain text . . . 348 finding newsgroups for a topic . . . . . . . . 682
files, sharing . . . . . . . . . . . . . . . . . . . . . . . . 163 finding palindromes in text . . . . . . . . . . . 589
files, showing which contain matching lines finding patterns in certain places. . . . . . 342
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 finding patterns only in certain positions
files, splitting into smaller . . . . . . . . . . . . 189 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
files, touching . . . . . . . . . . . . . . . . . . . . . . . 189 finding phrases in text regardless of spacing
files, tracking revisions to . . . . . . . . . . . . 202 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
files, transferring large . . . . . . . . . . . . . . . 189 finding prime factors . . . . . . . . . . . . . . . . . 567
files, undeleting. . . . . . . . . . . . . . . . . . . . . . 150 finding relevancies in texts . . . . . . . . . . . 301
files, unzipping . . . . . . . . . . . . . . . . . . . . . . 535 finding similar or relevant text . . . . . . . . 301
files, world readable . . . . . . . . . . . . . . . . . . 170 finding the correct spelling of a word . . 275
files, world writable . . . . . . . . . . . . . . . . . . 170 finding the differences between directories
files, write-protecting . . . . . . . . . . . . . . . . 169 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
760 The Linux Cookbook, 2nd Edition
full path name . . . . . . . . . . . . . . . . . . . . . . 126 getting the status of an rpm package . . 716
Fuller, R.Buckminster . . . . . . . . . . . . . . . . . 23 getting the virtual console number . . . . . 33
fully qualified domain name (fqdn) . . . 687 Ghostscript . . . . . . . 391, 451, 457, 460, 605
functions, Emacs . . . . . . . . . . . . . . . . . . . . 234 gid . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163, 717
furniture, designing . . . . . . . . . . . . . . . . . . 438 gimp . . . . . . . . . . . . . . . 20, 427, 433, 446, 514
fvwm2 . . . . . . . . . . . . . . . . . . . . . 96, 100, 108 gimp, using the . . . . . . . . . . . . . . . . . . . . . . 434
fvwm95 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 giving a file more than one name. . . . . . 152
glame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
Glimmer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
G glob expression . . . . . . . . . . . . . . . . . . . . . . 153
Gaim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695 Global System for Mobile Communications
Galeon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 (gsm) . . . . . . . . . . . . . . . . . . . . . . . . . . 723
games, finding matches for word . . . . . . 588 Global Thermonuclear War . . . . . . . . . . . 585
gamma correction . . . . . . . . . . . . . . . . . . . 427 globbing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Gcal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 glue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
geek, computer . . . . . . . . . . . . . . . . . . . . . . . 25 gmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
general Linux guides and instruction . . 733 gnome . . . 97, 115, 157, 264, 580, 632, 638,
General Public License (gnu gpl) . . . . . 17 668, 682
generating output from sgml . . . . . . . . . 390 GNU Awk User’s Guide, The . . . . . . . . . 734
genesis of the free software movement . . 16 gnu Emacs. . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Gentle Introduction to TEX, A . . . 376, 735 gnu file utilities . . . . . . . . . . . . . . . . . . . . . . 23
Gentoo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731 gnu General Public License (gnu gpl)
geodesic domes . . . . . . . . . . . . . . . . . . . . . . 580 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18, 21
geometry, window . . . . . . . . . . . . . . . . . . . 102 gnu gpl . . . . . . . . . . . . . . . . . . . . . . 17, 18, 21
getting a description of a program . . . . . 46 gnu Image Manipulation Program (gimp)
getting a terminal window in X . . . . . . . 109 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
getting acquainted with Emacs . . . . . . . 232 gnu Manifesto . . . . . . . . . . . . . . . . . . . . . . 290
getting acquainted with Mozilla . . . . . . . 638 gnu Network Object Model Environment
getting acquainted with Vi . . . . . . . . . . . 245 (gnome) . . . . . . . 97, 580, 632, 668, 682
getting and installing a Linux distribution gnu notation . . . . . . . . . . . . . . . . . . . . . . . . . . 8
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706 gnu Privacy Guard (gpg) . . . . . . . . . . . . 572
getting files from the Web . . . . . . . . . . . . 653 gnu Project . . 17, 19, 97, 121, 286, 680, 737
getting information about a file . . . . . . . 187 gnu text utilities . . . . . . . . . . . . . . . . . . . . . 23
getting information about an X window gnu-style options . . . . . . . . . . . . . . . . . . . . . 37
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 gnu/Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
getting started with LyX . . . . . . . . . . . . . 379 GnuCash . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
getting started with TEX and LaTEX . . . 375 Gnumeric . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
getting the hostname of an ip address Gnuplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 Gnus . . . . . . . . . . . . . . . . . . . . . . . . . . . 632, 681
getting the ip address of a hostname . . 686 Go Fish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
getting the name of the current directory gocr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 going into maintenance mode . . . . . . . . . 705
getting the name of your current shell . . 91 Google Groups . . . . . . . . . . . . . . . . . . . . . . 679
getting the status of a deb package . . . 713 Gopher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
762 The Linux Cookbook, 2nd Edition
lines beginning with certain text, matching Linux tool and application guides . . . . . 734
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Linux User Group (lug) . . . . . . . . . . 11, 737
lines ending with certain text, matching Linux User Groups (lugs) . . . . . . . . . . . . . 14
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Linux Weekly News . . . . . . . . . . . . . . . . . . 737
lines of a certain length, matching . . . . 339 Linux, background and history of . . . . . . 15
lines of sorted text, viewing . . . . . . . . . . 226 Linux, displaying the version . . . . . . . . . 720
lines per page, counting in Emacs . . . . . 294 Linux, distributions of . . . . . . . . . . . . . . . . 19
lines, counting in a text . . . . . . . . . . . . . . 294 Linux, hardware for . . . . . . . . . . . . . . . . . . 732
lines, matching that only contain certain Linux, in specialized fields . . . . . . . . . . . . . 12
characters . . . . . . . . . . . . . . . . . . . . . . 340 Linux, installing . . . . . . . . . . . . . . . . . . . . . . 10
lines, outputting random . . . . . . . . . . . . . 585 Linux, the arrival of . . . . . . . . . . . . . . . . . . 18
lines, showing the ends of . . . . . . . . . . . . 217 Linux.Com . . . . . . . . . . . . . . . . . . . . . . . . . . 737
link, copying to the clipboard from Mozilla Linux: Rute Users Tutorial and Exposition
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
link, opening in a new window . . . . . . . . 642 LinuxDoc dtd. . . . . . . . . . . . . . . . . . . . . . . 380
links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Linuxdoc-Tools . . . . . . . . . . . . . 358, 376, 388
Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 LinuxHardware.net . . . . . . . . . . . . . . 700, 732
links, following . . . . . . . . . . . . . . . . . . . . . . 639 LinuxHardware.org . . . . . . . . . . . . . . 700, 733
links, listing all in a page . . . . . . . . . . . . . 646 Lisp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
links, viewing hidding . . . . . . . . . . . . . . . . 646 list, columnating a . . . . . . . . . . . . . . . . . . . 323
Linux and related software, archives of listing a disk’s free space . . . . . . . . . . . . . 501
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732 listing a file’s disk usage . . . . . . . . . . . . . . 502
Linux books and guides . . . . . . . . . . . . . . 733 listing a sequence of numbers . . . . . . . . . 565
Linux distribution, getting and installing a listing aliases . . . . . . . . . . . . . . . . . . . . . . . . . 84
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706 listing all files in a deb package . . . . . . . 713
Linux distributions . . . . . . . . . . . . . . . . . . 731 listing all files in an rpm package . . . . . 716
Linux Documentation Project (ldp) . . . 13, listing all of a user’s processes . . . . . . . . . 42
50, 380, 733 listing all of the words in text . . . . . . . . 297
Linux FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . 733 listing all processes on the system . . . . . . 42
Linux Gazette . . . . . . . . . . . . . . . . . . . . . . . 733 listing all the links in a page . . . . . . . . . . 646
Linux guides and instruction, general . . 733 listing available groups . . . . . . . . . . . . . . . 163
Linux Journal . . . . . . . . . . . . . . . . . . . . . . . 737 listing available scanner devices . . . . . . . 443
Linux Network Administrator’s Guide, The listing available TEX fonts . . . . . . . . . . . . 398
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 listing available X fonts . . . . . . . . . . . . . . 397
Linux Network Administrators Guide . . 11 listing deb packages . . . . . . . . . . . . . . . . . 710
Linux Network Administrators’ Guide, listing dependences for a deb package
Second Edition . . . . . . . . . . . . . . . . . . 733 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
Linux news and commentary . . . . . . . . . 737 listing dependences for an rpm package
Linux on Laptops . . . . . . . . . . . . . . . . . . . . 733 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
Linux software and hardware, sources of listing directories . . . . . . . . . . . . . . . . . . . . 133
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731 listing directories in color . . . . . . . . . . . . 134
Linux System Administrator’s Guide . . 11, listing directories in columns . . . . . . . . . 138
734 listing directory tree graphs . . . . . . . . . . 156
Linux Today . . . . . . . . . . . . . . . . . . . . . . . . 737 listing file attributes . . . . . . . . . . . . . . . . . 136
Concept Index 767
text, checking for long sentences . . . . . . 289 text, inserting at the beginning of a file
text, checking for misused phrases . . . . 286 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
text, checking for readability . . . . . . . . . 288 text, justifying . . . . . . . . . . . . . . . . . . . . . . 311
text, columnating . . . . . . . . . . . . . . . . . . . . 322 text, left-justifying . . . . . . . . . . . . . . . . . . . 311
text, columnating from separate files . . 323 text, listing all of the words in . . . . . . . . 297
text, concatenating . . . . . . . . . . . . . . . . . . 256 text, listing in binary files . . . . . . . . . . . . 228
text, converting from proprietary formats text, listing only the unique words in . . 298
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533 text, listing the Misspellings in . . . . . . . 276
text, converting to LaTEX . . . . . . . . . . . . . 393 text, listing the urls in . . . . . . . . . . . . . . 659
text, converting underlines in . . . . . . . . . 328 text, listing words in . . . . . . . . . . . . . . . . . 297
text, counting . . . . . . . . . . . . . . . . . . . . . . . 293 text, listing words sorted alphabetically
text, counting a selection of . . . . . . . . . . 295 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
text, counting selected word occurrences in text, manipulating selections of . . . . . . . 253
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 text, matching lines beginning with certain
text, counting the characters in a . . . . . 294 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
text, counting the lines in a . . . . . . . . . . 294 text, matching lines ending with certain
text, counting the words in a . . . . . . . . . 294 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
text, counting word occurrences in . . . . 299 text, matching patterns of . . . . . . . . . . . . 335
text, cutting . . . . . . . . . . . . . . . . . . . . . . . . 254 text, numbering lines of . . . . . . . . . . . . . . 326
text, decoding in rot13 . . . . . . . . . . . . . . 571 text, outputting a visual image of . . . . . 362
text, deleting characters in . . . . . . . . . . . 318 text, outputting in a dialect . . . . . . . . . . 586
text, determining if two differ . . . . . . . . . 191 text, outputting in a font. . . . . . . . . . . . . 361
text, displaying . . . . . . . . . . . . . . . . . . . . . . 216 text, outputting in columns . . . . . . . . . . 370
text, displaying non-printing characters in text, outputting in custom pages . . . . . . 362
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 text, outputting in landscape orientation
text, displaying the beginning part of . . 218 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
text, displaying the end part of . . . . . . . 218 text, outputting in vertical slices . . . . . . 369
text, displaying the hex values of . . . . . 221 text, outputting multiple copies of . . . . 370
text, displaying the literal characters of text, outputting selected pages of . . . . . 371
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 text, outputting through a filter . . . . . . 371
text, displaying the middle part of . . . . 219 text, outputting to PostScript . . . . . . . . 359
text, double-spacing . . . . . . . . . . . . . . . . . 307 text, outputting with an underlay . . . . . 367
text, editing streams of . . . . . . . . . . . . . . 255 text, outputting with fancy headers . . . 368
text, eliminating extra spaces in . . . . . . 305 text, outputting with indentation . . . . . 370
text, encoding in rot13 . . . . . . . . . . . . . . 570 text, outputting with language highlighting
text, filtering into Morse code . . . . . . . . 584 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
text, filtering into Pig Latin . . . . . . . . . . 585 text, overstriked . . . . . . . . . . . . . . . . . . . . . 330
text, filtering out duplicate lines of . . . . 319 text, paginating . . . . . . . . . . . . . . . . . . . . . 312
text, finding anagrams in . . . . . . . . . . . . . 588 text, paginating only part of some . . . . 315
text, finding palindromes in . . . . . . . . . . 589 text, paginating with non-printing
text, finding relevancies in . . . . . . . . . . . . 301 characters . . . . . . . . . . . . . . . . . . . . . . 315
text, finding similar or relevant . . . . . . . 301 text, pasting . . . . . . . . . . . . . . . . . . . . . . . . 254
text, formatting . . . . . . . . . . . . . . . . . . . . . 305 text, perusing . . . . . . . . . . . . . . . . . . . . . . . 211
text, from PostScript . . . . . . . . . . . . . . . . 460 text, perusing raw . . . . . . . . . . . . . . . . . . . 214
784 The Linux Cookbook, 2nd Edition
Xspread . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581 Z
Xterm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Zawinski, Jamie . . . . . . . . . . . . . . . . . . . . . 592
xterm font, resizing . . . . . . . . . . . . . . . . . . 398 ZenIRC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
XWave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 zicq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
Xwrits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554 Zinf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Xwud. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 zip archives, managing . . . . . . . . . . . . . . . 533
Zip codes . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Zip drives . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
Y zipping files . . . . . . . . . . . . . . . . . . . . . . . . . 534
Zippy the Pinhead . . . . . . . . . . . . . . . . . . . 588
yanking text . . . . . . . . . . . . . . . . . . . . . . . . 254 Zmodem . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Yellow Dog. . . . . . . . . . . . . . . . . . . . . . . . . . 732 zombie process . . . . . . . . . . . . . . . . . . . . . . . 41
ymmv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 zork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
Ymodem . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608 Zsh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94, 367