Unix para Mac
Unix para Mac
Unix para Mac
TM
From
&
UNIX for Mac: Your visual blueprintTM to maximizing the foundation of Mac OS X
Published by Wiley Publishing, Inc. 909 Third Avenue New York, NY 10022 Published simultaneously in Canada Copyright 2003 by Wiley Publishing, Inc., Indianapolis, Indiana Certain designs and text Copyright 1992-2003 maranGraphics, Inc., used with maranGraphics' permission. maranGraphics, Inc. 5755 Coopers Avenue Mississauga, Ontario, Canada L4Z 1R9 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate percopy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: permcoordinator@wiley.com. Library of Congress Control Number: 2003101791 ISBN: 0-7645-3730-X Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1V/RX/QU/QT/IN
Truly a 19th century architectural wonder, London's Tower Bridge took 432 construction workers eight years to build. Architect Horace Jones designed the massive bascule bridge a type of counterweighted drawbridge and at its completion in 1894, it was the largest and most sophisticated of its kind ever built. Discover more about London's historic architecture in Frommer's London 2003, available wherever books are sold or at www.frommers.com
FOR PURPOSES OF ILLUSTRATING THE CONCEPTS AND TECHNIQUES DESCRIBED IN THIS BOOK, THE AUTHOR HAS CREATED VARIOUS NAMES, COMPANY NAMES, MAILING, E-MAIL AND INTERNET ADDRESSES, PHONE AND FAX NUMBERS AND SIMILAR INFORMATION, ALL OF WHICH ARE FICTITIOUS. ANY RESEMBLANCE OF THESE FICTITIOUS NAMES, ADDRESSES, PHONE AND FAX NUMBERS AND SIMILAR INFORMATION TO ANY ACTUAL PERSON, COMPANY AND/OR ORGANIZATION IS UNINTENTIONAL AND PURELY COINCIDENTAL.
Important Numbers
For U.S. corporate orders, please call maranGraphics at 800-469-6616 or fax 905-890-9434. For general information on our other products and services or to obtain technical support please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax 317-572-4002.
Permissions
maranGraphics Certain text and illustrations by maranGraphics, Inc., used with maranGraphics' permission.
Trademark Acknowledgments
Wiley, the Wiley Publishing logo, Visual, the Visual logo, Visual Blueprint, Read Less - Learn More and related trade dress are trademarks or registered trademarks of Wiley Publishing, Inc. in the United States and other countries and may not be used without written permission. The maranGraphics logo is a trademark or registered trademark of maranGraphics, Inc. UNIX is a trademark of American Telephone and Telegraph Company. Mac OS is a trademark of Apple Computer, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. and maranGraphics, Inc. are not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.
PRAISE
FOR
VISUAL
BOOKS...
This is absolutely the best computer-related book I have ever bought. Thank you so much for this fantastic text. Simply the best computer book series I have ever seen. I will look for, recommend, and purchase more of the same.
David E. Prince (NeoNome.com)
I have quite a few of your Visual books and have been very pleased with all of them. I love the way the lessons are presented!
Mary Jane Newman (Yorba Linda, CA)
I have always enjoyed your Visual books, as they provide a quick overview of functions. Visual books are helpful even for technically inclined individuals who dont have the time to read thick books in order to get the job done. As a frequent traveler, I am extremely grateful to you for providing a pdf version of each book on a companion CD-ROM. I can easily refer to your book while on the road without much additional weight.
Kin C. Wong (Calgary, Alberta, Canada)
I am an avid fan of your Visual books. If I need to learn anything, I just buy one of your books and learn the topic in no time. Wonders! I have even trained my friends to give me Visual books as gifts.
Illona Bergstrom (Aventura, FL)
I just want to let you know that I really enjoy all your books. Im a strong visual learner. You really know how to get people addicted to learning! Im a very satisfied Visual customer. Keep up the excellent work!
Helen Lee (Calgary, Alberta, Canada)
I just had to let you and your company know how great I think your books are. I just purchased my third Visual book (my first two are dog-eared now!) and, once again, your product has surpassed my expectations. The expertise, thought, and effort that go into each book are obvious, and I sincerely appreciate your efforts.
Tracey Moore (Memphis, TN)
These Visual Blueprints are great books! I just purchased ASP 3.0 it could not have introduced programming with ASP any easier!
Joseph Moglia (St. Louis, MO)
Compliments to the chef!! Your books are extraordinary! Or, simply put, extra-ordinary, meaning way above the rest! THANK YOU THANK YOU THANK YOU! I buy them for friends, family, and colleagues.
Christine J. Manfrin (Castle Rock, CO)
This book is PERFECT for me - its highly visual and gets right to the point. What I like most about it is that each page presents a new task that you can try verbatim or, alternatively, take the ideas and build your own examples. Also, this book isnt bogged down with trying to tell all it gets right to the point. This is an EXCELLENT, EXCELLENT, EXCELLENT book and I look forward purchasing other books in the series.
Tom Dierickx (Malta, IL)
I write to extend my thanks and appreciation for your books. They are clear, easy to follow, and straight to the point. Keep up the good work! I bought several of your books and they are just right! No regrets! I will always buy your books because they are the best.
Seward Kollie (Dakar, Senegal)
Feb 03
At maranGraphics, we believe in producing great computer books one book at a time. maranGraphics has been producing high-technology products for over 25 years, which enables us to offer the computer book community a unique communication process. Our computer books use an integrated communication process, which is very different from the approach used in other computer books. Each spread is, in essence, a flow chart the text and screen shots are totally incorporated into the layout of the spread. Introductory text and helpful tips complete the learning experience. maranGraphics' approach encourages the left and right sides of the brain to work together resulting in faster orientation and greater memory retention. Above all, we are very proud of the handcrafted nature of our books. Our carefully-chosen writers are experts in their fields, and spend countless hours researching and organizing the content for each topic. Our artists
rebuild every screen shot to provide the best clarity possible, making our screen shots the most precise and easiest to read in the industry. We strive for perfection, and believe that the time spent handcrafting each element results in the best computer books money can buy. Thank you for purchasing this book. We hope you enjoy it! Sincerely, Robert Maran President maranGraphics Rob@maran.com www.maran.com
CREDITS
Project Editors Kathleen McFadden Jade L. Williams Acquisitions Editor Jody Kennen Product Development Manager Lindsay Sandman Copy Editors Jill Mazurczyk Marylouise Wiack Technical Editor Erick Tejkowski Editorial Manager Rev Mengle Permissions Editor Laura Moss Media Development Specialist Gregory Stafford Manufacturing Allan Conley Linda Cook Paul Gilchrist Jennifer Guynn Production Coordinator Nancee Reeves Book Design maranGraphics Layout Carrie Foster LeAndra Johnson Joyce Haughey Kristin McMullan Heather Pope Screen Artist Jill A. Proll Cover Illustration David E. Gregory Proofreader Laura L. Bowman Quality Control John Tyler Connoley Andy Hollandbeck Angel Perez Indexer Joan Griffitts Vice President and Executive Group Publisher Richard Swadley Vice President and Publisher Barry Pruett Composition Director Debbie Stailey
TABLE OF CONTENTS
vi
View Portions of a Text File ..............................................................................................44 Extract Text from a File ......................................................................................................46 Redirect Text to a File ........................................................................................................48 Chain Text Commands Together ......................................................................................50 Compare Text Files ............................................................................................................52 Count Characters, Lines, and Words in Text ..................................................................54 Arrange Text in Columns ..................................................................................................55 Sorting Text ........................................................................................................................56 Print Text on a Printer ........................................................................................................58
vii
TABLE OF CONTENTS
Run a Process in the Background ..................................................................................100 Kill a Process ....................................................................................................................102 List Active Processes ........................................................................................................104 Monitor the Top Processes ............................................................................................106
viii
ix
TABLE OF CONTENTS
Chatting on IRC ..............................................................................................................212 Configure Sendmail ........................................................................................................214 Send E-mail from UNIX ..................................................................................................218 Look at Your Mail File ......................................................................................................220 Fetch E-mail from Other Servers ....................................................................................221 Install Pine ........................................................................................................................222 Read E-mail with Pine ....................................................................................................224 Send E-mail with Pine ....................................................................................................226
APPENDIX
What's on the CD-ROM ................................................................................................316 Using the E-Version of the Book ....................................................................................318
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .326
xi
Unix for Mac: Your visual blueprint to maximizing the foundation of Mac OS X uses straightforward examples to teach you how to get the most out of your Mac OS X system by fully using its Unix capabilities. To get the most out of this book, you should read each chapter in order from beginning to end. Each chapter introduces new ideas and builds on the knowledge learned in previous chapters. After you become familiar with Unix for Mac, you can use this book as an informative desktop reference.
Bold Indicates information that must be typed by you. Italics Indicates a new term being introduced.
An Apply It section usually contains a segment of code that takes the lesson you just learned one step further. Apply It sections offer inside information and pointers that can be used to enhance the functionality of your code.
An Extra section provides additional information about the task you just accomplished. Extra sections often contain interesting tips and useful tricks to make working with Mac OS X easier and more efficient.
Courier Font Indicates the use of Unix commands, scripting commands such as shell or Perl commands, source code such as C or Java commands, and HTML.
xii
Chapter 3, "Work with Directories," shows how you can create, delete, move, copy, change, and navigate files and directories. Chapter 4, "Work with Text," demonstrates how you can extract, view, and compare text files, and to chain text commands together. Chapter 5, "Work with Text Editors," illustrates how you can edit a text file in Unix, such as an application's configuration file, a Web page, or a Perl program. Mac OS X offers three text editors pico, vi, and emacs for editing text files. Chapter 6, "Customize Your Shell," shows you how to configure your terminal shell to fit your preference. Chapter 7, "Work with Processes," demonstrates how you can suspend, start, run, kill, list, and monitor processes. Chapter 8, "Automate Shell Tasks," illustrates how a shell script containing a set of instructions is typed in a terminal window and executed to form a basic Unix program. You will also learn how to set scripts to execute at a specific time of day or date using cron. Chapter 9, "Combine Unix and Aqua," demonstrates how you can best take advantage of running Aqua OS X GUI alongside the Unix command line. Chapter 10, "Work with Internet Commands," shows how you can connect to another computer and execute commands or download files. Chapter 11, "System Administration Commands," details how you can assign yourself as the system administrator of your system. Chapter 12, "Install Unix Applications," guides you through the download and installation of programs, some free and some not, which run on Mac OS X. These are often downloaded via the Internet, and come as packages or archives.
Chapter 13, "Install and Use Internet Applications," lists some of the most popular programs that you can download and install for better access via the shell to the Internet. Chapter 14, "Serve Web Pages with Apache," shows you how to use the Apache server on your computer to serve live pages on the Internet, or as your own test bed for Web site creation. Chapter 15, "Work with Perl," shows you how to use Perl for a variety of tasks from system administration to Web pages. Mac OS X comes with Perl pre-installed. Chapter 16, "Run the X Window System," shows you how to get the advantage of using both Mac and Unix graphical programs by running an X server with the Mac OS X GUI called Aqua. Chapter 17, "Install X Window System Software," introduces you to free alternatives to expensive commercial software such as the GIMP that provides the functions of Photoshop, and Open Office.org that is a free equivalent of Microsoft Office. The final chapter, "Develop Unix Applications," shows you how to create and run programs in other languages on Mac OS X.
xiii
INTRODUCTION TO UNIX
ou can get full use out of your Mac OS X computer by learning the ins and outs of the Unix operating system. Even though you may not know it, you use Unix every time you turn on your Mac OS X computer, because at the core, Mac OS X is Unix.
THE HISTORY OF UNIX
For most users, the Unix foundation for Mac OS X operates behind the scenes; they may use Mac OS X for years without needing to directly access the Unix features described in this book. However, by understanding and using Unix, you can take full advantage of the power of Mac OS X.
The original version of UNIX was created in the 1960s in the Bell Labs of AT&T, by researchers who devised a multi-user operating system for large mainframe computers. The role of an operating system like Unix is to provide basic functions such as running programs, BSD Unix System From AT&T, the Unix system spread to research universities, that quickly adopted it. The University of California, Berkeley, was one of the earliest adopters and developers of Unix. The staff and students at Berkeley added many more features to this everevolving operating system. The updated Berkeley Open Source Computer programs begin as source code, written in a computer language by programmers. They are then transformed into applications that you can run through a process called compiling, which translates the source code into commands that a computer can understand. You do not need the source code to run the program. However, if you have access to the source code, you can recreate the application, or change the application by modifying the source code. Many commercial companies do not make their source code public because, if they did, nobody would buy their software. Other groups make their source code freely available to the public; this is known as open source.
saving data, and sending output to a monitor or other device. On your Apple computer, these functions are provided by the Mac OS X operating system, a direct descendent of the original Unix operating system.
version of Unix was known as Berkeley Software Distribution (BSD), and it forms a major branch of the operating system family tree. The BSD family tree must be an apple tree, because the most recent fruit is Mac OS X, which is based on the BSD Unix system from Berkeley. Free Operating Systems and Applications The most famous open-source software is the free operating system known as Linux. A young, Finnish software developer named Linus Torvalds created Linux as a version of Unix that could run on Intel-style PCs, as well as other hardware. In addition to Linux, there are several free versions of BSD Unix, known as Free BSD, Open BSD, and Net BSD. Mac OS X is a cousin to these free BSD operating systems, but is not itself a free operating system. The largest collection of open-source applications comes from the GNU project, developed by the Free Software Foundation. GNU is an acronym for GNU's Not Unix, and yes, that is self-referential. Many of the Unix applications that you run are based on GNU code.
Up to and including Mac OS 9, the Apple operating system was not based on Unix. There was no Unix code at the core of Mac OS 9 or earlier systems; instead, they used an operating system that was developed within Apple Computer. Darwin When it was time to create the next version of Mac OS, Apple chose to base it on a BSD Unix foundation, modified for the specific needs of Apple. This version of BSD Unix was called Darwin. Darwin consists primarily of the Unix kernel, which is the program that runs and manages all the processes and shells of the operating system, along with associated programs and files that make the kernel run. The source code for Darwin is open and available on the Web from http://developer. apple.com/darwin/, although you will probably never need to use it. Not all the Mac OS X operating system is open source; for example, the programs used to create the Mac OS X desktop and windows, known collectively as Aqua, are not available for free and are only distributed as compiled applications. Shell Commands The original computers that ran Unix were not graphical; windows, drop-down menus, desktops, and the point-and-click capabilities of the mouse were to come later. Early versions of Unix were entirely textbased, taking input solely from the keyboard and displaying only on the screen, or sometimes just on a printer. This meant that all Unix programs were textbased, and responded to keystrokes. Users accessed the operating system through commands given to an application called a shell. The Unix operating systems of today can handle graphics with ease, but underneath the graphical windows, text still reigns supreme. Your Mac OS X computer is no exception. In Mac OS X, you enter shell commands through an application named Terminal. Aqua Each time you run Mac OS X on your computer, you are using Aqua. Aqua is the graphical user interface system that gives your Macintosh the distinctive look and feel of Mac OS X the main menu at the top, the Dock, the desktop, the three colored buttons at the upper left corner of each window. The Aqua interface lets you point-and-click to run applications. In truth, Aqua is a group of applications that run atop the Mac OS X foundation of Unix; Aqua starts automatically to provide you with the familiar Mac OS X interface, designed for both keyboard and mouse. X Window System The X Window System is another graphical user interface system that is used on most computers running Unix; however, it does not come standard with Mac OS X. Although both the X Window System and Mac OS X contain the letter X, they are not related the X in X Window System comes from its being a successor to an earlier window-based system named W, and the X in Mac OS X, of course, stands for the Roman numeral ten. Because the X Window System is used on so many other computers, including Linux, BSD, and Solaris machines, there are a number of applications written for the X Window System, most of them open source and free. You can run X Window System applications on your Mac OS X computer by installing an application called an X server, which gives you access to a wide variety of X Window System software.
ou can use the Mac OS X Terminal application to enter Unix shell commands and to run Unix applications. The name of the Terminal application refers back to the physical terminal devices that were connected to old Unix mainframes. Each terminal consisted of a keyboard for input and a screen for text output. The Terminal application provides the same function, allowing you to enter your commands through the keyboard and to view the output in the Terminal window. The Terminal application comes with the Mac OS X operating system as a utility application. You can find it in the Utilities folder of the Applications folder, by using Finder. Because you are using the Terminal application to run the Unix commands in this book, you want to keep the Terminal handy by setting it to Keep In Dock. This allows you to launch a Terminal window from the Dock with a single mouse-click. You can have several Terminal windows running at once. You can also switch between Terminal windows by using the keyboard shortcuts.
START THE TERMINAL APPLICATION
Go
Each Terminal application runs a separate Unix shell. A shell is an application that sends your commands to the Unix system and provides you with the output of those commands. The shell starts by printing a welcome message, then provides a prompt and waits for you to type a command. The prompt contains the name of your computer and your short username, as follows: [computer:~] user% When a Unix shell command is completed, the prompt appears again. As you provide commands to the shell, the output of your commands moves down the Terminal window. Output that scrolls past the top of the window is not lost forever; you can access it by using the scroll bar on the right side of the Terminal window, or by using the pageup and page-down keys.
Applications
Click Go Applications.
Double-click Utilities.
You can have several Terminal windows running at once. To open a new Terminal window, press + N. To switch between the Terminal windows, press + or + . If you use the scroll bars to scroll back and then type a command, the window snaps back to the current prompt, with the result that you can no longer see the scrolled text. The version of the Terminal application that comes with Mac OS X 10.2, Jaguar, lets you split your Terminal window so that you can keep scrolled text on-screen for reference. To split the window, click the small icon that looks like a broken square in the upper-right corner of the Terminal window. A bar appears, separating the window into two panes. Each pane has a separate scroll bar, and only the lower pane scrolls when you type shell commands. You can change the relative sizes of the panes by clicking the separator bar and dragging it up or down. To return the split windows to only one pane, click the square gray icon in the upper-right corner of the lower pane.
Keep In Dock
Double-click Terminal.
The Terminal window
opens, displaying a welcome message and a prompt.
ou can set the preferences and settings of the Terminal application to meet your particular needs. For example, you can give each Terminal a different name, such as Editing the Config File or Compiling the Server, to remind you of what you are doing in that Terminal; or, if you find the default font size too hard to read, you can enlarge it or change it to a different font. You can access the Terminal application Preferences panel through the Terminal window. This panel allows you to change the command shell that executes when you start the Terminal application. For more information on using other shells, see Chapter 6. You can change the appearance of the Terminal window by selecting the Window Settings option from the Terminal menu. The Terminal Inspector panel appears, allowing you to configure the settings for the current window. There are
CONFIGURE THE TERMINAL APPLICATION
Terminal
seven groups of settings: Shell, Processes, Emulation, Buffer, Display, Color, and Window. You can switch between groups by selecting the group name at the top of the Terminal Inspector panel. Within each group, you can change a number of related settings; for example, the Window settings allow you to control the size of the Terminal window and the title at the top of the Terminal window. Any changes that you make to the Window settings apply only to the current window. However, you can set the current values as the default for all future Terminal windows by clicking the Use Settings as Defaults button. You can save your Window settings by selecting the Save, or Save As, option from the File menu; this creates a TERM file. You can load Window settings from a TERM file by using the Open command from the File menu, thus creating a new Terminal window with those settings.
Window Settings...
The Shell and Processes settings let you determine whether the Terminal window closes when you quit the shell application, and they also help you to avoid accidentally closing windows with active Unix shell commands running. The Emulation settings allow fine-tuning of input and output controls to better emulate, or mimic, a physical terminal device. The Buffer settings control the number of lines that the shell saves as scroll back, and which you can access by using the scroll bars. The Display settings control the appearance of the cursor and the text in the Terminal window. You can change the font or font size, or you can set the text to be anti-aliased. Anti-aliasing uses shades of gray to make the text easier to read, but it can also slow down the display of Unix shell commands.
You can change the color of the Terminal window and text by using the Color settings. The Window settings affect the dimensions of the window and the title that appears in the top bar of the Terminal window. You can set the title to a specific name, or to reflect the current size or running commands of the Terminal window.
File
File
Save As...
My Terminal Preference.t
Click Open.
A Terminal window opens
with a configuration based on your saved settings.
Type a filename.
ou can execute Unix shell commands by typing them directly at the prompt in the Terminal window. These commands allow you to run Unix applications from the shell. You can also run commands that tell you the current state of your shell commands, such as which programs are running or the current location of your Terminal shell in the file folder hierarchy. After typing each command, you must press the Return key to tell the shell that you are done typing. The shell does not run your command until you press Return. This allows you to go back and edit the command before the shell runs it. If you make a typing mistake, you can use the Delete key to back up and erase your mistake, then retype the command and press Return. If you do not notice your mistake before pressing Return, you may get an error message. If you type a non-existent command, such as mistake, Unix returns the following:
ENTER UNIX SHELL COMMANDS
mistake: Command not found. You can recall your last command by pressing the up-arrow key; the exact command you typed appears after the prompt. You can edit the line using the Delete key and then press Return when you have corrected the mistake. This is also a useful way to repeat commands. If you press the uparrow key repeatedly, you can move either back or forward, respectively, through all the shell commands you have typed. The easiest Unix command to type is the w command. This command shows you who is connected to your computer and how long they have been idle. Old Unix machines often had dozens or even hundreds of users connected at once, but you see only one line for each Terminal window you have open.
You enter Unix shell commands through a keyboard, and so they are susceptible to typographical errors. Fortunately, you can set your shell to automatically intercept these mistakes and to make a reasonable guess at what you are trying to type. This helps you to avoid error messages that declare that a command cannot be found. You activate this function by using the set command. To do this, type set correct = cmd after the prompt. After you have activated the function, when you enter a command that does not exist, the shell tries to find a match. It then asks you to reply by typing a y for yes, n for no, e for edit, or a for abort.
TYPE THIS:
[darwin:~] user% ww
RESULT:
CORRECT>w (y|n|e|a)? yes 4:16AM up 3:46, 2 users, load averages: 0.78, 0.80, 0.68 USER TTY FROM LOGIN@ IDLE WHAT user co 4:01AM 3:45 user p1 3:53AM 0 -
Press Return.
The shell executes the w
command.
hell commands in Unix are often cryptic sets of letters strung together, apparently at random. To the uninitiated, they can appear arbitrary, but there are some general concepts that hold them together. Shell commands execute as soon as you type them and press the Return key. The execution consists of two steps:
ANATOMY OF A SHELL COMMAND
First, the shell interprets the command line you have typed and breaks it down into its constituent parts. Second, the shell uses those parts to determine whether a built-in command or an executable program should be run, and then passes the appropriate parameters to the command or executable program.
Each shell command is composed of specific parts, including the command name, options, and arguments. These parts tell the shell which command to execute, how that command should be executed, and what other information on your computer it should use in the execution of the command. You can better understand how Unix reads shell commands by looking at the following example: Simple Command Name The shell breaks down your command into words separated by spaces, and then interprets the commands one word at a time. The first word in the above command is grep, and so, the shell knows to execute the grep command. To save on typing, Unix commands have traditionally been very short words. Some are not even pronounceable words in English, such as the ls, cd, rm, or pwd commands. The word grep can be pronounced, but it seems to have no meaning in English. This is because it is actually an acronym for global regular expression print. That may not help you much, but for now, it is enough to say that the grep command lets you search for text in a file. Options You can type a number of options after the command name; these are strings starting with a hyphen or dash, for example -i. You use these options to force Unix commands to change their behavior. Each command has a unique set of options that you can use with it, and the meanings of these options vary from command to command. For example, with grep the option -i means to match text without regard for letter case, while with rm a command that deletes files the option -i tells the shell to ask the user to confirm each file deletion. Many options are single letters, but some are a single letter and then a value, such as -C2, which stands for the option -C and the numeric value 2. Longer options are often set off with two hyphens, as in --line-number.
grep -i -C2 --line-number "Mac OS X" Documents/to-do.txt This command illustrates all of the components that comprise a shell command, and illustrates how to use multiword arguments by employing quotes.
Arguments After the options in the command line, you can add arguments in the form of filenames or text. The shell command passes these arguments along to the command that you are executing, and they give the command such information as what file or information to look for, or where to store the results of the command when it is done. In the example above, the grep command has two arguments: "Mac OS X" and Documents/to-do.txt. The first argument to the grep command, "Mac OS X", is a specific piece of text that you want to find in a file, and the second argument, Documents/to-do.txt, is the name of that file. Escaping Arguments The quotation marks around the three words "Mac OS X" tell the shell to treat them as one argument rather than three. If the quotation marks are not used, the command line tells the grep command to look for the word Mac in files named OS, X, and Documents/todo.txt. You can use quotation marks whenever you need to include multiword arguments or filenames in your Unix commands. Or, you can type a backslash (\) before each space; this tells the shell not to treat the following space as a word separator.
10
Executable Files Most commands that you enter on the command line are requests to run a program of some kind. The command may be a compiled program originally written in a language such as C++ and now saved on disk as a binary file. It may be a script written in Perl, or it may be a shell script. To be run, a file must be executable. Executable refers to both the contents and the attributes of a file. Built-In Commands Some of the commands you type are built directly into the shell application and do not exist as separate files. These functions include starting and stopping commands, setting shell variables, repeating commands, and moving through the file structure. You can get a full list of the built-in shell commands by typing the command builtins at the shell prompt. One built-in command that is quite useful is the which command. The which command tells you whether a command is a built-in command or an executable file; if it is an executable file, the shell lists the location of that file. The shell locates the executable by searching through a set of locations on your hard drive called your path. The path is a list of folders, also called directories. If you type the name of an executable within one of those folders and press Return, you are running that file as a shell application. By default, your path contains a reasonable set of directories, but you can add other file locations. which Command You use the which command to determine whether a command is built-in or is an executable file. TYPE THIS:
[darwin:~] user% which w
RESULT:
/usr/bin/w
You can see from this output that w is an executable file stored in the location /usr/bin/w.
TYPE THIS:
[darwin:~] user% which which
RESULT:
which: shell built-in command.
This output tells you that the which command is built directly into the shell application.
11
ou can read the Unix manual pages by using the man command. These pages give you a basic summary of how to use a specific Unix command as well as detailed information on the types of parameters you can use with that command.
The simplest way to get information about a given command is to type man commandname. If there is such a command and if there is a manual page for that command, the shell displays the manual page. Because most manual pages are long, only the first screen of information displays in your Terminal window; to continue on to the next screen, you can press the Spacebar. You can continue pressing the Spacebar for each screen of information until you have read the entire manual page. A manual page first lists the name of the command, and in parentheses, the section number of the manual where you can find that command. Some commands or terms appear
READ THE UNIX MANUAL
in several sections, and you can select from among them by including the section number before the term. After the name of the command, a synopsis of the syntax for the command appears. Parameters in brackets are optional, but if you use them, you must replace the underlined words with an appropriate value or filename when you type the command. A manual page also includes a description of the command and often provides examples of how you can use it. Related commands also appear along with section numbers, and any files that relate to the command, such as configuration files, are shown. Extra bits of trivia, such as the history of the command or known bugs, may also appear.
It is quite common for Unix computers to ship without a printed manual explaining the Unix shell commands, and your Mac OS X computer is no exception. Decades of Unix users have relied upon the man command for instructions on the proper use of Unix commands. As heir to their legacy, you may sometimes find yourself consulting the manual pages to decipher obscure error messages. Therefore, you should be familiar with how to use the man command. You will find that only reading a manual page is not enough; you also need to understand what it is trying to tell you. This can be difficult, as most manual pages seem complex at first glance, having been written for a very technical audience of Unix system administrators. The key to understanding manual pages is to read enough of them so that you begin to absorb the concepts through familiarity. Use keyword searches and look up related commands and terms that you do not understand. Reading manual pages requires practice, but it is worth the effort.
You can become familiar with the man command by trying some of the commands.
Example:
[darwin:~] [darwin:~] [darwin:~] [darwin:~] [darwin:~] user% user% user% user% user% man man man man man man apropos whatis manpath tcshb
Some of the resulting man pages can be very opaque; so do not worry about anything you cannot immediately understand. For example, the man page for tcsh is extremely long.
13
hen you are done typing Unix shell commands, you can exit your shell and close the Terminal window, or exit the Terminal application. To do this, you can simply click the red Close button in the upper left-hand corner of each Terminal window. Alternatively, you can choose Close Window from the Window menu or Quit Terminal from the Terminal menu. However, these are not necessarily the best ways to shut down a shell window. This is because Unix shell commands can often continue to run in a Terminal window even if they do not appear on the screen, or seem to be doing nothing. When you close the window, you also terminate the shell application that started those commands, and as a result, you often terminate the commands as well.
EXIT THE TERMINAL WINDOW
For this reason, it is best to use the exit command to end a shell in a Terminal window. The exit command ends the shell, but leaves the Terminal open. After you quit the shell, you can close the window manually by clicking the red Close button in the upper left-hand corner of the Terminal window. You can change this behavior in the Window settings for Terminal by setting the windows to close automatically when the shell ends. If you close a Terminal window without exiting the shell, you probably do not do any serious harm if no shell commands are running. The Terminal application tries to prevent problems by warning you if you close a window that contains a running command. You can choose to continue closing the window, or cancel the window closure.
14
The Terminal application maintains a list of commands that it terminates if you close a Terminal window while those commands are running. Those commands are rlogin, slogin, telnet, and ssh. Each of these is an application that lets you connect to another computer and run commands as if you were sitting at that computer.
You can add or remove applications from the list of commands that the Terminal application automatically terminates when you close a window in the Terminal Inspector window; the list is found in the Processes group of settings. Click the name of the application and then click the Remove button. If you need to add an application to the list, simply click Add and type the name of the application. Be sure to click Use Settings as Defaults to save your Window settings. You can also set the Terminal application to prompt you each time you attempt to close a window without typing exit first; or you can set it to never ask you. If you often connect to another computer via telnet or ssh secure shell you may want to remove those applications from the list to avoid accidentally disconnecting.
Terminal
Window Settings...
Click Terminate to close the window and end all of the commands for this window.
The Terminal window
closes.
In a new Terminal window, click Terminal Window Settings. Click Shell from the scroll-down menu. Click the Close the window radio button.
To apply this configuration to all Terminal windows, click Use Settings as Defaults. Click the red Close button to close the Terminal window.
The Terminal window
closes.
15
LIST FILES
hen you are working in the Unix shell, everything is represented by a file within the file-based structure. The file structure is composed of directories, which are special types of files that can contain other files, including other directories. The commands you type are files as well called executable files with the exception of those commands built directly into the shell application. In fact, your shell itself is an executable file. If you are familiar with the Mac OS X operating system, you are also familiar with the file-structure concept everything is stored in folders. The folders of the Aqua interface are the directories of the shell interface folders and directories are interchangeable terms. The term directory has it roots in Unix, while the word folder comes from the Mac OS graphical interface lineage. Each file within a directory has a unique name. These names can contain letters, numbers, symbols, and even spaces, meaning you can have multiword filenames. However, if
your filename contains spaces or punctuation symbols beyond a period, underscore, or dash, you need to place quotation marks around that filename when you specify it in a shell command. When you open a Terminal window, your shell opens in a specific directory known as your Home directory. This is unique to each user on your computer, and Unix uses your Home directory to store the files, which you create using the various programs you run. The command ls shows you the contents of the current directory in which you are working. You can use the option -F after the ls command to add an additional marker to indicate each type of file. A forward slash (/) after a filename indicates a directory and an asterisk (*) indicates an executable file.
LIST FILES
16
ou can use the -A option with the ls command to list hidden files. Computers do not always display all files to the user. They do not do this to deceive you, but rather to help reduce the visual clutter in file listings. Hidden files are usually special files, set apart from the files that Unix users create and update. They may be configuration files or files that establish your shell environment. However, there are times that you may need to see a listing of all of your files, both hidden and normal, while working with Unix. Unix hides files by giving them a filename starting with a period (.). Most commands, including the ls command, ignore these files. You cannot see them in a normal file listing. They also do not appear in the Mac OS X Finder. However, you can list them along with the visible files by using the ls -A command.
You can make it more obvious which files are directories by combining the -A option with the -F option. When you type the command ls -A -F to get a listing of all files, a forward slash (/) appears after each directory name. You can also combine these options together and type the command as ls -AF. This command lists hidden files and highlights directories at the same time. You can run the ls command with an argument specifying the name of a file or directory. If you give a directory name, you see a listing of the contents of that directory. If the argument is an ordinary file, only the name of the file appears. If you specify a filename or directory that does not exist, the ls command tells you that there is no such file or directory.
17
directories that reference that file. These references, also called links, include the directory containing the file itself, so each file has at least one reference. For directories, the reference represents the number of files within each directory. The third and fourth columns show the user and group associated with the file. The fifth column shows the size of the file in characters or bytes. The sixth column shows the date and time the file was last modified. The final column shows the name of the file. If you want to examine an individual file, you can give the filename as an argument to the ls -l command. Using the ls -l command on a directory lists the contents of the directory, although you can use the -d option to request the attributes of the directory without the directory contents.
18
This directory can be read by the owner, the members of the group staff, and anyone else using the computer. Only the owner can write to the directory; however, anyone can move from directory to this directory.
19
COPY A FILE
ou can copy files with the cp command. This command allows you to save backups of important files or keep old versions of files while you edit them. Making copies of important files before editing them is a good practice because it assures that you can go back to the original. To copy a file, you supply two arguments to the cp command: the first is the name of the original file, and the second is the name of the new file. You do not have to own the original file to copy it, but you must have permission to read it. You also need write permission in the directory to where you make the copy. Your cp command should look like this: cp original-file copy-file
If copy-file is an existing directory, the copy will be placed in that directory and will be named the same as the original-file. Copying a file can be dangerous if the file already exists with the same name you specify for the copy. In such a case, you write over the existing file with the new copy. The cp command does not automatically warn you, but copies the file, assuming that you want to overwrite the existing file. To ensure that you do not accidentally write over a file, you can use the -i option with the cp command, so that it asks you to confirm that you want to write over the existing file. If you do, you can type y for yes and press Return; if you do not, you can press any key to cancel the process.
COPY A FILE
CREATE A COPY
The cp command either copies the file or abandons the operation, depending on your response.
20
ou can include a pathname to indicate a location outside of your current directory when you give a filename as an argument to a command such as cp. The file system of your Mac OS X computer is set up as a
USING PATHNAMES
hierarchy of folders containing files and other folders. Each of these folders corresponds to a directory. You can view the folders in the Mac OS X Finder application, or access them as directories through the Unix shell.
A pathname specifies the place in which you can find a file, just as an address tells you where to find someone in the physical world. For example, one might describe his current location by saying that he is on the planet Earth, in the country known as the United States of America, in the state of California, in the county of Orange, within the city of Fullerton, on Wilshire Avenue, in building number 110, on the Garden Level, in suite G-1, in the back office, at the desk of Kynn. A file, on the other hand, might say that it is on a hard drive, in the Users directory, in the kynn subdirectory of Relative and Full Pathnames The desk of Kynn is in an office that also contains the desk of Laura. If you are going to describe the location of Laura, you can just say the desk of Laura and not spell out everything starting with the planet Earth. This is a location relative to the desk belonging to Kynn. In the same way, you do not need to specify a full pathname if you are already in the same directory. For example, if you are working with files in the /Users/kynn directory and you want to copy the Chapter 02.doc file described above, you do not need to type the full pathname, only this: [ferro:~] user% cp Documents/"Chapter 02.doc" backup-ch2.doc This creates a copy of the file with the new name backup-ch2.doc. Note that this is in the /Users/ kynn directory, not in the Documents directory. Aliases for Special Pathnames Three pathnames refer to special directories. The alias dot (.) refers to the current directory in which you are working. The alias dot-dot (..) refers to the parent directory the directory which contains the current
the Users directory, in the Documents subdirectory of the kynn directory, and that it has the filename Chapter 02.doc. You can write that pathname as /Users/ kynn/Documents/"Chapter 02.doc". When writing the pathname, you must separate each directory name with a forward slash (/). In addition, because the filename contains a space, you must enclose it in quotation marks to refer to it in Unix.
The start of the Unix file system is the root directory, and you indicate it by an initial forward slash (/). A pathname beginning with a forward slash is therefore a full pathname, and is relative only to that root directory. Starting the pathname with the root directory is like starting with the planet Earth when telling someone where you are; the root directory corresponds to the Macintosh HD icon on your desktop in Finder. You use full pathnames to reference files that are outside of the directory in which you are currently working. For example, to copy a file in the /usr/share/dict directory to your own directory, you can type: [ferro:~] user% cp /usr/share/dict/ propernames name-list.txt
directory. The alias tilde (~) refers to your Home directory, where you store your personal files. If you give the name of another user immediately after the tilde, then it refers to the Home directory of that user.
21
RENAME A FILE
ou can change the name of a file with the mv command. In Aqua, renaming files and moving files are two different functions. You move a file in Aqua by dragging it to a new location, and you rename it by clicking the name field of the file and typing a new name. However, within Unix, when you rename a file, you are simply moving the file to a new place within the file system; even if you are within the same directory, you are moving the file to a new name. However, if you move a file to another file that already exists, you write over that second file. This is not a good practice unless you are certain that you want to overwrite the second file.
To avoid this problem, you can use the -i option with the mv command. If moving your file will overwrite another file, the shell asks you to confirm that you want to proceed. If you do, you can type y for yes, or any other key for no. To be safe, you should make a habit of using the -i option with the mv command. You can also set up a shell alias to automatically use the -i option with the mv command. You can use the mv command to move a file from one location to another. When you move a file with a command such as mv file /directory, the resulting file retains its original name, but resides in a different directory. It is only when you move a file to both a new location and filename that you rename the file.
RENAME A FILE
RENAME A FILE
The mv command either renames the file or abandons the operation, depending on your response.
22
DELETE A FILE
ou can use the rm command to delete files you no longer want to keep. When you delete a file using the Mac OS X Finder in Aqua, the Finder does not immediately delete the file, but stores it in the Trash. However, when you delete a file using the rm command, the file completely and instantly disappears. This means that if you mistakenly delete a file from the shell, you cannot recover it by simply dragging it back out of the Trash. As with the cp and mv commands, deleting files can be dangerous because people can make mistakes. You can use the -i option to tell the rm command to confirm that you want to delete a file; if you do, you can type y for yes, and press Return. If you do not, you can press any other key or simply the Return key.
DELETE A FILE
By default, the rm command only removes ordinary files, although you can remove an empty directory with the rmdir command; for a directory containing files, you can use the rm r command. You cannot remove directories unless they belong to you or you have write permission to the files. However, there is no special access permission required to delete a file. It is possible to delete a file whose name begins with a dash, such as -foo or -bar. These are extremely hard to remove, because the rm command tries to interpret the filenames as an option, because options begin with dashes. In this situation, you can use the option -- (a double dash). This means that the command does not check the rest of the line for more options, making this your last option flag.
DELETE A FILE
The rm command either deletes the file or abandons the operation, depending on your response.
23
ou can change the permissions on files you own, allowing you to grant or withhold permission to others to read, write, or execute your files. There are two parameters for the chmod command, the first being the new mode, and the second being the file you want to change. You specify the mode change by indicating who the change affects, whether the change should be to add, remove, or set permissions, and what kind of permissions you want to set.
one set of users by combining these designators together, such as go, to indicate users in the file group and users not in the file group, while omitting the file owner. You can mark permission changes with a plus symbol (+) to add permissions, a minus symbol (-) to remove them, or an equal symbol (=) to set them. The possible permissions are the same as those shown by the ls -l command: r for read access, w for write access, and x for execute access. You can make more than one change at a time to a given file by listing them with commas as separators. For example, to set the file example to be readable, writeable, and executable by you, readable and executable by those in the file group, and readable by those outside of the group, you can type chmod u=rwx,g=rx,o=r example.
Unix uses letters to designate the users that your mode change affects: u, for the owner of the file, or user, g, for users in the file group, o, for others users not in the group or a, for all users. You can designate more than
24
You can change the permissions for an entire directory and its contents, including your Home directory, by using the -R option with the chmod command. The -R option dictates that modes should be changed recursively, which means that the changes apply to all files in that directory or in its subdirectories. For example, if you want to make sure your Home directory is readable only by you and not by other users of your computer, you use the chmod R command.
TYPE THIS:
[ferro:~] user% chmod -R go-rx ~ [ferro:~] user% ls -l
RESULTS:
drwx-----drwx-----drwx-----drwx-----drwx-----drwx-----drwx-----drwx-----8 12 22 3 3 3 4 5 user user user user user user user user staff staff staff staff staff staff staff staff 272 408 748 102 102 102 136 170 Nov 13 13:57 Desktop Nov 13 02:00 Documents Nov 13 03:40 Library Nov 4 13:49 Movies Nov 4 13:49 Music Nov 4 13:49 Pictures Nov 4 13:49 Public Nov 4 13:49 Sites
Note: You cannot alter this file without changing the permissions back.
25
ou can use wildcard characters to avoid having to type out the full name of each file you want to work with in Unix. This not only saves typing but also lets you refer to multiple files with similar names in a single command. Unix shell wildcards are also called glob-patterns, and the use of these wildcards is known as globbing in Unix jargon. You can use these wildcards whenever you give a filename argument to a shell command. The asterisk wildcard (*) matches any sequence of zero or more characters in a filename. The question mark (?) matches any single character. A range of characters in square brackets, such as [a-m], matches any single character within that range. Keep in mind that letters in filenames are case-sensitive, so while the letter d is a match for [a-m], the letter D is not, because it does not come between lowercase a and m.
SELECT FILES USING WILDCARDS
A caret (^) at the start of a pattern or a range of characters indicates that the pattern should select those characters that do not match the given pattern. For example, if you want to use the ls -l command on all directories and files that begin with the letter P, you can type ls -l P*. To remove all files beginning with A, followed by three letters, and ending in .doc, from your Documents directory, you can type rm -i Documents/A???.doc. You should always use the -i option with the rm command if you give it wildcard arguments, to avoid deleting the wrong files. A careless rm * command in the wrong directory can remove the contents of the directory. Hidden files are resistant to being identified through wildcards. The command ls *, for example, does not list them while ls .* lists only hidden files.
command on the files in the current directory, except for those specified by the wildcard pattern.
Type ^ followed by the wildcard pattern matching the files you do not want to select.
26
ou can easily specify filename arguments by using command completion, which is a special function built into the shell. To use filename completion, you must type out the first part of the filename and then press the Tab key. If there is a file that matches the incomplete filename, the shell fills in the full filename for you. If no file matches the filename, your shell program emits a beep, indicating that there is not a match. If more than one file matches, the shell program fills in as much as it can and then emits a beep, while waiting for you to enter more text to differentiate between the files that match the pattern up to that point and then differ. At this point, you can either type out the rest of the command line and press Return, or type enough of the command line to uniquely identify the file you want to access, and then press Tab again.
To see the results of an ambiguous match, you can press Control + D after the beep. Alternatively, you can type set autolist, which instructs your shell to list the remaining choice whenever file completion fails. This is a good command to save in your .tcshrc file, which ensures that this feature is set every time you start a Terminal window. Similarly, you can turn off autolist with unset autolist. You can combine filename completion with full or relative pathnames as well; if you type a partial pathname and press Tab, the shell lists the options within that path. Using filename completion can save you a lot of typing as well as making it less likely that you mistype any characters.
Press Return.
The shell executes the
command.
27
ou can locate files by their names or other criteria by using the find command. This command tends to be faster than the Mac OS X Sherlock application for locating files, especially those that are used by the system or otherwise hidden from the Finder. The find command is a complex and very powerful utility that lets you run many different types of searches and perform a variety of actions on the files that it finds. However, the most common use for the find command is simply to locate files with a certain name and print out their locations. The basic syntax for the find command is: find pathname -name filename -print The first parameter, pathname, is the directory where you want to search. The filename is the name of the file for
which you are looking. The argument -print tells the find command to display the location of the file. You can also give a wildcard pattern instead of a filename, and the find command lists all files that match that pattern. When you use wildcard patterns in this way you need to enclose them in quotation marks. For example, if you save a Word document but you do not keep track of what folder you save it in, you can use the find command to locate all the .doc files in your Documents directory: find ~/Documents -name "*.doc" -print This displays a list of all file locations matching the pattern. If you want to see a full file listing instead of the relative pathname for the files found, you can replace the print command with the ls command.
28
In addition to searching by name or wildcard pattern, you can also search by other qualities of the file, such as the last time the file was changed, the owner of the file, or the permissions of the file. You control the search with the arguments you include after the pathname of the directory. ARGUMENT -group groupname -iname filename -mmin minutes -mtime days -perm +filemode -size charsc SEARCHES FOR
Files belonging to a certain group. Like -name, but matches regardless of case. Files modified within a certain number of minutes. Files modified within a certain number of days. Files that have specific permissions set. Files that are an exact size in characters.
find command and prints the file location for each file matching the wildcard pattern.
29
ou can change your current directory by using the cd command. Each shell window operates in a specific location within the file structure, and you can view this location by typing the pwd command. The pwd command is Unix shorthand for print (display) working directory. The current working directory is the directory from which relative pathnames are computed and the default directory in which files are found or saved. If you type cd alone, it returns you to your Home directory. If you provide the cd command with a pathname argument, either relative or full, you change to that directory. You can change your current directory to any directory that grants you execution access permissions. This allows you to explore nearly all of the directories on your hard drive, with the exception of a few system directories that are protected.
When your current directory changes, your prompt changes as well, to reflect the new location. Your prompt displays the names of up to three directories above your current location, or fewer if you are close to the root directory. For example, if you are in the directory /usr/share/ tcsh/examples, on a computer named ferro, your prompt looks something like this: [ferro:share/tcsh/examples] user% You can use wildcards and filename completion with the cd command; it accepts special directory names such as cd .., to go up one directory level, and cd ~user, to change to the Home directory of the user user. You can also use the cd - command to return to the last directory in which you were working.
30
31
CREATE A DIRECTORY
ou can use the mkdir command to create new directories. Directories are useful for organizing your files into a logical structure. When you create a directory in the Unix shell, you can access it through the Mac OS X Finder as a folder; conversely, when you create a folder in the Mac OS X Finder, you can access it as a directory in the Unix shell. The arguments that you give to the mkdir command affect how the command creates new directories. When you create a directory with a space in the name, you must enclose it in quotation marks, unless you want to create several directories at once. To create a directory, you need to have write permissions for the current directory or the directory in which you are creating the new directory. For example, if you want to
CREATE A DIRECTORY
create the directory /usr/local/resp, you must have write access to the /usr/local directory. You can either change your working directory to the /usr/local directory using the cd command and type mkdir resp, or you can type mkdir /usr/local/resp from any current directory. When you give a pathname, whether relative or full, the intervening directories must exist. If they do not, you receive an error message, and the directory is not created. You can tell the mkdir command to create any necessary directories by using the -p option. For example, to create the directory ~/Documents/by-date/2003/03, you can type mkdir -p ~/Documents/by-date/2003/03. This command creates the by-date and 2003 directories as well as the 03 directory if they do not already exist presumably, the Documents directory already exists in your Home directory.
CREATE A DIRECTORY
32
By default, anyone on the system can read and execute any directories you create, which means that all users of your computer can change to the new directories and list their contents. If you do not want universal access to your files or directories, you can change the directory permissions by using the chmod command, or you can instruct the mkdir command to set the file mode automatically by using the -m option. When using the -m option, you follow it with the file mode you want to set, as with the chmod command.
Example:
[ferro:~] user% mkdir -m go-rwx Private [ferro:~] user% ls -lad Private drwx 2 user staff 68 Nov 20 17:03 Private
33
DELETE A DIRECTORY
ou can remove unwanted directories by using the rmdir command. One use for this command is to remove extraneous directories that make it harder to locate files you actually need.
While you can use the rm command to delete normal files, you cannot use it to delete directories. This is a safety measure to prevent you from accidentally deleting a directory that might contain useful or important files. To delete a directory, you must use the rmdir command. The argument given to the rmdir command is the name of the directory, or directories, that you want to remove. If that directory is empty, then the command removes it. If the directory is not empty, then a message appears, stating that you cannot remove the directory. In such a case, you can go into the directory and remove any existing files using the rm command, or any
DELETE A DIRECTORY
subdirectories using the rmdir command. You can now remove the directory. Sometimes apparently empty directories contain hidden files such as .DS_Store, which is a Mac OS X system file and you need to locate them with the ls -A command and remove them before removing the directory. While you are not allowed to remove the current directory using the rmdir command, you may be able to remove it indirectly. For example, if you are in the subdirectory foo of your Home directory, you can type rmdir ~/foo. However, this is not generally a good idea, because you can end up stuck in an unresponsive non-directory where you cannot even use the ls command to list the directory contents. You can use the cd command, with no arguments, to return to your Home directory.
DELETE A DIRECTORY
Type rm -i * and press Return. Type y and press Return for each item that you want to delete from the directory. Type ls F and press Return to confirm that the directory is empty.
The directory is empty.
Type cd, a space, and the name of the non-empty directory. Press Return.
Note: You may want to use the ls command to view the contents of the directory before you delete it.
34
Note that in the second line above, the user probably means to type ~/Extra, but accidentally puts a space before the word Extra. This is a costly mistake, as it means that the rm command deletes the Home directory of the user.
Note: You may need to find and delete hidden files if you see an error that says the directory is not yet empty.
35
ou can move files into or out of a directory by using the mv command. This is the same as dragging a file in Finder to a new folder location. The mv command can rename a directory just as it renames a normal file, but it can also move the location of a file or directory within the file structure. You can use the mv command to move a file, or directory, by typing a command like this: mv file location The argument location must be a directory. Either this directory exists and is owned by you, or you must have permission to write files in the directory. If you type the name of a directory that does not exist, you will not see an error; the file will be renamed to the second name you typed. This can also happen if you mistype the name of the directory.
MOVE FILES INTO A DIRECTORY
You can move multiple files using the mv command, however, they must all go into the same directory. To do this, you can simply type out each filename and specify the destination as the final argument, as follows: mv fileOne fileTwo fileThree andSoOn location This command moves all of the files that you list to the location that you specify. If that location does not exist as a directory, an error message appears, and the command does not execute. Using the -i option with the mv command can prevent you from accidentally overwriting files when you move them.
Type ls F and a space followed by the name of the directory, and press Return.
The shell shows the files in
the new directory.
36
COPY A DIRECTORY
ou can use the cp command to make a copy of a directory by using the -R option. Individual files can be copied using the cp command with no options, and as with the mv command, you can give a list of files and a destination directory in order to copy a number of files into the same directory: cp fileOne fileTwo fileThree andSoOn location You can use wildcards to copy files. For example, to copy all of your .doc files into your Documents directory, type cp *.doc ~/Documents.
However, if you try to copy a directory as you would copy a file, you see an error message because directories are not normal files: [ferro:~] user% cp Documents "Backup of Docs" cp: Documents is a directory (not copied). To copy a directory, you must use the -R option, which tells the cp command to copy the directory and its contents to the new location. For example, to create a copy of the Documents directory, you can type cp -R Documents "Backup of Docs". This will copy the entire directory at once, creating the new directory and duplicating all of the files. The names of the original files will be the same, although the directory names will be different.
When you copy files into a directory, the new versions of each file will be named with their original names. The directory needs to exist, as the cp command will not create a new directory for you. You can use the mkdir command to create the directory first.
COPY A DIRECTORY
Repeat the ls F command in step 4 to show the contents of the new directory. 37
ou can use the du command to display the size and contents of a directory. The name of the du command stands for disk usage, and it tells you how much space each file or directory uses on your hard drive. This information is also available from the Finder using the Get Info menu option. When you use the ls -l command, you see a value for the size of the directory just as you do for other files. However, this value does not represent the size of the contents of the directory; it represents the size of the directory entry itself, a list of the files stored in the directory. To obtain the size of the contents of the directory, including subdirectories, you can use the du command.
directories or files. Additionally, the space used by all subdirectories also appears, along with subdirectories of subdirectories. This can make the output of the du command quite extensive and hard to read; if you want a single answer to summarize the size of a directory, you can use the option -s with the du command. When the du command displays sizes for files and directories, it measures these sizes in disk blocks; a block on a Unix file system disk represents 512 characters. This is an easy number for computers to work with but somewhat difficult for us humans to grasp. You can use the option -k to make the du command list sizes in kilobytes, which are units of 1,024 bytes.
If you type du alone, you get a listing of disk usage in the current working directory; if you give one or more arguments, you see the space taken up by each of those
38
You can use the df command to check the total disk usage on your computer. Like du, df measures sizes in 512-character blocks, but you can use the -k option to make the results easier to read. The df -k command lists all file systems on your computer, and gives you a percentage indicating how full your disk is.
Example:
[ferro:~] user% df -k Filesystem 1K-blocks /dev/disk0s5 5865644 devfs 90 fdesc 1 <volfs> 512 automount -fstab [314] 0 automount -static [314] 0 Used 4027644 90 1 512 0 0 Avail 1779344 0 0 0 0 0 Capacity 69% 100% 100% 100% 00% 100% Mounted on / /dev /dev /.vol /Network/Servers /automount
The last five file systems in the above list correspond to internal systems used by the Unix operating system. You can safely ignore them and only look at the first listing. According to this listing, the above computer has a single disk that is 69 percent full.
Type a directory or
filename and press Return.
39
ou can display the content of text files with the cat command. The name cat is short for concatenate, which means to join several things together into one. However, the cat command has additional functions beyond concatenation, one of which is to display files on-screen. You can display any file by typing this command: cat filename The screen displays the full contents of the file. If the file is longer than one screen, your Terminal window scrolls to display the whole file. The two types of files that you can display using the cat command are text and binary files. A text file consists of ordinary letters, numbers, spaces, and punctuation, collectively known as plain text. If you are using a wordprocessing program and you save the file as text, you are creating a text file.
VIEW TEXT FILES
The other type of file that the cat command can display is a binary file. Binary files contain special characters that you cannot print, because the computer codes for these characters do not correspond to any printable symbols. The executable files that programmers create from compiled applications are often binary files, as are proprietary data formats such as Microsoft Word documents. If you try to use the cat command to display a binary file, the best that you can expect is gibberish in your Terminal window. The worst result is that it resets the display format of your Terminal window, meaning that your prompt and any letters you type also appear as gibberish. To display the contents of a binary file safely, you can use the -v option with the cat command. This command displays non-printable characters by showing a caret (^) before control characters, and M- before Meta characters.
This is an example of a
40
ou can create a text file by using the cat command and redirecting the output to a file. If you type cat and press Return, the cat command appears to do nothing, but your prompt does not reappear. When you type something else and press Return, you just see whatever you typed echo back at you. This means that the cat command is letting you enter content. You are building a virtual file that only exists for the execution of the command. As long as you continue to type, you are adding content to that virtual file. To indicate that you are finished entering text into the cat command, you must indicate the end of your virtual file. You do this by pressing Return and then pressing Control + D. By itself, the ability to type text and see it reappear on-screen is not particularly useful. However, you can combine the cat command with output redirection to
make simple text files. Output redirection means that you save the results of a command to a file instead of displaying them on-screen. To redirect the output of the cat command to a file, you can type the following: cat > filename This creates a new file called filename. For better compatibility with the Mac OS X Finder, you may want to name a text file with the extension .txt. This allows you to double-click the icon for the file in Finder and open it in the TextEdit application. The contents of the new file are whatever you type after pressing Return. The file can contain multiple lines; just press Return at the end of each line. When you are done, you can press Control + D to create the file.
Press Control + D.
The cat command creates a file containing the text you typed.
Press Return.
41
If you try to use the less command on a binary file with unprintable characters, the less command warns you and asks if you want to continue. You can type y, for yes, and press Return, or simply press Return to cancel the less command. You have already used the less command if you have used the man command; when you type man, you read a manual page by viewing it as you would with the less command. The name of the less command makes sense when you know the history of pager commands in Unix. The original command for displaying a page at a time was named more, because, while waiting for you to read the page, it printed --More-- on the bottom line of the Terminal window. The less command was named as a natural successor to the more command, because it could do more than the more command could do.
The less command displays the first page of the content of the file.
42
In addition to pressing the Spacebar to page through a file using the less command, or the man command, you can also use other keystrokes to move through the file. For a full listing of keystrokes in less, type man less or type h while using the less command. KEYSTROKE
Return Down arrow Up arrow
MEANING
Go forward one line. Go forward one line. Go back one line. Go back one page. Search backwards in the file. Go to the first line of the file. Go to the last line of the file. Open the file in a Unix text editor. Read the less command help. Quit immediately.
b ?pattern g G v h q
the lower-left corner of the Terminal window, beside the forward slash.
The less command skips ahead to that word or phrase and highlights it.
43
ou can display a portion of a text file by using the head and tail commands. To understand how the head and tail commands work, it is useful to visualize a text file as if it were a fish being chopped into head, tail, and body. The head command displays the portion of the fish containing its head, and the tail command shows the portion containing the tail of the fish. You can give additional options that indicate where along the body of the fish you want to cut.
head -linenumber filename tail -linenumber filename For example, type head -3 /usr/share/dict/words to see the first three lines of the file /usr/share/dict/words. Several Unix programs use this text file as a source of English words, so it makes a good example for text commands. Typing tail -3 /usr/share/dict/words shows you the last three lines of this file. You can also tell the tail command to start a certain number of lines in from the beginning of the file by including a plus symbol: tail +linenumber filename If you want to view the tail of the words file starting at line 234,567 it is a large file you can type tail +234567 /usr/share/dict/words.
Without any options, the head command shows the first ten lines of a specified file and the tail command shows the last ten lines. If the file has ten or fewer lines, the whole file displays. You can change the number of lines that display in the following way:
44
You can also set the tail command to display any new lines added to the end of a file, by using the -f option. The Mac OS X operating system maintains a number of files known as log files. These files record system activity, much of it invisible to the user, which you can use to diagnose problems or monitor processes. New lines are regularly appended to log files. You can find most of the important system logs in the /var/log directory. You can monitor these log files by using the tail -f command. To stop monitoring these files, press Control + C.
Example:
[ferro:~] user% tail -5 -f /var/log/system.log Dec 2 16:40:03 ferro configd[105]: executing /System/Library/SystemConfiguration/Kicker.bundle/Resources/restart-AppleTalk Dec 2 16:40:03 ferro lookupd[533]: lookupd (version 272) starting - Mon Dec 2 16:40:03 2002 Dec 2 16:40:05 ferro root: setting hostname to ferro.local. Dec 2 16:40:05 ferro configd[105]: executing /System/Library/SystemConfiguration/Kicker.bundle/Resources/set-hostname Dec 2 16:40:06 ferro root: setting hostname to ferro.local. ^C [ferro:~] user%
45
around your regular expression pattern with the grep command. Options for the grep command include -i, which makes grep consider upper- and lowercase letters the same for matching purposes; -v, which inverts the search and lists lines that do not match; and -l, which does not display matches but instead lists the names of files whose contents contain the regular expression pattern. A simple but useful example of the power of the grep command is that it can help you with crossword puzzles or crossword-style games such as Scrabble. Using the list of English words in /usr/share/dict/words, you can display all lines matching a specific pattern. For example, if the first letter in a four-letter word is k, the third is n, and you do not know the rest, you can use this command to display all possible matches as show below: grep -i '^k.n.$' /usr/share/dict/words
press Return.
46
Regular expressions consist of ordinary text and characters with special meanings. The simplest regular expression is just plain text, such as Kynn. This matches any line that contains the word Kynn anywhere on the line. To select matches at the beginning of a line, you can use the special character caret (^). The regular expression to match lines starting with Kynn is ^Kynn. Likewise, the dollar sign ($) indicates the end of a line, as with Kynn$, which only matches lines where Kynn is the final text of that line.
A period (.) matches any character. A set of characters in square brackets, such as [0123456789ABCDEF], matches any of those characters, and a range in brackets matches any character within that range, such as [a-zA-Z]. To match more than one character of the same type, you can use the plus symbol (+) after a special character, normal character, or range. To match zero or more of the preceding types of characters, use an asterisk (*). The regular expression '.*' matches anything, because it is zero or more of any character. A question mark (?) indicates zero or one repetition of the preceding character.
The grep command displays all lines that do not match your pattern.
47
ou can save the text output of any shell command by redirecting the output to a file. Unix shell commands normally display their output in the Terminal shell window, immediately after you type the command. This display method is known as standard output. Using output redirection, you can change the destination of the standard output; it does not have to appear in the Terminal window. To save the output of a command into a file, you can use a greater-than symbol (>): command and arguments > output-file
information at any given time. For example, if you want to record your disk usage on a certain date, you can type command du -s > du-2003-03-05. When you redirect text, the shell does not print any special messages on-screen; after you complete the command, you only see the prompt again. You can use other commands, such as cat, grep, or head, to examine the text file that you create. You can combine output redirection with the cat command to create a new file from two or more files. You do this by using the following command: cat filename1 filename2 filename3 > composite-file The new composite-file consists of the text contained in each of the named files, in the order listed on the command line. You can concatenate as many files as you like.
For example, to save the output from the command grep 'Apple' CHANGES.txt into a file named applechanges.txt, you can use this command: grep 'Apple' CHANGES.txt > apple-changes.txt You can use the grep command to record the output of a command for later processing, such as editing or printing the file. It is also an effective way of making a record of
REDIRECT TEXT TO A FILE
Type a greater-than
symbol and a space.
Type a Unix shell command that displays text output, and a space. 48
If you redirect output to an existing file, you overwrite that file with the new text output. This can be dangerous, because indiscriminately overwriting files can lead to loss of data. You can instruct the shell to prevent output redirection from overwriting existing files by typing the command set noclobber. The shell prints an error message saying that the destination file exists, and the command does not execute. If you have the noclobber command set and you need to overwrite an existing file, you can type an exclamation point (!), or bang, after the greater-than symbol. This causes the redirection to occur even if the file exists.
Example:
[ferro:~] [ferro:~] [ferro:~] log: File [ferro:~] [ferro:~] user% head /var/log/system.log > log user% set noclobber user% tail /var/log/system.log > log exists. user% tail /var/log/system.log >! log user%
Type a greater-than
symbol, a space, and the name of the file you want to create.
The cat command concatenates the file and saves the output in the file you create.
Press Return. 49
ou can chain commands together by sending the output of one command as input to another. This is known as piping, and is an alternative way to use standard output. Instead of displaying on-screen or saving to a file, the standard output from one command becomes the standard input for another command. The second command runs using the output from the first command, and produces its own standard output, which you can then display, redirect to a file, or pipe to another command. This technique gets its name from a special character called the vertical pipe (|). On Apple keyboards, you create this character by holding down the shift key and typing a backslash (\). The syntax for a pipe command looks like this: first command and arguments | second command and arguments
command. Some commands do not automatically read standard input. For those commands, you must read the manual pages, but the most common way to indicate that a command should read standard input is to use a single dash (-) as an argument. Piping is similar to redirecting output to a temporary file and then applying a second command to that file, but it cuts out the middleman. For example: [ferro:~] user% log.tmp [ferro:~] user% Dec 2 16:40:06 to ferro.local. [ferro:~] user% [ferro:~] user% tail /var/log/system.log > grep 'ferro.local' log.tmp ferro root: setting hostname rm log.tmp
You can link together as many commands as you want to using pipes. Most commands that work with text, such as head, tail, grep, and others, automatically accept standard input if there is no filename given to the second
CHAIN TEXT COMMANDS TOGETHER
You can accomplish the same result with a single command line: tail /var/log/system.log | grep "ferro.local"
50
You can chain together commands using the backtick ( `), a left-leaning single quote character found in the upper-left corner of your keyboard. You use the backtick to take the output of one command and provide it as an argument to another command. You write the second command normally, but where you want to insert the output of the first command, you enclose it within a pair of backticks. For example, to see the size and permissions of the executable file for the less command, you type ls -l `which less`. This input executes the which command, which returns a full pathname to the less command, and then runs the ls -l command with that pathname as an argument. To move all files containing the word obsolete to a subdirectory, type mv -i `grep -l 'obsolete' *.txt` old-files/ This input executes the grep -l command, which displays a list of files containing the search pattern, and that list is used as a set of arguments to the mv command.
51
ou can compare two files by using the diff command, which shows you the differences between the files. You can compare three files by using the diff3 command. You use the diff command if you want to compare two versions of the same file to see whether the file has changed. The syntax for the diff command is: diff first-file second-file The output from the diff command consists of those lines that are not the same in both files. If the files are identical, the diff command prints nothing; you only see the command line prompt again. If there are differences, the diff command reports them in the following manner: The first line indicates the line numbers within each file, with a single letter between the
COMPARE TEXT FILES
lines or range of lines. The letter tells whether an addition was made, a, a line was deleted, d, or a line was changed, c. The versions from each file then appear, preceded by a lessthan symbol for lines in the first file, and a greater-than symbol for lines in the second file. You can also use the diff command to compare non-text binary files; however, the diff command does not print the actual differences between files, because these are likely to be non-printable characters. Instead, diff returns you to the prompt if the files are identical, or prints a message saying that the binary files differ from each other. The diff command only compares two files. If you need to compare three files, you can use the diff3 command. Note that there is not a diff4 command.
lines 3 and 4 have changed between the first and second files.
A less-than symbol
indicates a line change in the first file. indicates a line change in the second file.
A greater-than symbol
52
If you use output redirection to save the output of the diff command into a file, the result is a diff file. You can use a diff file to record changes between text files. For example, you may want to update a Web page by saving a copy of the HTML text document and then changing a few lines. You can use the diff command to determine what changes you made, and save the results in a diff file.
The patch application uses a diff file to update an original file with the changes made to the diff file. This is useful if you are compiling new applications from updated source code. You can also use the patch application to update a configuration file or any other text file. The syntax for the patch command is patch original-file diff-file The original file, without the patches applied, is saved as original-file.orig. You can use the output of the diff command with the ed command, a command line tool that lets you edit text. To make the output of the diff command into an instruction list, or ed script, that the ed command understands, use the -e option with the diff command.
Note: If the files differ, the shell displays a message. If the files are identical, no message appears.
53
ou can measure the number of lines, words, and letters in a file by using the wc command. The wc command, short for word count, also counts the number of lines and characters, or bytes, in a file. The output of the wc command looks like this: lines words characters filename
The wc command can also count lines, words, and characters from standard output. You can use the wc command to count the results of other commands, such as the grep command. For example, to count how many lines in a file contain a specific pattern, you can use this command: grep 'pattern' filename | wc -l Keep in mind that this counts the number of lines that the grep command returns, and not the number of times that the pattern appears in the file. A single line may have the pattern repeated many times; thus, this is not an accurate way to count the number of times a word, or pattern, appears in a text file. To count the number of files in a directory, you can pipe the output of the ls command to the wc -l command.
The lines value is the number of lines in the text. The words value is the number of words; a word, for this purpose, is any group of characters that does not contain a blank line or space. The characters value includes printed letters, numbers, and symbols, as well as blank lines and spaces. You can tell the wc command to print only the lines, words, or characters by using the -l, -w, and -c options, respectively. If you do not specify any of these options, the wc command lists all three values.
COUNT CHARACTERS, LINES, AND WORDS IN TEXT
54
ou can create neatly arranged columns of text by using the column command. It is easier to read long lists if they appear in multiple columns, as this allows you to see more of a file in the Terminal window. The column command arranges your text lists into columns, based on the width of your Terminal window. The syntax of the column command is:
column filename You can also provide a list to the column command from another command by piping the output to the column command. For example, if you want to make columns from the output of the grep command, you can type the following: grep 'pattern' filename | column
The maximum width of the lines in the input file determines the width of each column. If, for example, your Terminal window is 80 characters across and the maximum width of all lines within the file is 21, then you can have three columns. You cannot have four columns, because they would exceed the width of the Terminal window. If the longest line in the file is 50 characters wide, then you can only have one column, because you cannot have two columns of 50 characters each within an 80-character Terminal window. The column command arranges the items in the list vertically in columns. The second item appears under the first item, and continues until you reach the bottom of the first column. The list then continues at the top of the second column. If you want your columns to run horizontally instead of vertically, you can use the -x option with the column command.
55
SORTING TEXT
ou can sort lines of text by using the sort command. You can eliminate duplicate lines in sorted text by using the uniq command. Sorted text is easier to read, especially when you are comparing values or locating a specific word in a list. The sort command makes it easy to do this automatically rather than manually. You can control the sort command by using options, based on the type of list you want to sort. By default, the sort command uses character order. This seems sensible at first, except that computers sort uppercase and lowercase letters in a rather confusing manner. According to your computer, the alphabet consists of the uppercase letters A through Z, then the lowercase letters a through z. So the word Yellow comes before the word blue, in character order, because all capital letters come before lowercase letters.
SORTING TEXT
You can instruct the sort command to use alphabetical order instead of character order with the -f option. This sorts blue to come before Yellow, because the letter b comes before the letter Y. Neither way of sorting works well with numbers. All numbers beginning with 1 come first, and then numbers beginning with 2, and so on. So the number 111 comes before the number 28, because 111 starts with 1, and 28 starts with 2. To sort numerically, you can use the -n option with the sort command, which then sorts numbers correctly. A similar command to the sort command is the uniq command. The uniq command takes sorted lines of text, either given as a command line argument or from standard input, and removes those lines that are duplicates. The command then displays all lines that are unique.
56
You can use the sort command with the du command to determine which of your subdirectories are taking up the most space. This can help you plan your use of disk space when it becomes limited. The du command lists the size of each directory and subdirectory in blocks; if you prefer, you can use the -k option to show kilobytes. The first column of each line displays the size of the file, so you can use the -n option of the sort command to list the directory sizes in numeric order.
Example:
[ferro:~] user% du -k Documents | sort -n 0 Documents/Dogs/Sounds 4 Documents/Letters 28 Documents/Dogs 28 Documents/Dogs/Images 56 Documents/To Do Lists 88 Documents [ferro:~] user%
The example shows that the smallest directory is the Sounds subdirectory of the Dogs directory, and the largest is the entire Documents directory itself.
Type a greater-than
symbol and the name of a new file, and press Return.
contents of the file and saves the output in the new file.
57
ou can print a file on your printer using the lpr command. You can format and print a file on a PostScript printer with the enscript command. The lpr, or line printer, command sends text directly to your printer. The printer simply outputs the lines, in the order that it receives them. The syntax for the lpr command is
If you try to print a non-text binary file, two things may happen: If the binary file is in a format known to the printing system, such as a JPEG image file, it prints on your printer. However, if it is an unknown file format, or an executable binary file, it may not print at all. You can also use the enscript command, which converts your text file to PostScript. PostScript is a computer language understood by many printers; you should check your printer manual to see if it understands PostScript. If it does, you can use the enscript command to print text. The enscript command produces better output than the lpr command, because PostScript lets you use special effects. For example, you can place a large, diagonal message, such as Top Secret, in light gray underneath your text. This is known as an underlay, and is set by the --underlay= option of the enscript command.
lpr filename The lpr command also prints text that is piped from the standard output of another command: another command | lpr If you do not connect a printer to your computer, the lpr command does not work, and you receive an error message.
58
Additional options in the lpr and enscript commands give you even greater control over the appearance of your printed page. The -o option of lpr allows you to set specific printing options. -O OPTION -o landscape -o media=Legal -o media=A4 -o number-up=2 -o number-up=4 -o number-up=8 -o number-up=16 -o prettyprint PRINT EFFECT
Print in landscape, or wide, mode. Print on legal-sized paper. Print on A4, European standard, paper. Print two pages per sheet of paper. Print four pages per sheet of paper. Print eight pages per sheet of paper. Print sixteen pages per sheet of paper. Print a header with the date and filename.
The enscript command has even more options that you can use to generate or print PostScript output. For a more complete list, see the manual page for the enscript command by typing man enscript.
PRINT AN UNDERLAY
59
ou can edit text files with Pico, a basic and easy-to-use text editor. The function of a text editor is to enable you to open, edit, and save plain-text files. Mac OS X provides several text editors for this purpose. Text editors are less complex than word processors; they do not allow you to select fonts, layouts, or other factors that affect the look of the printed page. Three shell editors come with Mac OS X; they are Pico, vi, and emacs. Although they accomplish the same basic task of editing text, each one has its own strengths and limitations. Pico is the simplest to use, because all keystroke commands appear on-screen, and there are not many to learn. Because of its simplicity, Pico is a good choice for new users of the Mac OS X shell as well as experienced users who need to do simple text editing.
You start the Pico editor by typing pico at the command prompt, along with an optional filename as an argument. If the filename argument exists and is a text file, Pico opens the file for editing; if it does not exist, you start with a blank file. The list of Pico commands appears at the bottom of the screen. A caret (^) before a letter means that you need to hold down the Control key while typing a key. For example, the notation ^X stands for Control + X. You can use your keyboard to easily move around in a Pico document. You use the arrow keys to move to the position you want to insert text, and then start typing. You use the delete key to erase text to the left of the cursor.
60
The basic keystrokes for Pico appear on-screen. The function of each keystroke is not immediately obvious, so this table summarizes the most useful Pico commands. Many of these commands are not intuitive, but the mnemonics may help. For example, to view the help screen you would press Control + G, not Control + H, so you might think of the command as getting help. KEYSTROKE
^C ^D ^G ^J ^O ^R ^X ^W ^V ^Y
MNEMONIC
Current location Delete Get help Justify write Out Read file eXit Where is -
FUNCTION
Display the location of the cursor. Delete the character under the cursor. Display the program help screens. Reformat a paragraph. Save the current file. Insert the contents of another file. Quit Pico; save if necessary. Find text in the current file. Scroll down a page. Scroll up a page.
61
ou can edit text in the Pico editor, performing basic tasks such as finding specific text or saving a file. Pico is based on the text-editing functions of the Pine e-mail program, a shell application that allows you to compose, send, and read e-mail. You can learn more about installing and using the Pine e-mail program in Chapter 13. If you edit a file with long lines, Pico does not automatically wrap the lines of text to fit the size of the window. Instead, Pico shows a dollar sign ($) at the right side of the Terminal window for each line that extends beyond the width of the window. You can view those lines by moving the cursor up or down with the arrow keys, and then using the right and left arrows to move through the line.
The Pico text editor has several command-line options that you can use when starting the editor. The -f option activates the function keys, although you should note that only the first four keys, F1 through F4, work in Mac OS X. The -v option opens a file in read-only mode, which means that you cannot make any changes in the file. The most useful Pico editing commands are those that find and modify text, save a file, and then allow you to exit the text editor. For example, to locate a phrase or word, you can press Control + W. Saving a file is the same as writing an output file, so you can use the Control + O command to save your work. If you do not save your file, and you press Control + X, Pico asks you whether you want to save the file.
Press Control + W.
62
You can move text within your file by using the cut-and-paste functions of Pico. Pico uses keyboard commands to mark, copy, delete, and move sections of text. Pico does not allow you to export text to other applications. To cut a section of text in Pico, move the cursor to the start of the text you want to cut by using the arrow keys. Press Control + Shift + 6. Pico marks the beginning of the text block that you want to select by highlighting it in black. Using the arrow keys, move the cursor to the end of the text selection and press Control + K. Pico cuts the block from the file. This is an easy way to delete large sections of text. To paste text into a new location, use the arrow keys to position the cursor where you want to move the deleted text and press Control + U. This command uncuts, or pastes, the text.
Press Control + O.
The Pico editor prompts
you with the current filename.
Note: You can change the filename by using the Delete key or adding text.
QUIT PICO
Press Control + X.
The Pico editor asks
whether you want to save your file.
63
ou can use the vi editor to edit text files. The vi editor is more powerful than Pico and can perform many more text-editing functions. The name vi is short for visual; vi is a visual editor because you can edit the files onscreen as you see them, as opposed to using the command line as you would with sed, a stream editor. To begin using the vi editor, you can type vi at the command prompt with an optional filename argument: vi file-name If you do not specify a filename, the vi editor creates a temporary file for you and opens that temporary file for editing. The name of the temporary file consists of a seemingly random series of characters and numbers;
a sample filename with the full path would be /tmp/vi.Y8pi7R, because vi stores temporary files in the /tmp directory. When vi displays a file, lines that are longer than the width of the Terminal screen continue on the next line. The vi editor breaks lines at the edge of the screen, which means that the first half of a word may appear at the end of one line, with the other half beginning on the next line. The word itself is still intact and whole; vi simply displays it this way for editing purposes. The vi editor automatically uses the full Terminal window. If there are additional lines on the screen that vi does not use to display the file, a tilde (~) appears at the beginning of each of these lines. These are not part of your file; they simply indicate the end of the content of the file.
EDIT A FILE IN VI
64
You can change the behavior of the vi editor by setting editor options. You do this by typing a colon (:), the word set, a space, and then the option name. For example, to turn on line numbers, type :set number. To turn off an option, type a colon, the word set, a space, the word no, and then with no space before it the name of the option. For example, to turn off line numbers, you type :set nonumber. OPTION
autoindent list number ruler showmode verbose
FUNCTION
Automatically indent new lines. Display a $ symbol to indicate the end of each line. Display line numbers on the left. Display the current line number and character position. Show the current mode, for example, insert, in the lower right corner. Use wordy and informative warnings and messages.
You can see which options are currently set if you type :set and press Return. For a full list of all vi editor options, type :set all.
65
MOVEMENT WITHIN VI
ou can use single keystroke commands to move through a file in the vi editor. One feature that distinguishes the vi editor from the other visual editors is the concept of modes. The vi editor is always in one of two states, Command mode or Input mode. Command mode allows you to use keystroke commands to delete lines, move text, or save files. Input mode allows you to type text into the document at the location of the cursor. While in Command mode, you can use keystroke commands to change to Input mode. The Command-mode keystrokes in the vi editor are usually a single letter, and, unlike the Pico editor commands, they are typed without holding down the Control key. However, the keystroke commands are case sensitive, which means that a is a different command than A. You need to use the Shift key, of course, to create the uppercase letters.
MOVEMENT WITHIN VI
To move within a document in vi, the application must be in Command mode. The vi editor offers many ways to navigate the content of a file, some of which appear on the facing page. The easiest way is to use the arrow keys to move the cursor, as you would in Pico. You can also use the lowercase letters h, j, k, and l to move the cursor around on-screen. The find command in vi is much like the find command in less. When you type a forward slash (/) and enter the word or phrase you are seeking, the vi editor automatically moves the cursor to the next occurrence of that text. If you type a question mark (?) instead of a forward slash, the search occurs backwards in the file from your current position.
MOVING IN VI
With vi in Command mode, press Shift + H to move to the start of the file.
66
The commands in the table below allow you to move quickly through a file in vi, repositioning the cursor and scrolling the screen when necessary. KEYSTROKE EFFECT H G h j k l ^ $ w /text ?text
Move to the first line of the file. Move to the last line of the file. Move one character to the left. Move down one line. Move up one line. Move one character to the right. Move to the beginning of the current line. Move to the end of the current line. Move ahead one word. Find text from the cursor forward. Find text from the cursor backward.
FINDING TEXT IN VI
Type /.
67
ENTER TEXT IN VI
ou can enter text into a document by switching to Input mode in vi. When you start the vi editor, it switches to Command mode by default, allowing you to move through the file or enter keystroke commands. If you try to enter text while in Command mode, you can produce some very strange results, because many characters correspond to keystroke commands in Command mode. It is therefore very important to know which mode you are in before you enter text.
and that is to press the Esc (Escape) key, located on the upper-left corner of most keyboards. If you are not sure which mode you are in, you can press the Esc key to return to Command mode. Pressing the Esc key while in Command mode does nothing, so it is safe to press this key several times to make sure. Many useful command-mode keystrokes appear in the table on the facing page. The most important keystrokes are i, which inserts text at the current cursor location, and o, which opens a new line below the current one and allows you to enter text directly. When you edit the text in your file, vi does not save your changes until you give the command to do so.
The easiest way to determine your current mode is to enable the option showmode. You can do this by typing :set showmode while in Command mode. Your current mode appears in the lower right corner. You can use a number of single keystrokes to switch to Input mode from Command mode. However, there is only one way to switch to Command mode from Input mode,
ENTER TEXT IN VI
INSERT TEXT
Press Esc.
The vi editor switches to
Command mode.
68
The keystroke commands that you use to switch to Insert mode appear in the table below. There are other modes that function like Insert mode, allowing you to type text into the file. As with Insert mode, you can leave these modes by pressing the Esc key to switch to Command mode. KEYSTROKE MODE ENTERED FUNCTION A a I i O o R r S s
Insert Insert Insert Insert Insert Insert Replace Replace Change Change Append text at the end of the current line. Append text after the current character. Insert text at the beginning of the current line. Insert text at the current location. Insert a new line before the current line. Insert a new line after the current line. Replace existing text with the text you type. Replace a single character with the text you type. Substitute the current line with one you type. Substitute a single character with the text you type.
Press Esc.
69
DELETE TEXT IN VI
ou can delete text from a file using keystroke commands. If you press the Delete key while in Command mode, this generates the symbols, ^?, which do not correspond to any command known to vi, and an error message appears. In Command mode, the Delete key has no function. You can use other keystroke commands to delete text. To delete content from your document, you must first move to the location of the unwanted text using the arrow keys or a movement command. Deletion commands use the current location of the cursor as the starting point of the deletion. You can delete the character underneath the cursor by typing a lowercase x. If there is more text on the line, it shifts to the left to fill the space formerly occupied by the deleted character. A capital X deletes the character to the left of the cursor.
DELETE TEXT IN VI
You can delete larger sections of text by typing the letter d and applying a movement command. For example, to delete from the current location to the beginning of the line, you can type d^, because the ^ keystroke moves the cursor to the beginning of the line. To delete the current line, you can type dd. If you want to delete everything from the current position to the end of the current line, you can type either D or d$. A list of deletion commands appears in the table on the facing page. When you edit the text in your file, vi does not save your changes until you give the command to do so.
DELETE CHARACTERS
70
You can use these commands to remove text from the file you are editing. If you make a mistake, you can type the keystroke command u, which undoes the most recent change. You can use this command to undo insertions as well as deletions. KEYSTROKES D dd dG dw d^ d$ d/text u X x EFFECT
Delete from current position to end of line. Delete current line. Delete from current position to end of file. Delete current word, from current position to end of word. Delete from current position to beginning of line. Delete from current position to end of line. Delete from current position to next occurrence of text. Undo last command that changed the file. Delete character to left of cursor. Delete character under cursor.
Type dd.
71
:s/old/new/ :s/old/new/g :%s/old/new/g The first instance replaces a single occurrence of old with new on the current line. The second instance adds the flag g, which stands for global. This means that vi replaces all occurrences of old with new on that line, and not just the first occurrence. The third instance includes a range option, %, which tells vi to replace all instances of the word throughout the entire file. To join two lines of text together onto one line, you can use the editing command J. This removes the line break at the end of the current line, and joins it to the next line. When you edit the text in your file, vi does not save your changes until you give the command to do so.
Type :.
The cursor moves to
the bottom of the screen following a colon.
72
You can cut-and-paste text in vi by using the deletion keystroke commands and the p command. When you delete text, it is not completely lost; instead, vi stores it in a paste buffer. You can think of this as a container that holds the most recently deleted text. You can paste the contents of the paste buffer into the current location of the cursor by typing the letter p. For example, to move a line, delete it by typing dd and move to the new location in the file. Type the letter p, and vi inserts the deleted line into the new location.
You can copy text into the paste buffer without deleting it by using the y command, which stands for yank. As with deletion commands, you must follow the y with a movement command that indicates how many lines you want to yank, or you can type yy to yank the current line. To yank or delete a number of lines, you can precede the y or d keystrokes with a number. For example, to yank 12 lines, including the current one, type 12yy.
Press Shift + J.
73
hen you finish editing a file with the vi editor, you can save your work. It is a good practice to use the save command any time you make changes that you do not want to lose. To save the current file, you can type :w and press Return. vi saves the file to your hard drive, and any changes you make become permanent. The vi editor displays the filename, the number of lines, and the number of characters in the file after you save it. You can save the file with a different name by typing a filename before pressing Return. For example, to save the current file as my-update.txt, you can type :w my-update.txt and press Return. If you start vi without specifying a filename, you must remember to save with a new name, or else vi saves it in the /tmp directory with an arbitrary name such as vi.XW0hyP.
You may name your text file whatever you like, but for compatibility with Aqua applications, you should append text files with the file extension .txt. However, if you are creating a specific type of text file, such as an HTML file, a Cascading Style Sheets file, or an XML settings file, you must save it with the appropriate extension such as .html, .css, or .plist. To exit the vi editor, you can type the quit command as :q. You can combine the :w and :q commands together as :wq, which saves the file and exits the vi editor, returning you to the shell. If you have made changes but do not want to save them, you can exit vi by appending an exclamation point (!) to the :q command.
Type :.
The cursor moves to
the bottom of the screen following a colon.
74
One file you may want to edit is the .exrc file. This is a file that you store in your Home directory and that vi editor reads when it starts up. vi automatically runs the commands in the file, so this makes it a good place to store your preferred editor options, such as showmode. Because the filename starts with a period, it is a hidden file, invisible to the ls command, but you can still list it by typing ls -a.
EXRC File Example:
set set set set ~ ~ ~ autoindent ruler verbose showmode
To use these settings, make sure you are in your Home directory by typing cd, and then type vi .exrc. Enter the lines above into the file, save it, and exit. The next time you start vi, it automatically applies these options.
Type :.
75
ou can use the emacs editor to edit text files. emacs is a very complex program that can do everything from editing simple text files to downloading and displaying Web sites. Among advanced Unix users, there is a friendly rivalry between users of vi and users of emacs. This book gives greater coverage to vi because it is less complex than emacs. However, if you do not find vi to your liking or you prefer to use a very flexible and adaptable text editor, the emacs editor is an excellent choice. The basic functions of the emacs editor are easy to use. To open a file, you can simply give the name of the file as an argument, as with other text editors. Unlike vi, emacs does not have different modes for Command and Input, so you do not have to switch between modes as you would with vi.
OPEN A FIILE WITH EMACS
As with Pico, you can use the arrow keys to move around, and you can edit text directly. You can execute commands in emacs by using either the Control or Meta key. When you type a character with the Control key, this corresponds to the prefix C- in emacs terminology; a character that you type with the Meta key corresponds to the prefix M-. For example, to search for text, you press Control + S (C-s), and to move to the end of a file, you press Esc + > (M->). Keep in mind that the prefix C- means that you must hold down the Control key while pressing another key, and M- means you must press and release the Esc key before typing the following key. You use the Esc key instead of the Meta key because Apple keyboards do not have a Meta key.
76
The following table is a summary of some of the most useful emacs commands for moving and finding text. KEYSTROKES C-a C-b C-e C-f C-n C-p C-r C-s M-< M-> COMMAND NAME
Beginning of line Backward char End of line Forward char Next line Previous line Search backward Search forward Beginning of buffer End of buffer
EFFECT
Move to the start of the current line. Move one character to the left. Move to the end of the current line. Move one character to the right. Move down one line. Move up one line. Search backward for text. Search forward for text. Move to the start of the file. Move to the end of the file.
77
ou can edit and save text files in emacs with keystroke commands that use the Control and Meta keys. You can also configure the Terminal application to allow the Option key to function as the Meta key.
There are literally hundreds of emacs commands that you can use, and you can even add additional extensions to emacs to increase this number. Many of the more esoteric commands in emacs are only of interest to serious Unix users. As a beginning user, you may want to type C-h t to read the emacs tutorial. To do this, you hold down the Control key and type the letter h, then release the Control key and type the letter t. A short list of commands that let you edit your files appears on the facing page. As with other text editors, emacs does not make your changes permanent until you save the file.
To make it easier to type Meta keystroke commands, those indicated by the M- prefix, you can configure the Terminal application to use the Option key. You can activate this Window setting from the Terminal menu. It allows you to type Meta keystrokes by holding down the Option key while pressing the appropriate key, instead of pressing and releasing the Esc key before the following key. You can also get emacs to recognize and work with your mouse, a capability that most shell applications do not possess. To do this, you enable the Terminal Window setting named Option click to position cursor; when you hold down the Option key and click your mouse, emacs moves the cursor to the current position of the mouse pointer.
Press Control + S.
The emacs editor saves
your file.
EXIT EMACS
Press Control + X.
78
EFFECT
Delete the current character. Delete the current line, current position to end of line. Transpose, or switch, two characters. Open a new file for editing. Save the file. Transpose, or switch, two lines. Save the file under a different name. Undo the last change to the file. Find and replace text, type y to confirm. Transpose, or switch, two words.
Keep in mind that the prefix C- means to hold down the Control key while pressing another key, and M- means you must press and release the Esc key before typing the following key. You can also hold down the Option key to type M- keystrokes, if you have enabled the correct Terminal setting.
Terminal
Window Settings...
79
ou can change your command line prompt by setting special shell variables. Changing your prompt lets you customize the information that the prompt displays to better suit your needs. The prompt lets you know that you are entering text into the shell, rather than a program. When it reappears, this tells you that the last command has finished executing. You can set your shell prompt to contain whatever information you like using the following command: set prompt = 'prompt formatting sequence'
multi-user system, or if you frequently log on remotely to other computers. However, many users are only on one computer at a time the one they are sitting in front of and only as a single user. If this is true for you, you may want to set your prompt to the time, the number of commands entered, or the full path. In addition to the shell command prompt, you can set several other prompts. You use the prompt2 setting if you end a command line with a backslash (\), indicating that the current command continues on the next line. You see the prompt3 message if you have auto correction on for misspelled commands. You see the rprompt message on the right side of the Terminal window for every command. Prompt settings only last as long as the Terminal window in which they are set is open. To make them permanent, see "Edit Your .tcshrc File" in this chapter.
A prompt formatting sequence is a series of letters, symbols, and special character codes that serves as your prompt. A list of the most useful special formatting codes appears on the facing page. The default prompt is set to the name of the computer, the partial path, and your short username. This is useful on a
80
MEANING
The current directory. The day of the week. The day of the month. A partial pathname. This is the 14th command. The short name of the computer. Your short username. The precise time. The current time. The month of the year. The numerical month of the year. The year in two digits. The year in four digits. The % symbol, # if you are root.
81
ou can save time and reduce typing by setting short aliases for long commands. You can use the alias command to define and list aliases. To create a new alias, you can use a command line like this: alias short-alias 'longer command' One commonly used alias is ll, which most Unix users define with the following command: alias ll 'ls -l' This alias allows you to type ll as a command and have it execute the ls -l command, which shows a long listing. You can insert additional arguments, such as a directory, after the ll command just as you can with the original ls -l command. You can also redefine existing commands to be aliases. For example, if you are afraid that you may mistakenly delete an important file because you do not always remember to use the -i option with the rm command, you can set an alias as follows: alias rm 'rm -i'
SET COMMAND ALIASES
As a result, all of your rm commands automatically include the -i option. If you redefine a command, such as the rm command, using an alias, and you need to use the original version, not the alias, you can do so by typing a backslash (\) before the command name. This bypasses aliases and invokes an executable program in your path or a shell built-in command. To list all of your aliases, you can type alias without any arguments. If you need to remove an alias, you can use the unalias command. Like other shell settings, your aliases only remain as long as your Terminal window is open. You can make your aliases permanent by saving them in your .tcshrc file. See "Edit Your .tcshrc File" in this chapter.
Most advanced Unix users like to avoid typing unnecessary characters, and thus make extensive use of the alias command. Some of the most common and useful aliases appear in the following table. You can save these aliases by storing them in your .tcshrc file. SHORT ALIAS
cd cd.. cp home ll ls print rm ..
LONG COMMAND
pushd cd .. cp -i cd ~ ls -l ls -F lpr rm -i cd ..
DESCRIPTION
Always maintain the directory stack. In case you forget the space. Prevent cp from overwriting files. Return to Home directory. Long file listing. Always include file-type indicator. It is easier to remember print than lpr. Prompt for each file deletion. Change directory to the parent directory.
DELETE AN ALIAS
83
ou can affect the way your shell functions by setting shell variables. A shell variable can either have a value or it can have no value in which case the value is null. You can think of shell variables without values as simple on-or-off switches. If the variable is set, the shell functions as if the switch is on. If the variable is not set, the switch is off. A shell variable with a value, on the other hand, acts like a blank line on an application that you can fill with the correct information. If you are applying for a job, for example, there is a line labeled Name on the application where you fill in your name, and another labeled E-mail where you write your e-mail address. To set a variable, you use the set command: set variable set variable = 'value'
The first example sets the variable without giving it a value; it simply sets the switch to on. The second example sets the variable to a value, like filling in the blank on a job application. If you type set by itself on a line, you see the list of your current shell variables. The shell automatically sets many of these either when you start up the Terminal window or when you type commands. In addition to these automatic variables, you can set a number of other variables that affect how your shell works. These appear in the table on the facing page. Shell variables normally last as long as the Terminal window is open, although you can use the unset command to get rid of shell variables beforehand. To make your shell settings permanent, see "Edit Your .tcshrc File" in this chapter.
84
MEANING
Correct command mistypings. Exit the shell after 30 minutes of no activity. Use improved, case-insensitive, tab completion. Remove duplications in the pushd directory stack. Show last 75 command lines. Shell commands do not beep at you. Redirection does not overwrite existing files. Your path. Flash the Terminal window instead of beeping.
30 enhance
No value
75
No value No value
(/bin /usr/bin)
No value
There are a number of variables that are automatically set by the shell such as version, uid, user, shlevel, term, and home. You should not change shell variables unless you know what effect they produce.
85
ou can change values that applications inherit by setting environment variables. Environment variables are similar to shell variables. Any command that the shell runs can access environmental variable settings; the environment variables represent the environment in which you run commands. Depending on the command, the shell may or may not use an environment variable to affect the execution of the command. For example, if you type a V in less, the less command uses the EDITOR environment variable, so that you can edit the file that displays. To set an environment variable, you use the setenv command: setenv VARIABLE setenv VARIABLE 'value' The first example sets the variable without a value, that is, with a null value, and the second example gives a value to
SET ENVIRONMENT VARIABLES
the variable. Note that unlike the set command, the setenv command requires no equal sign. You should type environment variable names in all capital letters to distinguish them from shell variables. You can get a listing of the current environment variables and their values by typing the printenv command. If you compare this listing to that of shell variables viewed by typing set you can see that there is some duplication. Pairs of variables such as HOME/home, TERM/term, and SHLVL/shlvl have the same names and values. This duplication allows the values to be accessed by the shell as well as by commands run within the environment of the shell. These variable pairs automatically link so that changing one changes the other. If you need to unset an environment variable, you can use the unsetenv command. Your environment variables last only as long as the current Terminal window is open, unless you save the setenv commands in your .tcsrhc file.
Type an environment
variable name and press Return.
86
Applications are the primary users of environment variables. This means that each application may have a different set of environment variables that it looks for in order to affect its operation. To know which environment variables to set, you must consult the documentation for the programs you use. You can usually find this information on the manual page by using the man command. Some environment variables are standard and are understood by many programs. Some of these are listed in the table below. Those marked with a plus symbol (+) are set by the system and should generally be left unchanged. VARIABLE EDITOR HOME (+) LANG (+) PATH PWD (+) SHELL (+) TERM (+) USER (+) VISUAL SAMPLE VALUE /bin/vi /Users/kynn en_US /bin:/usr/bin /bin/tcsh vt100 kynn /bin/vi MEANING
Your preferred text editor. Your Home directory. Your preferred language. Your path. The pathname of your shell. The Terminal application emulates a vt100. Your short username. Your preferred text editor.
87
ou can change the directories where the shell searches for commands by setting your path variable. Changing your path is necessary if you install new command-line software on your computer. The default path includes the directories /bin, /sbin, /usr/bin, and /usr/sbin because they are where Mac OS X stores the programs that come with the system. If you add new programs, they may install into other directories such as /usr/local/bin, /usr/local/sbin, or /sw/bin. If you do not change your path, then the only way to run those programs is to type out the full pathname before each, as in /usr/local/bin/vim filename. You can set your path by typing out a list of pathnames in a set command. Because you are providing a list, you should use parentheses instead of single quotes. For example: set path = (/bin /sbin /usr/bin /usr/sbin /sw/bin)
SET YOUR PATH
This command immediately updates your path as well as the PATH environment variable. When you type the filename, it locates any executables stored in the new path; you can use the which command to confirm this. If you already have a long path value, it may be difficult to retype or copy-and-paste the current path value. Instead, you can add new directories to the path by typing: set path = ($path /new-directory) $path tells the shell to insert the current value of the path variable before setting the value. You type the pathname of the new directory after $path to append it to your path. Because path is a shell variable, any value that you set lasts only while the current Terminal window is open. To make the changes to your path permanent, you can store the command to set the path in your .tcshrc file.
88
ou can save the commands to set your prompt, your aliases, your shell variables, your environment variables, and your path so that each time you open Terminal, your shell is configured to your preferences.
You can also use the example tcsh files that are located in the /usr/share/tcsh/examples directory on your computer. You can add a line at the very beginning of your .tcshrc file as follows: source /usr/share/tcsh/examples/rc The source command tells the shell to read the commands from a text file and run them as if they are being entered directly into the Terminal program. As a result, this command in your .tcshrc file tells the shell, upon starting, to run the commands stored in the /usr/share/tcsh/examples/ rc file. For more information, you can type less /usr/share/ tcsh/examples/README. You can also store your aliases, variables, and environment variables in separate files as described in the README file, although it is acceptable to set them all within your .tcshrc file.
You save these commands in a special file called .tcshrc that you create in your Home directory. The period, or dot, at the beginning of the name indicates that the file normally hides from the Mac OS X Finder and from the ls command, although you can still list it using the -a option with the ls command. It is common for Unix programs, such as the tcsh shell, to store their configuration settings in invisible dot-files in your Home directory. These files begin with a period and often end in rc. The tcsh shell executes all commands in your .tcshrc file whenever you open a Terminal window or start a shell. To create your .tcshrc file, you can use any text editor, including Pico, vi, or emacs, and enter one command per line.
EDIT YOUR .TCSHRC FILE
Type cd ~.
This takes you to your
Home directory.
Terminal window, the shell executes the commands in the .tcshrc file.
89
ou can list the commands that you have typed before by using the history command. You can also use special characters to repeat or edit commands you have already typed. The history command lists the commands you have typed since opening this Terminal window, along with the time at which each command was run. The history command lists the 100 most recent commands, provided that you have typed more than 100 commands into the current Terminal window. You can repeat commands or portions of commands using the history recall built into the shell. You do this by typing an exclamation point (!), or bang, followed by a special code that indicates what information from your history you want to recall. There are a number of different history codes that you can use, the simplest being two exclamation points (!!); this code repeats the last command that you
typed. If you type an exclamation point and then some letters, the shell searches through the command history for the most recent command beginning with those letters, and repeats that command. In both cases, the shell displays the recalled command immediately before executing it. A list of other history codes appears on the facing page. You can also edit the previous line by using a caret (^). This is a method to correct a mistake you may have made, or to change a command so that it applies to different files. You use the caret as follows: ^old-text^new-text The command is repeated, but with the old-text replaced by the new-text. For example, if you have just typed cd /usr/shrae and you want to correct yourself, you can type ^shrae^share and press Return.
90
The table below lists some of the most useful history codes. You can use these history substitutions anywhere in your command line. For example, if you have just moved a series of files with the mv command and you want to change their file permissions, you can type chmod +r !!* to use the chmod command on the arguments supplied to the mv command that you have just executed. HISTORY CODE !! !!* !!^ !!$ !text !?text? !number !-3 MEANING
The previous command. The argument of the previous command. The first argument of the previous command. The last argument of the previous command. The last command beginning with text. The last command containing text. The command number from the history command. The command three commands ago.
91
ou can start another shell by typing the pathname of the shell. Running commands in a sub-shell can preserve your shell settings or allow you to use a different shell program. Each time you start a new shell, it executes the commands stored in your .tcshrc file or the appropriate dot-file for the shell if it is not tcsh and gives you a new prompt. Most shell variables are set to their initial default values, but environment variables remain set with any values they had in the original shell.
If you are done using a new shell, you can close it by typing the exit command. This returns you to your original shell. If you changed your current directory in the new shell, you find yourself back in the original directory when the new shell exits. Mac OS X comes with three shells installed. The tcsh shell is the default, and the one that this book assumes you are using. The Bourne-again shell, known as bash, is a popular alternative to the tcsh. The Z shell, zsh, offers many customization opportunities for Unix power users. The pathnames for these shells, respectively, are /bin/tcsh, /bin/bash, and /bin/zsh. For more information about the bash and zsh shells, see "Work with the Bourne-Again Shell" and "Work with the Z Shell" later in this chapter.
When the new shell starts up, it has a clean command history. If you type history, you see a very short list that does not include any of the commands executed in the original shell. Likewise, after you exit the new shell, the command history for that shell does not appear in the history of the original shell. You only see the command to start the newer shell.
92
ou can change your default shell from tcsh to bash or zsh, so that the Terminal program automatically starts with your preferred shell. You may never want to change your shell; the tcsh shell is a very useful and user-friendly shell program. However, many people like the bash shell, especially those from a Linux background, and you may wish to use that shell instead. For more information about the different shells, see "Work with the Bourne-Again Shell" and "Work with the Z Shell" later in this chapter. Changing your shell is a two-step process. The first step is to use the chpass command to change your shell record in the master password file. You can update this file, which is located at the pathname /etc/master.passwd, by typing the following: chpass -s /path/to/shell
After you update the master password file, you need to enter the changes into the NetInfo database. NetInfo is a database maintained by Mac OS X for keeping track of many things related to the operation of your computer, including default shells. To make your shell change take effect in NetInfo, type the following command exactly as it appears here: sudo cat /etc/master.passwd | sudo niload -m passwd / This example uses the sudo command to allow you access to files and permissions you normally would not be able to change. For this reason, you must make sure that you do not make a mistake typing the command. After you press the Return key, you see a prompt asking you to enter a password. At this point, you can enter your normal user password and press Return.
For example, chpass -s /bin/zsh makes your default shell the Z shell, and chpass -s /bin/bash changes your default shell to the Bourne-again shell.
CHANGE YOUR SHELL
93
ou can use bash instead of tcsh as your primary shell, or you can start the bash shell from the command line. The Bourne-again shell is a popular alternative to tcsh, which is commonly used on Linux computers. The original shell on early Unix systems, /bin/sh, is known as the Bourne shell after the programmer who wrote it, Steven Bourne. The bash shell takes its name from Bourne in a clever play on words. The Bourne-again shell is more compatible with the commands of the original /bin/sh program than the tcsh shell, which is based on the later C shell. If you are a typical user, you may not see a great difference between the tcsh and bash shells. You can type commands as you normally would, redirect output, and perform most tasks without problems. The first obvious difference is a change in your prompt, letting you know that you are now running the bash shell.
You notice the second difference if you try to change your shell settings. The Bourne-again shell uses different commands to set variables. To set a variable, for either shell or environment, in the bash shell, you type the following: variable-name=value No set or setenv command is necessary, just the variable name and value, separated by an equal sign. All variables are automatically shell variables unless you export them as environment variables. To make the value of a variable available as an environment variable for use by other programs, you can type the command export variable-name. Another important difference is that the bash shell does not run the commands in the .tcshrc file when you start a new shell. Instead, it executes the commands in the .bashrc file in your Home directory.
94
f you are an advanced user, you can write functions that perform shell tasks in the highly configurable Z shell. If you are new to Unix, this may be much more than you need.
The differences between shells are most apparent when you are writing shell scripts, as these scripts use the advanced features of the shell. The Z shell uses a number of functions that you can define in order to override or change default behavior. The Z shell was created to be compatible with another early shell known as the Korn shell, or ksh. If you are going to be using your shell a great deal and want to become more familiar with shell customization, the Z shell may be a good choice for you. Many of the built-in commands familiar from the tcsh shell have different command names and values in the zsh shell. For example, you can set zsh shell options similar to shell
WORK WITH THE Z SHELL
variables in tcsh by using the command setopt, and you can set and export environment variables as you would in bash. Instead of running the contents of the .tcshrc file when a shell starts, the zsh shell executes commands in the .zshrc file in your Home directory. Aliases in the zsh shell must be set using the following syntax, which differs from the tcsh shell by the requirement of an equal sign: alias short-alias='command and options' You can take full advantage of the extensibility of the Z shell by creating specialized functions in your .zshrc file. A function creates a command, similar to an alias but with more flexibility and control. To learn about Z shell functions, you can see the manual pages for zsh by typing man zsh.
Press Return.
The Z shell defines a new
command named cp.
95
ou can suspend a process to regain control of the command line, and from that point, kill the process, move it into the background, or leave it suspended until you are ready to restart it. Just as almost everything that makes up a Unix system is a file, almost everything that a Unix system does is a process. The shell that responds to the commands you enter in a Terminal window is a process. Each command you enter is a process. When you ask the system what processes are currently running, that too is a process. Just as Unix makes little distinction between system files, application files, and personal files, it makes little distinction between system processes, applications, and the commands that you enter in a Terminal window. The activity of the system is implemented as a series of processes. Unlike some operating systems, Unix systems like Mac OS X allow you to gather a lot of information about the processes that are running on your system. In fact, you can start, stop,
SUSPEND THE CURRENT PROCESS
and suspend them if you have sufficient privileges. You can also move processes to the background so that you can issue other commands. Every process has a process ID a unique numeric identifier that the system assigns. While you enter a command in your shell, that shell is an active process. When you press Return, the command that you just entered starts running, and your shell is suspended until that process completes. You can suspend a process by pressing Control + Z. When you suspend a process, it cannot run. It does not access files, accumulate run time, or task the CPU. A suspended process is also referred to as a stopped job.
In a Terminal window, type the command find /usr -name ps print and press Return.
96
On a multiprocessing system such as Unix, many processes appear to be running at the same time. They are actually running in quick succession, taking turns using the system's CPU and memory. The system tracks the resources that each process requires and restores the process environment as needed each time a process gets its turn to run. At almost any instant in time, most processes are waiting for some resource, whether that resource is a response from the user, data from the disk, or simply a turn at the processor. Processes change state frequently while they are running. Process states include running, sleeping, stopped, and terminated. When you suspend a process, you essentially put it on hold so that you can run other commands. Similar to putting a caller on hold, suspending a process means that no progress is made as long as that process is suspended. The process is stopped, awaiting your instruction to start again or to terminate and release all of its resources. You can open a second Terminal window when you are working on the system, but this is not an option if you are logged in remotely.
SUSPEND A PROCESS
Press Control + Z to
suspend the process.
Press Return.
97
RESTART A PROCESS
ou can save some work by restarting a suspended process. Instead of running the job again, you can pick up where you left off when you suspended the process. In addition, restarting a suspended process frees resources tied up by that process. All processes that you run, suspended or not, are associated with the particular shell in which they were started. If you suspend a single process in each of two Terminal windows, for example, each of these processes will have 1 as its job number. At the same time, each of these suspended processes will also have a unique process ID. Where each job number is related to the parent shell and only the parent shell, each process ID is related to the entire system. This means that you can refer to a process by its job number only in the shell in which it was started.
Job numbers are always small numbers like 1 or 4. While you can accumulate a large number of suspended jobs if you work at it, in practice this is never done. Process IDs are usually large numbers like 325 or 5234. The system assigns these numbers in some fashion, reusing the numbers as needed. If you see a process running today with the process ID 4321, you might not see this number used again for months. Process numbers that are small like 1 or 69 are assigned to system tasks. To restart a suspended process, use the fg (foreground) command. If only one suspended process is in your current shell, that process restarts. If there are several suspended processes, the one most recently suspended will restart. To restart a particular suspended process, enter the fg command followed by its job number.
RESTART A PROCESS
98
You can only restart a process that has been suspended. You cannot restart a process that has run to completion or a process you have terminated. Each process has a life of its own. Even if you run the same command seven times in a row, each running is an independent process. You can restart processes by bringing them back into the foreground, and they will then continue running as if they had not been suspended. You can also restart processes by sending them to the background and continue entering commands from the shell from which these processes were run. If you press Control + D to exit a shell in which you have suspended processes, the shell alerts you to the suspended processes. The message "There are suspended jobs" appears. This warning ensures that you do not forget about commands that you suspended. You can still exit the shell by pressing Control + D again. If you exit the Terminal window by clicking the red button, no alert appears. The suspended processes are quietly killed when you close the window.
99
unning a command as a background process allows you to continue entering commands while that process runs. A process running in the background is not suspended; it continues to execute. When you run a command in the Terminal application, the output from the command appears on your screen. Until the command finishes, no other commands can run. This is called foreground processing. When the command finishes running, your command prompt returns. Unix allows you to run commands in the foreground or in the background. Unlike commands in the foreground, commands run as background processes allow you to enter additional commands. Your shell continues prompting and you can continue entering commands. The simplest way to run commands in the background is to start them in the background. You can run a command in the background by adding an ampersand (&) to the end of the command line. For example, if you enter a find
RUN A PROCESS IN THE BACKGROUND
command, type an ampersand at the end of the line, and press Return, the find command continues processing and writes to your screen as it locates files that meet your search criteria. At the same time, you have control of the command line and can issue other commands while the find command continues to run. Like suspended processes, jobs that run in the background have both a job number and a process ID. Both suspended processes and background processes appear in the listing when you use the jobs command. The important difference between a suspended process and a background process is that a background process continues to run while a suspended process is inactive. Running commands as background processes allows you to get more work done in a single Terminal window. If you press Control + D to exit a shell while there are background processes running, the system issues a warning.
A message displays
The find command continues running in the background, while you enter the date command and get your output.
100
You can place a process into the background by first suspending it with Control + Z and then using the bg (background) command to move it into the background. If you run a command, such as find / -name findme -print, and then suspend it by pressing Control + Z, you can restart it in the background with a bg command, such as bg %3. The command continues running and searching for your files while allowing you to enter other commands at the shell prompt.
TYPE THIS:
find / -name findme print control+Z bg pwd date
RESULT:
/Users/user Thu May 1 11:12:13 EDT 2003
101
KILL A PROCESS
ou can use the kill command to stop a running or a suspended process. By halting a command that you mistyped, you can avoid wasting system resources or performing a process that you did not intend to run.
if they are running in other Terminal windows. When you issue the killall command, the system looks for commands you are running. As a normal non-root user, you can only kill processes that you have started. As a root user, however, you can kill any process on the system. Unix provides little protection from making mistakes that can bring your system down. One of the worst mistakes that root users can make on a Unix system is to enter kill 1 when they mean to enter kill %1. The user's intention is to kill a suspended process. Typing the command without the % kills a process known as init and will likely crash your system. For this reason, most disciplined system administrators avoid using the root account except when there is no other way to accomplish a job.
Stopping a process that is running on a Unix system is called killing it. To kill a running process, you use the kill command followed by the process ID of the process. For example, kill 1234 would kill the process with process ID 1234. To kill a suspended process, you use the kill command followed by the job number. For example, kill %2 would kill the second suspended process. After you kill a process, you cannot restart it. You can run the same command again, but this action starts a new process. You can kill a process by name. The variant of the kill command used for this purpose is called killall. If you enter killall man, you will kill all man commands, even
KILL A PROCESS
102
You can use the kill command to send signals to running processes. The kill command is useful for terminating a process. Although most people talk about the kill command as if its sole function were to terminate processes, this is not the case. In fact, the kill command's real function is to send very short messages called signals to running processes to control the behavior of these processes. The default kill command the command without an argument sends a signal that asks the process to terminate. Systems people often refer to the default signal as a SIGTERM. Another common signal, referred to as a SIGHUP, for hang up, is most often used to tell a running process that it should go back and re-read its configuration file. Many system processes remain unaware that their configuration files have changed unless you send this signal to them. Another often-used signal is SIGKILL, a signal used to terminate a process that is not terminated with SIGTERM. TYPE THIS:
[ferro:~] user% man kill control+Z [ferro:~] user% kill KILL <type the process id> [ferro:~] user% jobs
In a new Terminal
window, type man killall and press Return.
103
ou can use the ps command to find out what processes are running on your system or to find the process ID for a job that you want to kill. To kill a process by its process ID, you obviously must know its process ID. Fortunately, Unix systems provide a command that displays information about running processes, including the process IDs. That command is ps. You can also use the ps command to display a list of all processes that are running on your system. Depending on the arguments that you provide, this list can include information about the time each process started and who started each process. The ps command by itself only displays a list of the commands you are running. To list system commands and the commands that other users are issuing, you add arguments to your ps command. The ps -aux command shows all processes running on the system and provides details on each one.
LIST ACTIVE PROCESSES
The ps a command lists all users' processes. You will own some of these processes, while others start when the system boots. The ps u command adds information such as when each process started, as well as the how much CPU and memory each process is using. The ps x command adds processes that are not associated with a particular Terminal window, such as the processes started before you logged on. The most commonly used ps command for Mac OS X users is ps aux, combining the most useful command options. By using the ps command followed by a vertical bar, commonly referred to in Unix as a pipe, you can restrict the output that it return to your specific interests. For example, ps aux | grep init displays the init process and other processes that contain this string in their names.
104
The columns in the output of the ps -aux command provide a lot of information about running processes. This information can help you understand who is using your system, what is running, and sometimes why the systems is running slowly. Each of these columns is explained in the table below. PS COLUMN USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND MEANING
Username of the person running the process. Numeric process ID. Percentage of CPU resources the process is using. Percentage of memory the process is using. Virtual size of the process in kilobytes. Size of process in memory. Associated control terminal, or ?? if there is no associated terminal. Status of the process. Time, if started today, or date a process was started. Accumulated run time. Command that is running, complete with arguments.
information for each tcsh process, plus the grep command used to select these processes.
105
ou can use the top command to find out which processes are using the most resources on your system. This knowledge is especially useful when your system is running slowly. Although processes appear to be running simultaneously, they actually take turns using the CPU. This sharing happens at an extremely rapid rate, but you can view some process details using commands such as ps and top.
the ps command displays. In addition, the top command provides useful information about processes in general and system performance. The information included in the top output for each process includes the process ID (PID), the simple command without arguments, and the percentage of CPU usage. It also includes information on threads and memory sizes. Some of the information the top command displays tells you a lot about system performance. For example, if a system is more than 90 percent idle, you know that the system is not running more processes than it can handle and you can assume that performance is good. Another good indicator of performance is the system load. The top command has numerous options that you can use to alter its behavior. For more information on these options, type man top and press Return.
While the ps command allows you to view important statistics related to processes such as how long they have been running or how much memory they are using the ps output display order is somewhat random. To examine processes to determine how much demand they are placing on the system, another tool is more appropriate. That tool is top. The top command orders its output to display the tasks using the bulk of the CPU time available at the top of the list. The columns in the top output are similar to those that
MONITOR PROCESSES WITH TOP
Press Control + C.
106
You can use the top command to determine how hard your system is working. The load averages that the top command displays tell you how many jobs, on average, were ready to run but were waiting for access to the CPU. Small load averages like those shown in the top output support the conclusion that the CPU on this particular system is not busy and that processes rarely have to wait for access to it. Load averages above four may indicate a system that is burdened. Load averaging higher than 10 indicates a system with excessive CPU contention. You can use the uptime command to see how many users are logged on and to display load averages. This command tells you how long the system has been up, how many users are currently logged on (though it counts each Terminal as a separate logon), and the 1-minute, 5-minute, and 15-minute load averages. TYPE THIS:
uptime
RESULT:
2:26 PM 4:18, 3 users, load averages: 0.03, 0.03, 0.01
The top command displays processing events for the top processes.
107
ou can place commands that you repeatedly execute in a file and execute these commands by entering the name of the file. A file of Unix commands that you execute is called a shell script. Writing shell scripts can save you a lot of work and make it unnecessary for you to remember complicated commands. The Unix commands that you place in a script are commands that you might have entered in a Terminal window. When you run the script, the system executes the commands in the order entered. Shell scripting is a very basic form of Unix programming, although scripts can run the gamut from a simple list of commands to elaborate programs with looping, embedded functions, and complex data structures.
command in a file and execute that file, you also get a listing of your files. While there is no advantage to executing a simple command such as ls using a script, the advantage to scripting becomes readily obvious when you need to execute complex commands or many commands in a certain order. In fact, script writing is so efficient that nearly everyone who manages a Unix system automates routine tasks by writing scripts. You can write shell scripts that ask the person running them to supply some information or that make use of the user's shell variables. For example, one of the simplest shell scripts you can write greets a user when he or she executes it. If you place the command echo hello, $USER in a file, the user running the script sees a personalized message such as "hello, jdoe."
If you enter a command such as ls in a Terminal window, the shell passes the command to the kernel for execution. The result is a listing of your files. If you enter the same
To start the Pico text editor, type pico and press Return. 108
You can write scripts that are easier to understand and maintain by adding comments that explain the complicated commands and describe how the scripts work. Comments are lines in scripts that the system ignores when it runs the script. Comments serve the function of explaining your script to others who read it so that complex commands are easier to understand and so other users do not have to read the entire script to know what it is supposed to do. To turn a line of text in a script into a comment, insert a pound sign (#) in the first column. The shell ignores that line when it runs the script, so you can place anything you like in a comment. You can also add comments to the end of a line of code by adding # at the end of the Unix command and before the text of your comment. Always place at least one space or tab on each side of the #. While it is a good idea to include some comments in a script to explain what the script does, you do not need to comment every line of code. Inserting one or two lines of comments at the beginning of a script is useful. Placing a comment on every other line is distracting. When you run this script, the shell ignores the comments. TYPE THIS:
# this is a script that greets the user echo hello, $USER # address user by his username
RESULT:
hello, user
Press Return.
109
ou can save yourself a lot of work and better remember complicated Unix commands by placing commands in scripts and running the scripts. When you run a script, you can execute a sequence of commands by typing no more than a single filename. After you turn a series of commands into a script, you can type the filename of that script just as if it were another Unix command. In fact, many Unix advocates like to think of scripts as extensions to the operating system. In a sense, when you create a script, you add a new command to your system.
typing each line in the Terminal window. The second way is to first make the script executable and then execute it by typing its name. See Chapter 2 for more information on file permissions. For a script that you intend to run many times, changing the file permissions so that you can run it by entering only its name can save you time. If you use the chmod a+x command, other users can execute the script too. The source command is especially handy when you want to run scripts that do not have execute permissions set. If you do not own a script and cannot change its permissions, you may still be able to run it by using the source command. You must have read permission, which enables you to read a file, to run it using the source command.
You can execute a script in two ways. The first way is to type the command source, followed by the name of the script. When you use the source command, the shell reads and executes the file one line at a time just as if you were
Type source followed by a space. Type the name of a script and press Return. 110
TYPE THIS:
[ferro:~] user% source macosx
RESULT:
I love Mac OS X
TYPE THIS:
[ferro:~] user% /bin/sh sh-2.05a$ source macosx
Type ls -l followed by a
space.
111
ou can issue a command or a list of commands many times by placing a loop in your shell script. Adding a loop keeps you from having to run your script for every file in a directory or every value in a list. When you want your script to loop through a series of files, numbers, or other values, you can use a looping command. To ensure that the proper shell is used when your script runs, you can add a line to the top of your script beginning with #! followed immediately by the full pathname for the particular script. For example, a script written to run in tcsh starts with #!/bin/tcsh. For tcsh, you can use the foreach command to loop through a set of values. The command foreach number (4 5 6) runs three times, once for each of the numbers
WRITE LOOPING SHELL SCRIPTS
listed. Each time through the loop, the next number is assigned to the variable $number. Following the foreach command, you can enter whatever commands you want to execute for each $number. You terminate your loop by entering the word end on a line by itself. For some tasks, you want the number of times that you loop through a set of commands to depend on the value of a certain variable or some other condition. For example, if you want to write a script that adds two numbers, you can write it so that it adds the numbers until the person running the script stops entering numbers. In this case, you use a while loop. A while loop continues executing as long as the specified test condition is true.
Start the Pico editor to create a file named work2day. Type #!/bin/tcsh and press Return twice. Type foreach weekday (
Mon Tue Wed Thu Fri ) and
Type echo Go to work on $weekday and press Return. Type end, press Return, and then type echo Today is `date +%a`.
Your script is complete.
press Return.
112
You can often reduce the lines in a script by placing repetitious commands in a loop. You can loop by using any of the shells provided with Mac OS X. The foreach and while commands are built-ins associated with tcsh and csh. You must use a different syntax if you are writing scripts in bash, zsh, or sh. The for command syntax for these shells uses the word for, followed by a variable name and the word in, followed by list of values. The words do and done mark the beginning and end of the commands to be executed in your loop. Make sure that you use /bin/sh, /bin/bash, or /bin/zsh when you run the following exercise that loops through the days of the week.
TYPE THIS:
[ferro:~] $user /bin/sh sh-2.05a$ for weekday in Mon Tue Wed Thu Fri > do > echo Go to work on $weekday > done
RESULT:
Go Go Go Go Go to to to to to work work work work work on on on on on Mon Tue Wed Thu Fri
Type echo n "number> " and press Return. Type set num = $< and press Return.
Type end and press Return twice. Type echo $sum. Save your file, and exit
Pico.
113
You then enter a list of commands that you want to execute if the condition you specified is true. For readability, script writers usually indent these lines. After this list of commands, end your conditional statement with the word endif on a line by itself. In bash, sh, and zsh, the if statement takes a different form. You follow the word if by a set of square brackets that enclose the test condition. Follow the brackets with a semicolon (;) and the word then. You can type the word then on the following line if you prefer. You terminate the list of commands to be executed with fi. You can also specify a list of commands that should run if the specified conditions are not met. In both forms of if commands, you use the word else to begin this list. An else class must follow the if clause that it is related to.
USING TCSH
Start the Pico editor to create a file named work2day3. Type #!/bin/tcsh and press Return twice. 114
Type echo Go to work and press Return. Type endif. Save your file, and exit
Pico.
It is often useful to collect information from the system by running a command and assigning its output to a variable. The work2day scripts in this chapter use backticks ( `) for this. The output from the command enclosed in backticks is assigned to the variable and can then be displayed or tested. You can use backticks to run almost any simple Unix command. However, you should always take care to consider the output that will be assigned to your variable. It may be different than you expect. Be sure you use tcsh or csh when you loop on the command line.
TYPE THIS:
[ferro:~] user% foreach FILE ( 'ls -l' ) foreach -> echo $FILE is a file foreach -> end
RESULT:
total is a file 64 is a file -rw-rr is a file 1 is a file user is a file staff is a file 134 is a file May is a file 5 is a file 07:21 is a file addloop is a file
USING TCSH
115
ou can use the awk command to extract text from files or from the output of other commands. It is particularly useful for extracting a portion of each line. You can then use the output from awk for further processing.
programming language, it is most popularly used within shell scripts or on the command line to select data from files or the output of other commands. Any command that you write for awk and awk scripts begins with an opening brace ({) and ends with a closing brace (}). The awk command processes lines of text one at a time and assigns each portion of a line to a variable such as $1, $2, and so on. The awk command language has some built-in variables such as NF and NR that represent the number of fields on each line and the record number of the current line. Fields are portions of text separated by white space or some other delimiter that you specify. You can write many useful scripts and commands using awk. Awk is a scripting language that includes conditional tests and looping.
Like many other Unix commands, awk works well with the concept of white space any combination of spaces and tabs that might exist between strings of text and numbers. If you want to display the first or the third word on every line of a text file, awk is the tool to use. If you want to display the last word on each line, awk can handle that as well. If the information that you want to display is not separated by white space, you can still use awk to extract it. You can use awk on the command line, or you can write scripts using nothing but awk commands. Though awk is a
EXTRACT INFORMATION WITH AWK
Type ls -l followed by a
space.
116
TYPE THIS:
[ferro:~] cat work2day | awk '{print $NF}'
RESULT:
1 0 9 6 1 5
RESULT:
#!/bin/tcsh ) $weekday end +%a'
117
he sed command lets you modify the input or output of a Unix command or the content of a file without having to use a text editor. Sed is a special editor that is unlike Pico, emacs, and vi. It can change the contents of files or the output of other commands on the command line. Think of sed as a pipe into which you pour text and out of which modified text flows. The shape of this pipe, representing a set of editing commands that you specify, determines what text changes and how that text changes. The simplest sed command replaces one string with another string. The command echo Please go to work today | sed "s/go to work/stay home/" prints "Please stay home today". Sed changes one instance of the first string to the second on each line. If you want the same text to change every time it appears in a line, add the letter g to the end of the
EXTEND SCRIPTS WITH SED
command. The command sed "s/a/z/g" changes every occurrence of the letter a in its input to the letter z in its output. If you want to change a number of strings at the same time, create a file containing all of your substitutions. The command sed -f subs < infile > outfile looks for a series of change requests in the file subs, applies these changes while processing the file called infile, and writes the changed text to outfile. If the text that you want to change includes a forward slash (/), you can see where sed might be confused as to what portion of text it needs to change. However, you can specify a different delimiter to separate the old and new text. The command sed "s:old:new:" works as well as sed "s/old/new/". Whichever delimiter you use, be sure to use three of them.
Type Don't forget to take your lunch. Save your file, and exit
Pico.
Start the Pico editor to create a file named message. Type Please go to work
today. and press Return.
118
As with awk, you can use sed to create fairly complex scripts, but you most often use the command to extend shell scripts. Scripts written entirely in sed can be simple or extremely challenging. Try a simple sed script like that shown here. Enter this script in a file called oneline and make it executable. It joins lines of a file into a single line by removing linefeeds. Then, try the following commands.
TYPE THIS:
[ferro:~] echo a > mytext; echo b > mytext; echo c > mytext [ferro:~] user% ./oneline < mytext
RESULT:
abc
Type echo Today is `date +%a` and press Return. Type if ( `date +%a` ==
"Sat" || `date +%a` == "Sun" ) then and press Return.
Return again.
119
ou can schedule scripts or other Unix commands to run automatically at a time you specify. This can keep you from forgetting to run routine scripts and can allow you to schedule big jobs to run when the system is not busy. Use the cron command to schedule the execution of commands or scripts. Cron makes use of files called crontab files that specify what time commands and scripts are to be run. All crontab files have the following format: min hr day month day-of-week command-to-run The first field represents the minutes, and the second represents the hours. If you want a script to run at 2:15 p.m. every day, enter 15 14 for these fields. The entry 8 1 in the day and month fields means January 8th. The day-of-week field must be a number between 0 and 6; Sunday is 0, Monday is 1, and so on.
SCHEDULE SCRIPTS TO RUN AUTOMATICALLY
Time fields can include a string of comma-separated values or an asterisk (*). An asterisk indicates that every possible value for the field is valid. In the day-of-week field, for example, * tells cron to run the command every day of the week. Typing 0,30 in the minutes field tells cron to run the command on the hour and half hour. You can also specify values such as */10 in the minutes field to tell cron to run the command every ten minutes. A job scheduled to run via cron only runs if all of the timing criteria are met. For example, the line 5 17 * * 5 /Users/user/bin/send_weekly runs the send_weekly script every Friday at 5:05 p.m. To schedule jobs to run automatically, use the crontab -e command and add a line for each command or script you want to schedule.
Start the Pico editor to create a file named check_space. Type #!/bin/tcsh and press Return twice. Type set when = `date
+%H:%M` and press Return.
Type set diskspace = `/usr/bin/du sk ~$USER` and press Return, then type echo $when $diskspace >> ~$USER/dulog. Save your file, and exit
Pico.
120
RESULT: Cron does not let you save the file. The 7 in the day-of-week field is invalid. Only a value between 0 (Sunday) and 6 (Saturday) is allowed in this field. Change it to the proper digit for the current day of the week and "hello" messages should appear in your Terminal window after a few minutes. To inactivate the line without removing it, use the crontab e command again and type a pound sign (#) in column 1.
121
ou can use the shell command open to open a file in an Aqua application such as TextEdit, Preview, Photoshop, or Microsoft Word. The file opens as if you had double-clicked it in the Mac OS X Finder. There are three ways to use the open command: open filename open -e filename open -a Application-name filename The first version of this command launches an Aqua application to open the designated filename. Mac OS X associates each document with information known as metadata. This metadata includes information such as which Aqua application created the file. The open command launches that application. If the application that created the file is not listed in the metadata, then Mac OS X looks at the extension of the file. The extension is the last part of the filename that appears
OPEN AQUA APPLICATIONS FROM THE SHELL
from the period (.) on. For example, the filename my-dog.jpg has an extension of .jpg. Mac OS X uses the default application for opening .JPG files. This is the same method the Mac OS X Finder uses to determine which application to use when you double-click the icon of a document. Not all Unix text files end with the .txt extension. An HTML file may be named about-cat.html. If you use open, the file opens in a Web browser, but if you want to edit it, you may want to use TextEdit. The second form of the open command, with the -e option, opens the file in TextEdit, which lets you edit text files not ending in the .txt extension, such as HTML pages or configuration files. The third version of the command lets you specify which application to use. You can name any application located in the /Applications directory or its subdirectories. You can start the application with a blank file by omitting the filename argument.
122
The open command is not limited to only opening files. If you provide other arguments, the open command tries to display those arguments in the appropriate viewer or editor. One of the most useful ways to employ open is to open directories in the Mac OS X Finder. This command creates a Finder folder window to open the current directory.
[ferro:~/Pictures] user% open
The open command can also open Web URLs in the default Web browser you have specified in your System Preferences on the Internet panel. To open, type your URL as the argument.
[ferro:~] user% open http://cssin24hours.com/
You may need to enclose the Web URL in quotation marks to prevent the shell from interpreting question marks and other special characters. You can also send e-mail to an address by using a mailto: URL. This command starts your default mail program and sends mail to the specified address.
[ferro:~] user% open mailto:kynn@idyllmtn.com
123
ou can create a screenshot of your current desktop and application windows by using the screencapture command. A screenshot is simply a graphics file that shows the state of your display at any given time. You can use a screenshot for troubleshooting or sharing what you see with someone else who does not have direct access to your computer. Screenshots are also useful for step-by-step instructions, such as those used extensively in this book. You can create a screenshot at any time in Mac OS X by holding down the Shift + Command () keys while typing the number 3. This key sequence captures whatever is currently on the entire screen and saves it to a file in your Desktop directory. The file is named Picture 1.pdf and is in the Portable Document Format (PDF) developed by Adobe. The Mac OS X Preview application or the Adobe Acrobat Reader program can read PDF files. If you create more screenshots in this manner, they receive successive filenames, such as Picture 2.pdf and Picture 3.pdf.
The screencapture shell command gives you more control over your screenshots, allowing you to save them wherever you wish and with any filename. The syntax for this command is screencapture options filename.pdf If you use the -m option, the screenshot captures the entire main screen. The -i option puts the screencapture command into Interactive mode. In Interactive mode, you can define an area of the screen to capture by dragging the mouse. Typing a space in Interactive mode switches the selection from mouse selection to window selection; if you click a window in Window Selection mode, that entire window is captured.
After you have captured a screenshot, you will probably want to edit it. The Mac OS X screen capture only saves files in Adobes PDF format, which is usually not the best format for images. Many graphics applications do not open PDF files, and you cannot use a PDF file as an image in a Web page or word processing document. There are two ways to deal with this inconvenient file format. The first is to use the Preview application, a standard Mac OS X application, to convert the screenshot to a different format. You can open the screenshot in Preview using the open command.
open -a Preview screenshot.pdf
The Export function is available through the File menu and allows you to choose a different format, such as TIFF, JPG, or BMP. The other approach saves your screenshot directly to the Aqua paste buffer, using the -c option with the screencapture command.
screencapture -c -i
No filename is necessary because the captured portion of the screen is stored in your clipboard. You can paste it into a graphics application such as Photoshop or Preview and then save the file in whatever format you prefer.
ou can copy and paste using the Aqua clipboard with the pbcopy and pbpaste commands. Mac OS X keeps temporary data in a special memory space known as the clipboard or paste buffer. When you use the Copy function of an Aqua application, whatever you copy replaces the contents of the clipboard. When you use the Paste function, you paste the contents of the clipboard into the document. The Copy and Paste functions are usually listed in an applications Edit menu, or you can use the shortcuts + C for copy and + V for paste.
pbcopy < filename shell-command | pbcopy This action stores the contents of the file or the output of the command in the paste buffer, and you can paste it into other applications, such as TextEdit or Mail. If you have copied text from another application, you can access the paste buffers contents by using the pbpaste command. This command sends the contents of the clipboard to standard output, where you can redirect it to a file or pipe it to another command. pbpaste > filename pbpaste | shell-command Typing pbpaste alone displays the current contents of the paste buffer. If you have forgotten what is on your clipboard, this is an easy way to check.
The pbcopy command reads text from the standard input and places it into the Aqua clipboard buffer. You can use this command to read a files content into the clipboard by using input redirection from a file or by piping the output from another command to the pbcopy command.
contains the file that you can paste into other programs.
126
You can combine the pbpaste and pbcopy commands by piping the commands together. This action allows you to insert a shell command to modify the contents of your paste buffer. For example, you could copy the following text from a Web site using your browsers Copy function:
Nying, a dog Olorin, a cat Kim, a dog Angie, a dog
You can use the following command to sort the contents and then store the text in your clipboard:
[ferro:~] user% pbpaste | sort -bfi | pbcopy
If you paste the text into your word processor, the list of pets is sorted:
Angie, a dog Kim, a dog Nying, a dog Olorin, a cat
You can extract a list of the dogs only with the following pipe through the grep command:
[ferro:~] user% pbpaste | grep dog | pbcopy
127
ou can copy a file and its resource fork using the ditto command. Mac OS X uses resource forks to store additional information about the file. A resource fork is a hidden file that accompanies another document. When you use Aqua applications, resource forks are created automatically but are kept invisible to both the Mac OS X Finder and the Unix shell. To list resource forks in your current directory, type this command: [ferro:~] user% ls -l */rsrc You see that your files are shadowed by smaller files of the same name with /rsrc appended. Each of these files contains encoded information about which application created the file and other types of metadata. Aqua applications use this information, but Unix shell commands ignore it.
The Unix cp command does not normally copy resource fork files because they are effectively invisible to most shell commands. If you copy a file or directory with cp, your copy does not have a resource fork. However, resource fork sizes are included in the disk usage totals provided by the du command; thus, your copy may not appear to be the same size as the original. The ditto command is another way to copy files and directories. Unlike the cp command, ditto copies a directory and its contents automatically so you do not need to include an -r option as you would with cp. You do need to include the -rsrcFork option: [ferro:~] user% ditto -rsrcFork original copy This action produces a copy with the resource forks preserved.
COPY A FILE
The ditto command copies the file and its resource fork.
128
Two other commands work with resource forks to ensure that the Mac OS X Finder has access to metadata. These commands are the CpMac and MyMac commands. CpMac is a version of cp that copies files along with resource forks, and MvMac is a version of mv that moves files while preserving resource forks. The CpMac and MvMac commands are not automatically installed on all Mac OS X computers, but are on the Mac OS X Developer Tools CD-ROM. For more information on installing the Developer Tools, see Chapter 12. The executable files for the CpMac and MvMac commands are stored in the /Developer/Tools directory. If you have not added that directory to your shells path, you will have to type the full pathname to use these commands.
Example:
[ferro:~] user% du -s cat-pics/ 48744 cat-pics/ [ferro:~] user% cp -r cat-pics/ cat-pics-cp [ferro:~] user% du -s cat-pics-cp 37872 cat-pics-cp [ferro:~] user% /developer/Tools/CpMac -r cat-pics/ cat-pics-CpMac [ferro:~] user% du -s cat-pics-CpMac 48744 cat-pics-CpMac/
COPY A DIRECTORY
The ditto command creates a copy of the directory and copies the resource forks as well.
129
ou can run Applescript commands or files from the command line, letting you access and control other Mac OS X applications. Applescript is a simple but powerful programming language built into the Mac OS X. It is relatively easy to read and understand because it uses a syntax similar to English. For example, to have the Finder application create a pop-up dialog box, you can use the following Applescript: tell Application Finder to display dialog Good morning!
The first version runs a file containing an OSA script language; you do not need to set the script-file executable. If you omit the script-file argument, the osascript command reads lines of script from the standard input. The second version of the command reads and executes a single line of script that is specified on the command line. You can include multiple -e arguments if you want to execute more than one line of script at the same time. The default scripting language for osascript is Applescript. If you have another OSA language installed, you can specify it by giving a -l option to osascript, followed by the name of the language. You can use the Applescript language in many more ways than shown here. You can use Applescript to control most Mac OS X applications. To learn more about the Applescript language, www.apple.com/applescript for Apples Web site.
The Applescript language follows the Open Scripting Architecture (OSA) standard, making it an OSA language. For a full list of OSA languages installed on your computer, you can type the osalang command. To execute scripts written in OSA languages from the command line, use the osascript command. There are two forms of this command: osascript script-file osascript -e one line of script
RUN APPLESCRIPT FROM THE SHELL
The osascript
The osascript
The osascript
131
ou can make shell scripts that you can run by doubleclicking their icons in the Mac OS X Finder. A script is clickable if the name of the script file ends with the suffix .command. Ordinary shell scripts are not clickable. Double-clicking a shell scripts icon opens it in a text editor instead of running it. To make it clickable, you can make the script executable by using the chmod command and giving it a name ending in .command.
#!/bin/csh # top.command: # This script will start the top command with the options # you prefer. It can be run by doubleclicking the file # icon in the Finder. top -u -s5 seconds # sort by CPU, update every 5
When you double-click the icon of a .command file, the Terminal program opens a new window and executes the command in that window. For example, if you want to run the top program in a shell window, you can write a shell script like this:
CREATE CLICKABLE SHELL SCRIPTS
If you save this file as top.command and set it as executable, you can double-click the icon to start the top command. You can also add a new icon using the Mac OS X Finder. You can make other types of executable programs clickable by renaming them to .command filenames as well.
132
ou can use any file found in the Mac OS X Finder by dragging the icon onto the Terminal window. The pathname of the file appears in the shell as if you had typed it. This capability is useful if you are deep within folders in the Finder and you want to use a shell command on a file you have found. You can save typing in this way and make it much less likely that you will mistype a pathname. For example, to get a long directory listing of a file, type a partial command and a space: [ferro:~] user% ls -l
release the mouse button, the file is not moved, as it usually would be if you dragged the icon to a new folder. Instead, the files full pathname is pasted onto your Terminal window: [ferro:~] user% ls -l /Users/user/Pictures/kitty/olorin1.jpg You can then press the Return key and execute the command. This action works with any file, including folders, to paste the directory path of a dragged folder into the Terminal window. You can drag multiple files to the Terminal if you are typing a command that takes several arguments, such as the diff shell command. You need to remember to type spaces between each file, or the pathnames will not be separated and will be read as one long pathname.
Then switch to Finder and locate the file. Click and hold the mouse button on the files icon and then drag it to whatever part of your Terminal window is visible. You do not need to be able to see the full window, only a portion of it. When you
DRAG PATHNAMES TO THE TERMINAL WINDOW
133
If your Macintosh is a home-based system, you will probably hook up to the network using a dial-up or DSL connection. If your Macintosh is on your desk at work, you will probably hook up to network wiring that is installed throughout your building. After you are connected, you can use all the services of the Internet from the classics, such as telnet and ftp, to Web surfing and more. Home-based systems almost always rely on technology that automatically assigns an address to the system and directs it to a name server and router that allows it to reach other systems. Although these topics are not covered in depth in this chapter, you should know the names of these services. Dynamic Host Configuration Protocol (DHCP) dynamically assigns IP addresses to its client systems. Domain Name System (DNS) allows you to look up domain names, such as www.apple.com, and retrieve their IP addresses.
System Preferences...
134
10
Connecting to the Internet allows you to take advantage of a wealth of information and services. Understanding the basics of how this connection works will make it easier for you to report on and resolve problems when they occur. For dial-up accounts, you generally do not need to be concerned about the IP address, subnet mask, DNS server, or default router that your system will use. Although this information is critical to your network connection, your Internet service provider (ISP) assigns it when you connect. If your Macintosh is attached to a local area network, you might use a static IP address one that is permanently assigned to your system or one that a DHCP server assigns when you boot your system. Regardless of how this information is assigned, your system requires a unique IP address to identify it as a member of a network, a subnet mask to allow the system to determine the extent of the local network, a default router to direct remote connections, and a DNS server to allow you to locate systems by name.
135
house number. A subnet mask allows a system to determine when systems are on the same network and when they are not. When the network portions of two IP addresses are different, the systems are not on the same network. The default router is a system on the local network that forwards communications to remote systems systems not on the local network. While all of these addresses are essential for network connections, it is more convenient to use fully qualified domain names such as www.apple.com to communicate on the Internet instead of IP addresses such as 17.254.0.91. For this to be possible, you need to use a service that translates names into IP addresses and vice versa. The service that translates between domain names and IP addresses is called the Domain Name System and is generally referred to as DNS. The nslookup command allows you to make use of DNS services on the command line.
10
TYPE THIS:
[ferro:~] cat /etc/resolv.conf
RESULT: The content of the resolv.conf file showing DNS configuration data is displayed.
137
ou can gather quite a bit of information about a domain by using the nslookup or the whois commands. These commands provide information that can be helpful if you want to know how to reach someone responsible for a domain. Such information can also be useful in troubleshooting. The primary function of DNS is to return IP addresses in exchange for fully qualified domain names such as www.apple.com. The secondary function is to return fully qualified domain names in exchange for IP addresses. These, however, are only the most obvious services that DNS provides to the systems that use the service around the clock and around the globe. DNS also provides several other useful functions. For example, DNS maintains and can provide information about a domain and its registration. You can retrieve information about a domain by requesting the statement of authority (SOA) record with the nslookup command. The SOA record includes a statement about the
LOOK UP DOMAIN INFORMATION
server's zone of authority what information it can vouch for and usually provides a point of contact. It also contains the serial number and information about when zone information expires. The DNS mail exchanger (MX) record identifies the mail servers for the domain. These records determine which systems are contacted when another system needs to deliver e-mail to someone with an address at that domain. You can also get this information using the nslookup command. The whois command looks up information in the Network Information Center (NIC) database. This information includes the registrar and the name servers responsible for the registration. If you are curious about a domain that has a name similar to your own or you want to determine whether you can buy it, the whois command will provide you with some basic information.
138
10
DNS records include those defined in the table below. RECORD TYPE A CNAME PTR MX SOA FUNCTION
Maps a domain name to an IP address Provides an alternate name or alias for a system Maps an IP address to a domain name Identifies a mail exchanger for a domain Provides information about the domain as a whole
There is not necessarily a one-to-one correspondence between fully qualified domain names and IP addresses. A single fully qualified domain name can resolve into multiple IP addresses. This indicates that connections to these systems are being distributed in such a way that each system in the set is responding to a share of the overall traffic. A single system may have virtually any number of fully qualified domain names, and this is, in fact, often the case with ISPs that provide Web site support for hundreds or thousands of customers. For this to work, each of these domain names must resolve to the same IP address.
Type set querytype=MX and press Return. Type a domain name and
press Return.
139
iewing network connection information is especially helpful when you are troubleshooting connection problems. For example, you can check if your network connection is running or determine your netmask with the ifconfig command. You can examine your network connections, view the state of your network interfaces, determine what connections are established, and form an idea of how well your network connections are performing.
All networked Unix systems have at least two network connections. One is the normal connection associated with the network adaptor and used to communicate with other systems. The other is called a loopback and provides the means for a system to use network protocols while communicating with itself. The loopback address is associated with the same IP address on every Unix system. That address is 127.0.0.1. The normal or network IP address is different on every system and, if dynamically assigned, might also be different each time a system connects to the network.
EXAMINE YOUR NETWORK CONNECTION
Both network connections serve an important function and you can examine both with the ifconfig command. The ifconfig interface configuration command provides information on the network interfaces established on a system. This information includes what addresses are assigned to each interface and whether the network interface is operational. The ifconfig command also displays the subnet mask associated with your network connection. This information is critical to proper functioning on a network, both for proper functioning on the local network and the ability to communicate over the Internet. Another informative command for examining your network connections is netstat. This command provides a listing of your routing table a table used in directing network traffic and details about current network connections as well as network statistics that provide insight about how well your network connection is working. This includes how busy your network interface is and what types of traffic your system is handling.
USING IFCONFIG
USING NETSTAT
dial-up IP address, and network interface addresses appear. Both interfaces are operational.
140
10
Unix systems, especially those that are servers, generally have many established connections at any point in time. At each end of a connection, a system is communicating via a port. A port is an address associated with a service requester on the client end and a service on the server end. Ports enable software such as Microsoft's Internet Explorer to communicate with a service such as Apache. The netstat command allows you to view which systems are communicating and which ports they are using in the process.
Network connections are based on TCP. TCP is one of the primary protocols making up TCP/IP and the one that almost all network tools use. Network connections run through a series of states starting from the initial connection request and ending with its closure. Ports on servers listen for requests. When a client request arrives, the client and server exchange information and a connection is established. You can view established connections using a netstat command. Information provided by the netstat a command includes the names or addresses of the systems at both ends of each connection as well as the port or service address that is being used. Viewing netstat output can help you determine how many connections your system is supporting and how well it is performing under the load. TYPE THIS:
[ferro:~] netstat -a | grep ESTABLISHED
141
connection. If your system receives a reply for every request, you probably have a good connection. Another useful command for testing network connections is traceroute. The traceroute command attempts to time the connection between your system and each successive router in the route between you and the target host. The result is a list of each hop, along with reports on how long it took to reach each system. This timing information can be used to interpret the quality of the connection. Both ping and traceroute rely on a protocol called the Internet Control Message Protocol (ICMP) that is sometimes blocked on routers. Because of this blocking, you might get inaccurate results if you ping or run traceroute on a system. The results may suggest that the system is unreachable, but you may be able to reach it with a telnet or ssh command.
Type ping followed by a space. Type www.microsoft.com and press Return. Press Control + C after
waiting 10 seconds or more.
The ping command displays a summary of its responses. No packets were lost or
unanswered.
The ping command displays a summary of its responses. If no replies were received,
the ICMP protocol is probably being blocked.
142
10
RESULT:
PING 192.74.137.5 (192.74.137.5): 56 data bytes 64 bytes from 192.74.137.5: icmp_seq=0 ttl=240 time=157.03 ms 64 bytes from 192.74.137.5: icmp_seq=1 ttl=240 time=166.589 ms ^C - 192.74.137.5 ping statistics 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 131.532/157.241/191.94 ms
TYPE THIS:
netstat -an | grep ESTABLISHED
RESULT:
[ferro:screenshots] user% netstat -a | grep ESTABLISHED tcp4 0 0 east-18-34.dynam.49218 fajita.toad. net.http ESTABLISHED
Traceroute responds
with a header line and a single route timing line.
An asterisk in place of a
time means that the response did not come back in time to be counted.
143
ou can take advantage of accounts and applications on other systems. You can log on to a remote system using telnet or rlogin. Unix systems, such as Mac OS X, provide several ways for you to log on to other systems. The most established of these is a tool called telnet that has been available longer than the Internet. Telnet establishes a terminal-like connection to another system. If the remote system has telnet services enabled, it asks you for a username and password and logs you on. Most telnet servers give you the option of logging on with the username you are using on your local system, but you are free to enter a different username at the prompt. You end a telnet session by logging out. For most systems, you can press Control + D or type the command logoff to exit.
Another tool for logging on to remote systems is rlogin. This tool is much like telnet, but less common. You are likely to find it only on Unix systems, and even then, it may be disabled. The rlogin command requires that you log on with the same username that you are using on the local system unless you add the -l newname argument to the end of the command. To use any of these tools, you must have an account on a remote system. If you do not have a shell account on another system, however, you can try telnet or rlogin by logging on to your Mac OS X system. The logon will only work if you have enabled remote access. See the section "Enable Remote Access to Your Computer" later in this chapter.
USING TELNET
Type who am i and press Return if the remote system is a Unix host.
Note: Type telnet localhost if you do not have a remote system account.
144
10
You can use telnet to test connections to other systems by supplying a port number in addition to the system name on the command line. If you want to check how many messages are in your inbox on a system that supports POP3, you can connect to the port that services the POP3 server and ask for this information using telnet. You can also use telnet to determine whether a mail server is responding. POP3 is a simple protocol used to download e-mail from the mail server.
TYPE THIS:
[ferro:~] telnet <servername> 110
Use the name of a server from which you receive e-mail using POP3. After the system responds, enter the following lines, replacing the text in brackets with your account information:
user <your username> pass <your password> stat quit
RESULT: After the stat command, the system displays a number telling you how many messages are in your inbox.
USING RLOGIN
LOG OFF
In a Terminal window,
type rlogin followed by a space.
145
TRANSFER FILES
ou can often obtain needed files and applications from other systems. You can move files between your system and others using ftp. Approximately as old as telnet, the ftp command has been enabling Unix users to upload and download files for a couple of decades. The protocol, or language, of ftp is fairly simple, although some ftp servers have implemented a wide range of commands.
In its simplest form, ftp allows you to log on to a system, upload files using the put command, download files using the get command, and move around the directory structure on the remote system. You can transfer data in binary mode or ASCII mode. ASCII mode is designed for text files, and ftp translates line endings if you are transferring text files between Unix and DOS systems. Binary mode is designed for software, image files, and other types of files that use non-printable characters that might otherwise interfere with the transfer.
One popular form of ftp is called anonymous ftp. When using anonymous ftp, you type the word anonymous as if it were your username and your e-mail address (or sometimes any string of characters) as your password. Anonymous ftp allows people who do not have accounts on a system to upload or download files. For example, if you set up a drop box for your customers to upload error logs so you can analyze problems they are having with software you sold them, you might chose anonymous ftp. Many companies, such as Apple, that provide documentation and software tools to their customers do so using anonymous ftp. You should cd into the directory in which you want downloaded files stored before you start your ftp session. Like telnet, ftp is not enabled as a service on Mac OS X when you first install the operating system.
TRANSFER FILES
146
10
You will have an easier time figuring out what went wrong in a file transfer if you know what to look for. Files that you download incorrectly will have problems. Binary files that you transfer as if they are text files are likely to be corrupt and probably unusable. If you attempt to display or otherwise use the files, the system will display an error message. Text files that you download as binary are likely to be fine if you download them from another Unix system. However, a text file that you download in binary mode from a Windows system is likely to have an extra character at the end of every line. This character represents the carriage return that Unix systems do not use. It displays as ^M when you open these files with an editor.
Example:
Making Better Use of Ping^M ^M Long one of the system administrator's favorite tools for^M troubleshooting network-related problems, ping is used^M
You can remove these unwanted characters using the Unix tr command.
Example:
[ferro:~] cat textfile | tr -d "\015" > textfile$$ [ferro:~] mv textfile$$ textfile
147
ssh server such as sshd. For some ssh connections, you will log on with username/password pairs. For others, you may be provided with a digital certificate. If your username is not the same on both systems, you must use the l option. From a user's point of view, using ssh in place of telnet or rlogin makes little difference. The process and the result are nearly the same, especially if the user logs on with a username and password. The encryption and decryption securing the transferred information is completely transparent. When digital certificates are installed on the client and server end of a connection, the process of logging on may be simplified even further. However, the logon only works on systems that have had the certificates installed. Similarly, you can use sftp in place of ftp to securely transfer files. When you use sftp, the files you download are encrypted during the download.
148
server.
10
If you need a file that is on a remote system and your are limited to using secure connections, you can still download files, but you must use sftp instead of ftp. When you use sftp, your download files are encrypted between the remote server and your system, making it safer to download sensitive files. You can download a file using sftp in the way just described or by entering a one-line command in a Terminal window. Type the line shown below, replacing the portions of the command in brackets with your data.
Example:
[ferro:~] user% sftp user@remote.system.net: /home/user/myfile.txt Connecting to remote.system.net... user@remote.system.net's password: Fetching /home/user/myfile.txt to myfile.txt
149
ou can download files with very little effort by using the curl command. Although the most obvious way to download a Web page is to type or copy the URL in your browser's Address block and use the Save As feature, this is not necessarily the easiest or most efficient method. Mac OS X includes a command line tool called curl copy URL for downloading Web pages. Curl works with a number of protocols, including HTTP, HTTPS, FTP, GOPHER, DICT, TELNET, LDAP, and FILE. Not only does curl allow you to download Web pages on the command line, but it also allows you to download files using curl commands in a script. In fact, you can download and install files in a completely unmanned fashion. The syntax of the curl command is flexible enough to allow you to access multiple pages or multiple sites with a single command.
To use curl, you type curl followed by any of the options that you want to specify and the URL string. A command such as curl -O http://www.sandrich.com/index.html copies the specified file from the specified site to your current directory using the same filename. Without the -O, the curl command downloads the file to your screen and presents you with lines of HTML. Curl allows you to copy more than Web pages. You can also use it to download binary files, including image files and software. In fact, the command is so efficient that Unix tools designed to locate and download applications from the Internet often use curl to do the downloading. You can specify multiple URLs or portions of URLs by enclosing the strings you want to match within braces. The string www.{a,b,c).com, for example refers to the three systems www.a.com, www.b.com, and www.c.com.
Type -O followed by a
space.
Type -O followed by a
space.
150
10
Curl can post to Web sites as well as download files of various kinds. Posting commands include the name of the script to be executed along with the parameters that you would enter in the online form. You need to know quite a bit about a form to successfully post to it. The example below assumes that the parameters birthyear and vote are being collected by the online form. It also assumes that the data is processed when a button is pressed and that the value of the press equals OK. A post command in curl might look like the following:
curl -d "birthyear=1985&vote=1&press=OK" www.site.com/vote.cgi
This type of command can be used in a script to automate posting. To learn more about curl and how you can use it in scripts, you can read the man page or download a tutorial available online. TYPE THIS:
[ferro:~] curl -O http://curl.planetmirror.com/ docs/httpscripting.html
Type -O followed by a
space.
Type echo n "URL> " and press Return, then type set URL = $< and press Return twice. Type cd ~/src; curl O http://$URL. Save your file, and exit
Pico.
151
ou can allow others to log on to your computer or make it possible for you to log on to your Mac OS X system from another system.While Mac OS X systems make it possible for you to log on to remote systems, browse Web sites, and download files, they do not allow others to log on to your system or access files on your system. If you want to allow this type of access, you have to enable it by modifying your system's configuration. There are two basic ways to provide a network service on your Mac OS X system. You can start the service for example, start up a Web server by typing the name of the server process on the command line. These services are designed to run in the background and continue running until you shut your system down or kill them. See Chapter 7 for
more information). Alternatively, you can configure the service to start whenever a request arrives. In this latter case, another process listens for requests on behalf of the service and starts it as needed. The decision as to which method to use depends on the particular service. Web servers, such as Apache's httpd, are better run all of the time. This provides better Web performance. Services such as ftp and telnet that are used only now and then are better run on an asneeded basis. You configure as-needed access through the /etc/inetd.conf file. To modify system configuration information in Mac OS X, you need to be a privileged user. The sudo command, which allows you to run a command as root, works well for this purpose if you are allowed access.
152
10
TYPE THIS:
[ferro:~] sudo date [ferro:~] sudo date
RESULT: On the first call to sudo, the system asks you to enter your password. On the second call, it does not.
Type ps -aux | grep inetd and press Return. Type sudo kill -HUP
followed by the process ID for inetd and press Return.
The inetd process reads the /etc/inetd.conf file, enabling the ftp server.
The ftp service that you just enabled responds to your request.
153
ou can effectively administer a Mac OS X system by learning some basic commands. Unix administration is a complex job, but Mac OS X provides many tools for making the job manageable.
SYSTEM ADMINISTRATOR
The basic responsibilities of any Unix system administrator are to keep the system running smoothly and to ensure that important data and configuration files are preserved. To administer a Mac OS X system, you need to understand the fundamentals of file systems, know how to set up user accounts, recognize when the system is having problems, and be prepared to manage applications and disk space. System administrators routinely back up the systems they manage. This allows them to restore files if the
system crashes or if someone mistakenly deletes the wrong files from their account. System administrators also manage accounts for other users. They establish an account for each user and ensure that the user can use the tools and applications they need. Users in large companies can often rely on help from a user support team. If you are using Mac OS X at home or in your small business, you are probably responsible for managing the system yourself; in effect, you are your own system administrator.
ACCESS PRIVILEGES
Critical to the role of a system administrator is the concept of privilege. In order to install applications and modify configuration files, you need to have access to the root or superuser account or to be a privileged user. A normal user on a Unix system can only work on files in their home directory. The root user has virtually unrestricted access to the system. As a result, the root user can modify files
belonging to any user, modify any configuration file, and shut the system down or reboot it from the command line. While the privileges assigned to the root user are most significant when a Mac OS X system is managed by one person and used by many, use of the root account is important even on systems where root and user are one and the same person.
154
11
Mac OS X is not only different from Mac OS 9 and earlier versions of Mac OS, it is also different from other versions of Unix. For example, the root user on a Mac OS X system is disabled by default. This means that you cannot simply adopt the root identity and run commands that you are not allowed to run as a normal user. Instead, you need to either preface these commands with the word sudo, or you need to activate the root account. COMMAND apropos chown compress crontab -e crontab -l df du dump fastboot fdisk file find fsck gunzip gzip halt ifconfig kill ln lpq MOST COMMON USE
Find related commands. Change the owner and, optionally, the group of a file. Compress a file. Edit a cron file. List cron jobs. Display free and used disk space. Display disk space usage. Dump a file system to a backup device or a file. Reboot the system without a disk check. Examine or change DOS partitioning information. Determine the type of a file. Find files using particular criteria. Check the integrity of a file system. Unzip a file zipped with gzip. Compress a file. Shut down a system immediately. Display or change network interface information. Send a signal to a process, possibly terminating it. Create a symbolic or hard link to a file. Display a printer queue.
You also need to know the basic file system layout where the system stores files and you must also know whether you should pay attention to the files you find in the /etc directory the normal configuration directory on Unix systems. The table below contains a list of some of the most important Mac OS X commands for system administrators. COMMAND man mount netstat newfs nidump nireport nslookup passwd ping ps reboot shutdown MOST COMMON USE
Present the manual page for a system command. Attach a file system to the system. Look at routing tables, network connections, or network statistics. Create a new file system. Display network information from NetInfo. Print tables from NetInfo. Look up DNS information. Change the password for a user. Test the connection to a system by asking for a reply. Display information on running processes. Shut down and reboot the system. Shut down a system gracefully. immediately.
shutdown -r now Shut down and reboot a system strings tar top touch umount uncompress
Display the strings in a binary file. Create a file archive or read from one. Display statistics on the most demanding processes. Update the last changed date on a file or create an empty file. Unmount a file system which is currently mounted. Uncompress a file compressed with the compress command.
155
ou can shut down or restart a Mac OS X system from the command line instead of the Aqua interface if you have access privilege. This is useful if you are not sitting at the system keyboard. The command to shut down Mac OS X is shutdown. Although it is not the only way to shut the system down, it is the safest. Using the shutdown command allows you to send warning messages to users still logged onto the system that you are shutting down the system. This gives them time to finish up what they are doing and log off.
You can also specify a warning message that appears to users. You can tell users that, although the system will be shutting down, it will be available again at a specified time. For example, the command shutdown +15 "ferro must be shut down for emergency service, please log off" allows your users to finish work they are doing, while letting them know that the system may be down for quite a while. The halt and reboot commands do not provide users with a grace period to complete their work, but terminate running processes before the shutdown. Both commands have options that change the way they run. For example, with a -q argument, both of these commands shut down without terminating processes first.
You can specify the time at which the system shuts down by entering a time in the yymmddhhmm format, or you can enter a number, such as +15, to specify that the system shuts down in 15 minutes.
156
11
If you enable the root account, you can shut down or restart the system without using the sudo command. When you do not have the root account enabled, you need the sudo command to give you the authority of root while you execute the shutdown command. The same is true of the reboot and halt commands. Though the shutdown, reboot, and halt commands may appear simple, there is a lot that happens during the shutting down or booting of a system.
You can simplify the process of restarting or halting a system by using the fastboot or fasthalt commands. These commands save time in the boot and halt processes, respectively, by skipping the process of checking your disks for integrity. Though these commands may save you time, you should use the more comprehensive shutdown and halt commands as they help ensure that your file systems remain intact. If you look at /rc.boot and /etc/rc files, you can get an idea about the processes that run when a system boots. The scripts in these files manage a large part of the boot process.
STOP A SHUTDOWN
Type sudo shutdown +5 "system going down for maintenance" and press
Return.
157
ou can easily add a new user to your Mac OS X system by using the Accounts tool found in System Preferences, or from the command line in a Terminal window. When you add a new user to your system using the Accounts tool, you must fill out a form with information describing the new user. You need to assign a username and a password. If you want, you can supply a password hint to help the user when they cannot remember the password. You can also incorporate an image into the logon page. When you use the command line method to add new users, you can create a file containing the information describing the new users, or you can build a script containing a series
of commands that add the new users to the system. Current account information may or may not appear in the /etc/passwd file on your system. Mac OS X does not use the information in the /etc/passwd file but uses similar information stored in a database called NetInfo. You can use the nidump command to list the password information that your system uses. Similarly, you can load new information into the NetInfo databases using the niload command. The niutil command allows you to read and write NetInfo data. For example, using the niutil command, you can add each portion of a user record to the database using a separate command, or modify a portion of a user record.
158
11
efficient. The script below contains niutil commands that prompt for each piece of information it needs to create a new user, $user.
-create . /users/$user -createprop . /users/$user -createprop . /users/$user -createprop . /users/$user -createprop . /users/$user -createprop . /users/$user -createprop . /users/$user -createprop . /users/$user
passwd uid $uid gid $gid realname $fullname shell $shell home $homedir _shadow_passwd ""
mkdir $uhome chmod 755 $uhome chown $user $uhome echo "password: " passwd $user
159
ou can enable the root user account, which allows you to switch user to root or to log on as root in addition to exercising root authority using the sudo command that allows you to run commands as root if you are an administrator. The root account on a Unix system is the only account that can perform any action; you should use it sparingly as the system is not protected from any action that this user takes. While normal users cannot overwrite files that do not belong to them, root can overwrite any file on the system, regardless of who owns it and how important it is to the proper running of the system. To use the sudo command, you type sudo followed by the command you want to run as root. There are times when logging on as root or switching user to root simplifies the work that you have to do, but you
must always be careful when you do so. Use of root privilege allows you to modify system configuration files, store files in directories that are owned by root, shut down or reboot the system, and add or remove user accounts. The root account is disabled by default in the root account information stored in your NetInfo database. This means that you cannot log on as root, nor can you use the su command to switch users. You can enable it in one of two ways. The first is to use the NetInfo Manager. To do this, you need to authenticate yourself by entering your password, after which you can initiate the change in the root account by selecting an option to enable the root account. The second method is to change the root password from the command line.
Note: For instructions on locating the NetInfo Manager in the Utilities folder, see page 4.
An administrator name
and password dialog box appears.
Click Security
Authenticate.
160
11
TYPE THIS:
[ferro:~] user% su Password: [ferro:~] # pwd
RESULT:
/Users/user
TYPE THIS:
[ferro:~] user% su Password: [ferro:~] root# pwd
RESULT:
/private/var/root
Security
Click OK.
The root user password is
changed, enabling the account.
In a Terminal window,
type sudo passwd root and press Return.
appears informing you that you must re-authenticate to make additional changes.
161
ou can run arbitrary commands as root by using the sudo command regardless of whether you decide to enable the root account on your Mac OS X system. In order to use the sudo command, you must be a user with system management privilege. If you have this privilege, you can make use of root privilege when you need it by inserting the word sudo in front of any command that you require root permission to execute. You do not need root privilege to work on your own files, and you should not use root privilege when you do not need it because the system has no protection against the actions of this all-powerful user. The sudo command uses a configuration file that includes a list of the users or user groups allowed to run commands as root. While this configuration file permits a precise level of
EXECUTE COMMANDS AS ROOT
control over privileges, the default setup gives privileged users the ability to run any command as root. Privileged users are given privilege when they first establish their accounts. However, this privilege derives from their membership in the admin group. The sudo command prompts you to enter your password every five minutes. This process of re-authenticating the user helps to ensure that the user running the command is really the privileged user. You can use the nidump command to display a list of users allowed to use the sudo command. The default sudo setup places no restrictions on the commands that privileged users can run and is not a mechanism for limiting privilege.
The passwd command prompts you to enter the new password for the other user.
11
The sudo command allows you to give limited root privilege to trusted users. For example, you can allow a junior administrator to set up accounts for new users or to cancel print jobs. By configuring a limited set of commands in the /etc/sudoers file for certain users, a system administrator can delegate certain system privileges while not giving out access to the root account. To use sudo in this way, you need to create a list of commands that one or more users can run as root, and then restrict them to the list of commands. Type sudo visudo and add system and usernames to reflect users on your system.
Example:
kynn,sandra,eric kynn ferro=/sbin/dump,/sbin/restore ferro=/sbin/shutdown
These lines allow the first group of users to use the dump and restore commands and the second to shut down the system.
ou can safeguard your work and protect your system by backing up your files. Maintaining a set of backups is always a good idea. Mac OS X cannot prevent a user from removing a file or a set of files that they may still need. There are, however, quite a few tools that you can use to back up your files.
Most Unix systems use the dump command for regular system backups, although you may need to dump to a remote tape drive to use this command. The dump command can back up a complete file system or select only those files that have changed since the last backup. This latter method of backing up is called an incremental backup. While dump is a good Unix command, the Mac OS X version can only back up an entire file system, fully or incrementally, and only works with Unix file systems (UFS). If your Mac OS X installation is an upgrade from Mac OS 9 or earlier, your file systems may all be HFS+. If this is the case, you might consider downloading the hfspax software available from www.homepage.mac.com/howardoakley. This software works well with data and resource forks and provides a command-line interface.
Some Unix commands such as cp and ditto allow you to make copies of files. Many long-time Unix users make a habit of copying important files before editing the originals, in case they need to restore them and start over again. Other Unix commands allow you to create archives of important files. This is a great way to save a copy of all the files associated with the project in a single file. The tar command works well for this purpose.
Note: You can also type the name of a set of files, such as *.txt.
164
11
To initiate a restoration from a dump, use the restore -ivf command followed by the name of your backup device or dump file. Use cd to move between directories, followed by the name of a file to select it for restoration, and extract when you are ready to begin restoring the files. On Mac OS X systems, the dump command can only back up an entire file system. Because you are probably working with a single partition, it requires a large-capacity device to create a backup. The dump command can write to the tape drive on a remote system if you configure the remote system to allow this.
You can use the restore command to restore files from the backup that you create with the dump command. The restore command can restore an entire file system, although you usually only need to restore a single file or set of files from your backup. In this case, you can use the interactive mode of the restore command to navigate within the backedup files. You can then select those files that you want to restore and initiate their restoration. The restored files appear in a subdirectory of the directory where you run the restore command.
165
A similar command is chgrp. The chgrp command changes the group associated with a file or set of files. If you need to share a set of files with a group of other users, you can add these users to the group associated with the file or change the group for the file. In general, changing the group for the file is easier. The chgrp command has a similar syntax to chown. If you type chgrp devt myapp.java, then anyone in the development team obtains group access to the file. If members of the group can write to the file, this allows anyone in that group to modify the file. Like chown, chgrp can be run recursively with the -R option.
Type ls -l followed by a
space, then the name of the file, and press Return.
Type ls -l followed by a
space, the name of the file, and then press Return.
166
11
When you change the group and ownership of a file, you do not affect the contents of the file in any way. Information about a file, referred to as metadata, is stored in a separate location from the file itself. You affect this metadata when you change ownership or the permissions associated with a file. Metadata is stored in a file system structure known as an inode. You see metadata every time you list file information using the ls l command. You can list files with the numbers of the inodes that are associated with these files by using the i option instead. It is sometimes useful to know which inodes are being used. For example, two files in the same file system with the same inode refer to the same content.
RESULT: 139742 AnnaRoof.JPG 143416 AnnaSky.JPG 141835 AugSky1.JPG 140953 NoLaneBridge.JPG 140093 OldBarn.JPG 140095 OldBarn2.JPG
Type ls -l followed by a
space, the name of the file, and then press Return.
Type -R followed by a
space.
167
ou can simplify the navigation of your file system by creating symbolic links. A symbolic link is a special file that acts as a pointer or shortcut to another file or directory at another location in the system. By creating a symbolic link to a directory with a long or difficult pathname, you can move to the directory by typing cd followed by the name of the link you create. If you want to create a shortcut for moving into or listing the contents of the directory /Applications/Utilities, you can type the command ln -s /Applications/Utilities util. The full pathname specifies where you want your link to point, while the final argument specifies what you want to call your link. The -s argument tells the ln command that you want to create a symbolic link.
After you type this command and press Return, you can type commands such as ls utils or cd utils. If you only specify the file or directory that you want to point to when you type the ln -s command, the link receives the same name as the original file. If you share a set of files with other users, and those files are not stored in your home directories, you can use symbolic links to simplify the sharing process and better organize the shared files. If you do not include the -s argument, you create a hard link instead of a symbolic one. A hard link is a special copy of a file, in that it is a reference to the original file. Though it looks like a file that is completely independent of the original, it is the original file with a new file system reference; any changes to the original file are reflected in the link.
Type ls -l followed by
space.
Type ln -s followed by a
space.
168
11
ls -l /bin/csh ls -l /bin/tcsh
RESULT:
167100 /bin/csh 167100 /bin/tcsh
original file appear, showing that your symbolic link connects to the original file.
Type ls -l followed by a
space, the names of the two files separated by a space, and then press Return.
169
ou can use the df and du commands to determine how much space is available on your disks and how much space is used, respectively. The df command tells you how much disk space is allocated, used, and available. When you use the df command with a -k argument, disk space appears in kilobytes instead of 512-byte blocks. One of the columns that appears in the df output is Capacity. This column shows you how much room in that file system is already used as a percentage of the overall space available. Most Unix system administrators try to keep file systems at less than 90 percent of capacity simply because they perform better when there is adequate free space. You can use the du command to determine how much space a particular directory uses. This command can help you track down files that consume a lot of space in a file
system that is running out of space. For example, if you cd into a particular directory and use the command du sk * | sort n, you receive a list of the contents of that directory sorted in size order. This is very helpful if you want to know where most of the disk space is being consumed. You can use the df -k command periodically to see how much space remains on your disk. When a file system approaches full capacity, the responsiveness of the system decreases, although any file system that is less than 90 percent full is not a reason for concern. At the same time, any file system that jumps in size by 10 percent in a short amount of time may do so again. The rate at which a file system is growing suggests how soon you will run out of space.
170
11
creates a generous allocation of inodes. When you type the command df -i, the system displays the number of inodes used as iused and the number available as ifree. Unless the ifree value is extremely small, you are unlikely to have any problems. The ratio of inodes to disk space is usually set so that running out of inodes is nearly impossible.
df -i
RESULT:
Filesystem 512-blocks Used Avail Capacity iused ifree /dev/disk0s 53545168 17462872 35570296 32% 2246857 4446287 devfs 201 201 0 100% 644 0 fdesc 2 2 0 100% 4 253 <volfs> 1024 1024 0 100% 0 0 %iused 33% 100% 1% 100% Mounted on / /dev /dev /.vol
Type du followed by a
space.
Type | followed by a
space.
171
ou can use the lpq command to examine your print queue and cancel print requests. This command also lists print jobs that are waiting in the queue. As the printer handles each print request, the job disappears from the queue and the next job in line starts printing. The cancel command cancels a selected print job, removing it from the queue and leaving the remaining jobs to be printed. You have numerous reasons to examine a print queue and to cancel jobs. For example, if you are waiting a long time for a printout, you can check the queue to see what other jobs are printing or should be printing. If the printer has been out of paper for a while, you can view where your print job is in the queue, and decide whether to cancel the job.
Some users request a printout of a document several times in a row before checking to see if the reason that it does not print is because there is no paper. When this happens, it is a good idea to cancel all but one of these print jobs. Other users may print a document in the wrong format and end up printing a pile of paper that they cannot use. Canceling these jobs can save you both time and paper. To submit a print job from the command line, you can use the lpr command followed by the name of the file you want to print. Applications, such as Photoshop, also submit print jobs and these also appear in your print queue. You can view all of the pending print jobs using lpq, whether the print requests are generated by applications or the lpr command and regardless of who submitted each print request.
172
11
If you need to cancel all of the jobs in a print queue, you can use the cancel command with a -s argument. This command option saves you the time of canceling jobs individually. The Print Center is a useful tool for monitoring and controlling your printer; it allows you to: determine the status of a printer; restart the printer; view the jobs that are waiting to print; and determine whether the printer is active. If the lpq command indicates that your printer is not ready, you can set it back to operational status using the Print Center. To do this, double-click the name of the printer that the lpq command tells you is inactive, and activate it again. The Print Center is located in the /Applications/Utilities folder. TYPE THIS:
[ferro:~] user%
RESULT: lpq
DESKJET_930C is ready and printing Rank Owner Job File(s) active user 3 Chap11.txt 1st user 4 oldhouse.jpg
Each job in the queue has a rank, an owner, and a job number. To cancel a job in the queue, use the command cancel followed by a space and the job number.
173
ou can learn a lot about system operations and problems by inspecting your system logs for error messages and various anomalies. System logs, stored in /var/log, record the activities of many system services such as e-mail and printing. You will find these files to be valuable as they can be an important source of information when system problems arise. The most important messages about your current logon sessions appear in a log file called console.log. You can view these messages using the Console tool, available in /Applications/Utilities. The scrollable window allows you to read the messages that accumulate after you log on. These messages include authentication failures and mounting problems. A system daemon called syslog maintains most system log files. Like numerous other daemons, the syslog daemon, syslogd, has a configuration file that it reads when it starts
up. This configuration file tells syslogd where to write each type of log message. By using the services of syslogd, other services do not have to do their own logging. The syslog configuration file, /etc/syslogd.conf, provides you with an opportunity to change where logs are written or to deactivate certain types of logging. To modify the logging operations of syslogd, you can modify the configuration file for syslogd and instruct the daemon to check the file for changes. Do not edit the default /etc/syslogd.conf file unless you want to separate particular messages or stop collecting them altogether. If you keep the Console tool open while you work, you can see these messages display as the daemon generates them. This is a good troubleshooting technique as it informs you of problems immediately and reminds you to check your log files.
Double-click
Applications.
174
11
The log file that gathers the most information on most Mac OS X systems is system.log. The system writes many routine messages to this file, and the system.log file is routinely rotated. Older system.log files are renamed system.log.0, system.log.1, and so on, and are compressed with gunzip to save space. At any point, you may have a number of these files available to you to help you track down a problem. Any log file may have thousands of records far too many for you to read the file from top to bottom. Using commands like grep and awk to extract some of this data can make the job of reviewing log data much easier. You might consider writing scripts that check for certain types of errors in your log files and report the findings to you. You can check the /etc/syslog.conf file to see where particular types of messages are written.
Double-click Utilities.
Double-click Console.
175
ou can greatly reduce the size of a file by compressing it down to a sixth or less of its original size when you use a good compression tool. Compression is a good solution for managing your disk space while not sacrificing files that you may need later on.
The other command that you can use to compress a file is called compress. The compress command compresses a file using a different algorithm than gzip. It also uses a different file extension. Files compressed with the compress command take on the extension .Z. The gzip and gunzip tools are members of the GNU tools that many Unix systems use whether they are included in the distribution or added later. These commands are included in the standard distribution of Mac OS X. Both the gzip and the compress commands use the filenames to determine whether a file is already compressed. It is possible to compress a file again after renaming it, but the subsequent gain is small, and the likelihood of confusion high.
For most files, gzip is one of the best compression tools available. It is both quick and effective, reducing files down to a fraction of their original size. It is also available on many systems, allowing you to move your compressed files to another system, confident that you can unzip them. To compress a file, you can type gzip followed by the name of the file. The gzip command creates a new file with the extension .gz appended to the end of the filename. For example, when you compress the /var/log/system.log.0 file, the resultant file is called system.log.0.gz. Unlike Windows, Unix does not care how many extensions a file has.
Type ls -l followed by a
space.
Type ls -l followed by a
space.
176
11
Most software that you download from FTP sites is compressed to reduce both the storage space requirements on the server and the time required to download the file. You can determine the type of compression used by looking at the file extensions. Files that end in .Z have been compressed with the compress command, while those that end in .gz have been compressed with gzip. You may also see file endings such as .zip, .tar.Z, and .tgz. FILE EXTENSION
ZIP TAR
DESCRIPTION
Files ending in .zip are ZIP files. Files ending in .tar are tape archive or TAR files.
BENEFIT
Many systems have zip and unzip commands and can both create and extract from these files. These files are not compressed but contain a number of files that you can individually or collectively extract with the tar -xf command. To extract the contents of one of these files, you must first uncompress it. This leaves you with a TAR file. You then use the tar -xf command to extract the contents.
TARZ/TGZ
Files ending in .tar.Z or .tgz are TAR files that have also been compressed with the compress command.
Type uncompress
followed by a space.
Type ls -l followed by a
space.
Type ls -l followed by a
space.
177
USING NETINFO
ou can explore and modify the contents of your NetInfo database. NetInfo is a service that replaces the simply formatted text files that were once used exclusively in Unix to store information about systems, users, and so on. The early Unix systems stored all user information in the /etc/passwd file, and information about the local system and other systems in /etc/hosts. Along with some additional files, also stored in /etc, the records in these files determined who could log on and what services the system could support. In the past, new lines were added to the /etc/passwd file as new user logons were created. New hosts were added to the /etc/hosts file so that the systems could communicate. Today, we use network information and lookup services such as NetInfo, NIS, and LDAP on many systems to replace the simple text files. NetInfo is a lookup service or database that contains many types of system information. In fact, if you look for your
USING NETINFO
account in the /etc/passwd file, you are not likely to find it. The system does not use these files; it uses NetInfo. Therefore, learning to browse the NetInfo information base and make changes is essential for understanding and monitoring your system. The most important NetInfo commands are nidump, niload, and niutil. The nidump command displays the NetInfo contents. The command nidump passwd . displays the passwd entries that were stored in the /etc/passwd file on older Unix systems. You can use the niload command to load new contents into NetInfo, and the niutil command for various read and write processes. NetInfo refers to the types of information that it contains as formats. There are also nifind, nigrep, and nireport commands. Read about these by entering a man command; for example, man nigrep.
The nidump command displays a usage statement along with a list of the formats that it can dump for you.
178
11
While the nidump and niload commands are relatively straightforward, the niutil command has a number of options, each of which is like a separate command. These options include -create, -destroy, -createprop, -appendprop, -mergeprop, -insertval, -destroyprop, -destroyval, -renameprop, -read, and -list. Although NetInfo works well, you should consider making your changes with a carefully written and well-tested script, and not attempt to enter all of the necessary netutil commands manually. Read the man pages for niload, nidump, and netutil to learn more about how you can use these commands.
NetInfo uses terminology that is different from that of the system. For example, not only does NetInfo maintain formats in place of files, but it also has directories in place of records and properties in place of fields. If you use the niutil command to create a new user record, you can use the niutil -create command, which creates a new directory. You can then set the values associated with the full name of the user, their Home directory, and so on, by using the niutil -createprop command.
Type . followed by a
space.
Type . followed by a
space, and then < followed by a space.
the dumped data back into NetInfo, including the account information for zoe.
179
ou can load a variety of software development tools onto your Mac OS X system. The Developer Tools CD that ships with the OS contains a complete set of development tools. This includes a number of standard programming languages, utilities, and libraries along with software management tools and debuggers. There are compilers that allow you to turn your source code into programs your system can run from scratch, debuggers special tools that help you to locate errors in your code, and tools to help you analyze performance. You can load all of the tools available on the Developer Tools CD at once, or you can open the Packages folder and select any of six individual packages that you want to install. These are BSDSDK, DevDocumentation, DevExamples, DevPBW0, DevSDK, and DevTools. During the installation of the developer tools, the installer goes through a number of phases, including an optimization phase in which the installer attempts to improve the overall
INSTALL DEVELOPER TOOLS
performance of your system. Do not be alarmed if your system slows down during this part of the installation process; this is not uncommon. The installation process may take longer than you think it should. Be patient and allow it to complete. To make your system easier to manage, you should install the developer tools on the same disk as your Mac OS X installation, if possible. You can load the developer tools from the CD in roughly half an hour. If you are operating on a local area network, you can make the developer tools available on one system and install them on other systems over the network. The README.html file is a good starting point to help you find the documentation that you need to get started. You can keep your developer tools current by periodically looking for updates at www.apple.com.
Double-click the
Developer.mpkg icon.
180
12
Click Continue.
CONTINUED
181
Developer/Documentation/Java/java.html with a browser or by double-clicking the file. This page provides links to essential information on using Java on Mac OS X, including information about the Java 2 API, WebObjects, and so on. Before viewing the Java 2 API reference for the first time, type sudo /Developer/Documentation/Java/scripts/ unjarJavaDocumentation.sh in a Terminal window. This command extracts Java API documentation from a Java archive file a jar file so that you can read it. There is also a PDF file entitled Java Development on Mac OS X that introduces you to Java development on your Mac OS X system, including Basic Java, double-clickable applications, and how to use Project Builder. QuickTime for Java provides cross-platform APIs to allow you to build multimedia components, such as streaming audio and video, for both Macintosh and Windows systems.
In the Applications directory, you can find many useful tools to help with your development projects. Among these, you find PackageMaker a tool to help you package your software for easy installation. You can also find Interface Builder a graphical interface editor for Cocoa and Carbon applications and MallocDebug to measure an application's use of dynamic memory. The Java Browser can make it easier to analyze and view your Java code. More than 20 tools are available. The Documentation directory contains documentation on many aspects of development. To get started with the Java development documentation, for example, you can open
Click Agree.
182
12
You can begin your browsing of the developer documentation by opening /Developer/Documentation in your Finder. The README file, README.html, provides a gentle introduction to the thousands of pages of documentation that you find on the system from tutorials and conceptual overviews to detailed release notes. ProjectBuilder allows you to move smoothly from looking at your code to viewing documentation. By holding down the option button and double-clicking on the particular API element, the tool takes you swiftly to the proper document or provides you with a list of relevant choices.
The developer tools are installed with a large collection of pages to help you learn about various commands. These pages should have been installed during the installation of the developer tools. You need to have /usr/share/man on your MANPATH to view the pages. You can add this directory to your path by typing setenv MANPATH $MANPATH":"/usr/ share/man or by adding to the path defined in your .tcshrc file. The latter method is a better choice as it adds this to your path every time you log on.
Click Continue.
CONTINUED
183
hile many of the tools on the developers CD are intended for Java development, there is also a large set of tools to help you build applications in other languages. The version of gcc that is included is a compiler for C, C++, and Objective-C applications. The cpp-precomp and cpp tools are preprocessors. The first works with C and Objective-C. The latter works with C++.
libtool creates both dynamic and status libraries and is used by gcc as needed. The developer tools also provide CVS, a tool for maintaining source code that also comes from the GNU Foundation. CVS allows you to maintain multiple versions of an application and to create any particular version as needed. CVS also allows multiple developers to work on the same code without the danger of overwriting each other's changes. Code is checked in and checked out so that only one individual can change a module at a time. You can determine differences between multiple versions of the same code and merge code as needed to facilitate incorporating changes from more than one individual.
The as command is the system assembler. gdb is a debugger from the GNU Foundation that is well known in the industry. The developer tools provide a debugging guide as well as a quick reference to get you started. ld is the static link editor. It combines object files into binary files such as those that make up applications and shared libraries. dyld is the dynamic link editor for Mac OS X. This tool is used by applications that load libraries as needed, rather than incorporating them as is the case when libraries are linked statically.
184
12
The release notes provided with the developer tools help you to understand what has changed in a tool since the last release. If you are new to development on Mac OS X, the release notes may not mean a lot to you today, but you may find them important after you have spent considerable time developing software and are ready to upgrade to a newer release of the developer tools. In this case, reading the release notes is a great idea as it tells you what to watch out for as you begin to work with the newer software. For an unusual introduction to Java programming, double-click /Developer/Examples/Java/Sound/Sound. After clicking Start, you can read the README.txt file and begin to learn how this sample application was created. The application loops, so you may want to hit the Stop button after several times.
You can find two of the Aqua dots, DotBlue.tif and DotGray.tif, in the Developers directory. These TIFF images look like the dots in the upper-left hand corner of your Terminal window. Sample Applescript programs are available to help with your scripting efforts.
Installation is complete.
Click Close.
185
ou can download software in one of two forms: as precompiled binaries that you can run after a quick installation process, or as source code that you must compile before you can run it. The easiest way to obtain new tools for your Mac OS X system is to find precompiled binaries. While many sources of precompiled binaries exist on the Web, you can only use those that are built specifically to run on Mac OS X. The advantages of starting with source code are first, that you can study the source code and determine exactly how a tool works, and second, that you can modify the code for your own purposes. As you might expect, one of the best sources of precompiled tools for Mac OS X is Apple Computer. In fact, to facilitate your access to their software tools, Apple has included the Get Mac OS X Software option in the Apple drop-down menu on your desktop, which takes your browser to their comprehensive download site.
FIND UNIX APPLICATIONS FROM THE WEB
When you download a software tool from the Apple site, the Download Manager appears, allowing you to monitor the progress of your downloads. At this point, you can close your browser window. The software continues downloading, although you must remember not to shut down your network connection if you are on a dial-up line. There are several sites that provide Mac OS X precompiled binaries. For example, you can obtain a precompiled binary for Fink, a sophisticated software package manager for Mac OS X, from www.fink.sourceforge.net. Other useful tools include Mozilla from www.mozilla.org, PHP from www.entropy.ch/software/macosx/php, and XFree86 from www.apple.com/downloads. OpenOffice, an office suite that rivals Microsoft Office, may be officially released by the time you read these words.
Click Apple OS X
Get Mac OS X Software.
Command-click the
download link for the software you select.
186
12
There are literally thousands of programs that you can download and install to increase the usefulness and versatility of your Mac OS X system; some of these programs may prove to be essential add-ons to your system, while you may install others simply because they are interesting or fun. The most beneficial programs are those that either complement the tools that you already have, or do a much better job than the tools delivered with the OS. For example, Mac OS X does not include a spell checker. If you intend to do a lot of writing on your Mac system, installing ispell provides you with a versatile spell-checking system. Another tool, aspell, purports to be a more intelligent spell checker, but requires some additional configuration. Programs that need to generate character-based displays in a terminal-independent manner require a copy of libtermcap, another program that is not included in the standard Mac OS X installation. You can find libtermcap at www.gnu.org.
Click Save.
187
ou can download, install, and use open source software to great advantage. Open source software is free, and is developed and tested by some of the most dedicated people in the industry. The intention of open source licensing is to encourage collaboration and innovation while shifting the focus of control from large companies to end-users. The Open Source movement is dedicated to quality and fair practice. The basic idea behind open source is that, with the potential to have hundreds of people improving and testing code, the software development cycle is shortened and the quality of the software improves. In addition, no individual or company can leverage that development toward goals that are against the interests of the overall population of users. Now roughly twenty years old, the Open Source movement is finally achieving a presence in the commercial world. As a result, companies like Red Hat can achieve financial success
USING OPEN SOURCE SOFTWARE
even though they are selling software that is essentially free. Commercial success and open source software are not incompatible with each other. In fact, Mac OS X is itself built on an open source foundation, a core operating system known as Darwin. Although the development of Linux has been very important to the Open Source movement, open source development has also brought us tools that are critical to the Internet such as BIND, sendmail, and Apache. A sizable portion of open source software falls under the GNU public licensing (GPL) agreement that states that any software incorporating GPL-based software must itself be licensed as GPL software. Not all open source, however, falls under this licensing agreement, so you need to know how source code is licensed to know how you can use it. While open source code is available for anyone to use, the original developers may retain some intellectual property rights.
Press Return.
188
12
ou can find plenty of open source software on the Web and even participate in open source development if it interests you. The best sites for open source software are those that are dedicated only to open source. These sites include www.freshmeat.org and www.sourceforge.net. You can also find useful links and a lot of additional information about open source software by visiting www.opensource.org. You can also look for source code on the original development sites of software applications. For example, you can go to www.apache.org to download the latest or earlier versions of the Apache server. You can get sendmail from www.sendmail.com, and you can get GNU tools from www.gnu.org. If you intend to use open source software for your business or projects, the issue of open source certification can become very important to you. Open source certification,
FIND OPEN SOURCE SOFTWARE
performed by Open Source Initiative (OSI), assures you that the source code that you are using meets all the requirements that qualify it as open source. The process of compiling an application from source code can range from straightforward to extremely difficult. Fortunately, most popular tools have the development bugs removed from them a long time before you obtain a copy of the source code. These include bugs in the compilation process as well as bugs in the code. If you are wary of code with bugs, you should avoid any code that is described as Beta. Beta is a word for code that has not been fully tested. A useful tool that you can download first is Fink. Fink is an open source tool for managing software installation and can save you a tremendous amount of time in finding, downloading, and installing other software.
189
ou can install an application package on Mac OS X quite easily. This is because a package is a specially formatted application file that is designed for easy installation. To let you know that a file is prepared for easy installation on your system, the Finder uses an icon that looks like an opened parcel. To install an application package, you can simply double-click the icon for the package in the Finder. This initiates a process that walks you through each step in the installation. You are asked to enter your password to authenticate yourself as a privileged user, to accept the license agreement, and to select the disk for the installation. You can monitor the progress of the installation by watching the progress bar. When the installation is complete, a message appears informing you that the installation was successful. You install all software packages in this manner.
INSTALL APPLICATION PACKAGES
Mac OS X also includes an install command, which you can use to move binary files into a chosen location from where you want to run them. You can specifically avoid overwriting earlier versions of the software if you use a -b option with the install command. With a -o option, you can specify who owns the application when it moves into the target directory. Similarly, a -g option allows you to specify the group. You can use a -d option to create missing directories. With a -m option, you can override the default mode of the file, restricting access as needed. While downloading and installing software is relatively easy, managing it can be much more challenging. Mac OS X does not place restrictions on where you install software, so you should maintain and enforce a convention to prevent your system from becoming disorganized.
Download an application
package from the Web.
A window opens,
190
12
When you install software in many different locations on your hard drive, it can become difficult to keep track of both where you have installed your software and what software you have installed. This situation is exacerbated when you frequently download new tools and utilities. While you can manually organize your software, you have another option for making the software easier to find and use: You can update your search path to include all directories into which you install software. You can update your search path by editing your shell configuration file. If you are using the default shell in Mac OS X, tcsh, your shell configuration file is defined in the .tcshrc file in the root of your Home directory. The system reads this file every time you log on, as well as every time you open a new shell or a new Terminal window. To update your path in tcsh, edit your .tcshrc file by adding the line, setenv PATH $PATH":"/usr/local/bin:/sw/bin", where the specified paths match the locations of your new software. Each system user needs to make this change in order to find software without knowing the software locations.
Click Continue.
Click Continue.
The installation proceeds
and installs the software on your disk.
191
ou can install software from a tape archive, or TAR file, by using the tar command with a -x argument. The -x argument instructs the command to extract from a specified file. You also use the tar command to create these archives, for example, in preparing applications for distribution. Many Unix users employ the tar command to prepare archives of important personal files. You must add a -f argument, making the command tar -xf, to indicate that you are including the TAR file in the command, and a -v argument, making the command tar -xvf, if you want to list the files as you extract them. To ensure that the TAR file is intact, it is always a good idea to examine the contents of the TAR file before you extract from it. If you downloaded a TAR file without using binary mode, you may end up with a file that is corrupt. Checking the contents also tells you where the software installs when you extract it. Most TAR files install in the directory that you are in when you issue the tar command.
You can use the tar -tvf command to examine the contents of a TAR file. For example, to extract from a file called drawfigs.tar, you can type tar -tvf drawfigs.tar. If the filenames that appear start with a /, the tar command attempts to extract the file with the path shown, starting at /. Otherwise, TAR extracts the commands into your current directory. The command for extracting files from an archive named drawfigs.tar is tar -xvf drawfigs.tar. The -v argument of the tar command stands for verbose. When you use this option, the tar command displays each filename as it extracts the file.
In a Terminal window,
type tar followed by a space.
In a Terminal window,
type tar followed by a space.
192
12
You can use the tar command to extract a single file or directory from an archive instead of the entire contents. For example, you may want to first read the license agreement or README file before proceeding to extract the remaining contents from the archive. To extract a single file from a TAR file, add the name of that file to the end of the tar command. The command tar -xvf drawfigs.tar README extracts only the README file. If you are extracting a file from a directory inside the TAR file, be careful to type the directory name and filename exactly as they appear in the file listing produced by the tar -tvf command. For example, if the file you want to extract appears as tmpls/template1.tmpl, type the command tar xvf drawfigs.tar tmpls/template1.tmpl. If you want to change some part of the pathname for the extracted files while you are extracting them, you can use the -s option. For example, if want to change the tmpls directory to orig_tmpls during the extraction, you can type tar -s /tmpls/orig_tmpls/ -xvf drawfigs.tar.
In a Terminal window,
type gunzip followed by a space.
In a Terminal window,
type uncompress followed by a space.
193
ou can compile software from source code with a utility called make, a tool favored by many users of open source software. make is not itself a compiler, but a tool that manages compilation. With the Mac OS X system, make calls gcc, the GNU C compiler, to compile the source code. While the process of compiling your own applications might seem tedious at first, some developments have arisen that have made source code compiling much more efficient. For one, the process of going from source code to executable has become significantly standardized; if you can remember this sequence of steps configure, make, make install, and make clean you can build and install most software that you find. For another, you can often avoid the manual process of compiling by using a tool such as Fink. One reason why make is efficient is because it does not recompile a program when the existing program is newer
COMPILE A PROGRAM WITH MAKE
than the source code; after all, this indicates that no changes have been made to the code since it was last compiled. Large applications containing many source files recompile much faster than they first compiled because only the updated source files are recompiled. You can also run make without a Makefile to compile a program with a single source file. Source code prepared specifically for Mac OS X may already include a Makefile. Generic source code requires an additional step that evaluates the configuration of your system and creates an appropriate Makefile. The make install step uses instructions in the Makefile to install the application into the directory from which you want it to run. The make clean step removes object files, which are intermediate files in the compilation of a complex application.
Type chmod a+x greetme and press Return. Type ./greetme and press Return.
The make utility compiles your program, and your program runs.
Type }.
12
Type touch greetme.c to give your source file a newer timestamp than the compiled file. Type make greetme and
press Return.
195
COMPILE APACHE
ou can compile and install a new version of Apache from source code. New versions are available from time to time from www.apache.org. Installing a new version may give you additional features, better security, or improved performance.
You compile Apache with the standard set of steps for compiling open source software. You generally start with a gzipped TAR file freshly downloaded from apache.org. You then need to unzip that file with gunzip, and untar the resulting file with tar xvf. After your untar operation is complete, you have a directory containing all of the files needed for configuring and compiling the new version of Apache. After moving into the new Apache source directory with the cd command, you run the configure script that is included with the distribution. This step takes several minutes to
COMPILE APACHE
complete. During this stage of preparing for compilation, information about your system is being collected and analyzed and a Makefile is being prepared that guides the compilation process on your Mac OS X system. Keep in mind that the Apache distribution was built so that it would compile on many different types of systems. Therefore, this configuration step is critical to the compilation on any particular operating system. After the configuration operation is complete, you can begin the actual compilation using the make command. The make command starts by reading the Makefile that the configuration process created and using it to drive the compilation process. Unlike the use of make with a simple C source code file, this make process compiles many different programs and builds a small number of programs, in particular the httpd process that represents the Web server you have just built.
Type tar xf followed by the name of your Apache TAR file, for example httpd2.0.43.tar, and press Return. Type cd followed by the name of your new source directory, for example httpd2.0.43, and press Return.
196
12
After compiling and installing Apache, you have to start the server. Along with the files that you just installed is a script named apachectl. This script starts, restarts, and stops the Apache server. If you installed Apache in /sw/apache, through the prefix=/sw configure option, you can find apachectl in /sw/apache/bin/apachectl. To start Apache, you then type /sw/apache/bin/apachectl start. The configuration and installation process described on these pages is probably the most standard process for installing Apache. Without the prefix argument provided with the configure command, Apache compiles to run from the default directory. The remainder of the process as described uses only default values. To learn about the many different options that you can use to build a customized Apache server, use the command ./configure help.
While your new Apache server is ready to run, it uses the default DocumentRoot the directory in which your Web pages will install and serves only the set of pages that the installation process installs. Refer to Chapter 14 for information on configuring your Apache server and populating your new Web site.
Compilation begins.
197
ou can manage the installation of software on your system using a software package management utility known as Fink. Fink is a versatile tool that allows you to download, extract, configure, compile, install, update, and remove software to and from your system, often with no more input from you than a single command. Fink works with software that is configured as a package. A package is a special format that contains binary files along with source code and patches that you may need to facilitate installation and subsequent management of the installed software. Fink maintains a database that allows it to locate software packages. It downloads the packages using curl and then proceeds to install your new software while giving you progress updates on-screen. Fink is intuitive to software dependencies, and so does not install a software package if you have not installed prerequisite software. It also does not remove software if other packages on your system require it.
MANAGE SOFTWARE INSTALLATION WITH FINK
Fink is not included in Mac OS X, but you can download it from www.sourceforge.net. You can visit www.fink. sourceforge.net/download to find links and instructions on how to obtain a copy. Fink is a port of a tool called the Advanced Package Tool or APT from Debian. Fink allows you to install a package from source code or from binary files, depending on what is available. Binary package files come in a format known as dpkg and have a .deb extension. After you install Fink on your system, it is easy to use. The command fink list displays a list of available software packages. Those that are installed on your system appear with a lowercase i in the leftmost column. To install an application, you can use the fink install command followed by the name of the package you want to install.
198
12
To operate well, Fink needs to work with the most recent data possible. If you install Fink and fail to update the inventory of available software, your installation of Fink gradually becomes out of date and unable to recognize new releases of packages. To update the list and descriptions of packages that Fink uses to find and install software, use the command fink selfupdate. To update all of the packages that you have already installed, type fink update-all.
You can also use dselect to install software. This tool comes from the Debian Linux community and provides a text-based interface. The dselect tool guides you through the process of choosing the access method you want to use, updating the list of available packages, requesting the packages you want to install, configuring packages which are not yet configured, and removing unwanted software. The tool opens with the following menu.
Example:
Debian `dselect' package handling frontend. 0. 1. 2. 3. 4. 5. 6. [A]ccess [U]pdate [S]elect [I]nstall [C]onfig [R]emove [Q]uit Choose the access method to use. Update list of available packages, if possible. Request which packages you want on your system. Install and upgrade wanted packages. Configure any packages that are unconfigured. Remove unwanted software. Quit dselect.
Type | grep followed by the name of the package you just installed, and press Return.
Fink confirms that the
installation is successful.
199
ou can download software using FinkCommander, a graphical interface that works with Fink. FinkCommander provides a GUI front end to the Fink software package management tool. Using this front end, you can select the software that you want to install and initiate the installation by picking the software from a list of available packages. Fink provides a variety of information on each of the available packages. While using Fink, you can pick and choose which of the information columns you want to see by selecting or deselecting them from the View menu. Latest is the most recent available version. Installed is the version that is currently installed on your system. Binary is the most recent binary version. Stable is the most recent stable version. Unstable is the most recent unstable version. Status is the status of your installation current or outdated. Category is the software category, such as base, crypto, database, or
game. Description is a description of the tool. Maintainer is the name of the person who maintains the tool. You can also filter the list by selecting a column, such as Name, from the menu in the toolbar. When you select a column, you can then type in your selection text in the field to the right. For example, you can list the available games by selecting Category in the menu and typing games into the text field. You can sort by any column by clicking the top of that column. When you download software, you can watch the progress of your download in the bottom window of the screen. FinkCommander even allows you to provide positive or negative feedback to the maintainer of a package by selecting the green for positive or red for negative stamp icons in the menu bar.
200
12
As with Fink, FinkCommander configures, compiles, and installs your software when you select Install from the Source menu. The bottom left corner of the FinkCommander window displays a message describing each phase of the installation. The message Done appears when the installation process is complete. At this point, the Status column for the newly installed tool contains the word current, telling you that you now have the current release of that tool. While the main purpose of FinkCommander is to make installing software easier, it also provides a convenient way for you to take an inventory of the software on your system. It provides a list of each package that is installed along with their version numbers, and the current or outdated status indicator tells you whether to install a newer version of a tool.
You can also use FinkCommander to remove software. The Remove option appears under each of the Source and Binary menus. While the software installs, you can continue to peruse the list of available tools. This does not interfere with the installation process. You can select FinkCommander Help from the Help menu to better understand how to take full advantage of this utility.
Source Install I
201
INSTALL LIBRARIES
ou can install system libraries for your personal use or for use by software applications. While Mac OS X is an extremely versatile operating system, there are numerous libraries that you can download to increase the functionality of your system. Tools that you download and install often need some of these libraries. You install libraries in much the same manner as other software except that libraries are usually single binary files. When you place these files in the correct locations on your system, other software can use them by making calls to various routines. For example, if you install a library that contains routines for displaying graphics in the PNG format, you do not have to build these routines into your own code. Instead, you can use the library routines in your code and compile your software to dynamically load the libraries when you need them. System libraries are stored in /usr/lib. By convention, most third-party libraries reside in /usr/local/lib. You should be careful to install these libraries in the appropriate directories so that the applications that need them can find them. When you install libraries on your Mac OS X system, acquaint yourself with an environment variable called DYLD_LIBRARY_PATH. This variable is essential in helping your executables to locate the libraries they need. If all of your libraries are not installed in /usr/lib, you must add the list of directories in which libraries are stored to the DYLD_LIBRARY_PATH variable of every user. You must assign this variable a colon-separated list of all directories containing libraries. For tcsh users, you can insert a command, such as setenv DYLD_LIBRARY_PATH /usr/local/lib:/sw/lib , to add these two directories to the locations where the dynamic linker
searches for libraries. You can read the man page for DYLD to learn more about how the dynamic linker uses DYLD_LIBRARY_PATH as a search path for libraries. You can download many libraries by launching the FinkCommander utility, selecting Category from the menu in the toolbar, and typing libs in the text field; FinkCommander displays a list of libraries that it can install for you. When you install software through the traditional configure-make-make install process, you may have an opportunity to install libraries as well. This is because, although the basic make-install process may install binaries in /sw/bin or /usr/local/bin, it may fail to install necessary libraries. Read the README and INSTALL files to determine if there is an optional make install-lib step that takes care of this. The table on the next page provides descriptions for a variety of libraries that you can install on your Mac OS X system. While incomplete, this list contains many of the most useful libraries that you are likely to find. Like other applications, libraries undergo changes as developers build and test new versions. Just as there are many locations from which you can download open source software, there are many places where you can find useful libraries. You can find references to any library you need by using a search engine such as Google.
202
12
USEFUL LIBRARIES
The list below contains libraries that you may want to install on your Mac OS X system. These libraries are especially useful if you plan to develop software. LIBRARY
db3 db4 dlcompat dtdparser expat fnlib freetype freetype2 gc gd gdbm giflib glib gmp gnomelibs gnujaxp gtk imlib libdnet libdv libfame
DESCRIPTION
Berkeley DB embedded database Berkeley DB embedded database Dynamic loading compatibility library Java DTD Parser C library for parsing XML Font rendering library for X11 TrueType font rendering library, version 1 TrueType font rendering library, version 2 General-purpose garbage collection library Graphics generation library GNU dbm GIF image format handling library, LZW-enabled version Low-level library that supports GTK+ and GNOME GNU multiple precision arithmetic library GNOME libraries Basic XML processing in Java GTK+, the GIMP widget toolkit used by GNOME General image-handling library Networking library Software decoder for DV format video Fast Assembly MPEG Encoding library
LIBRARY
libghttp libiconv libiodbc libjpeg libmpeg libpoll libtiff libungif libunicode libwww libxml libxml++ libxml2 libxpg4 netpbm pcre pdflib pil readline libghttp
DESCRIPTION
HTTP client library Character set conversion library ODBC libraries JPEG image format handling library GIMP MPEG library System V poll(2) Emulation Library TIFF image format library GIF image format handling library, LZW-free version Low-level Unicode processing library General-purpose Web API written in C for Unix and Windows XML parsing library C++ interface to the libxml2 XML parsing library XML parsing library, version 2 Locale-enabling preload library Graphics manipulation programs and libraries Perl Compatible Regular Expressions library A library for generating PDFs The Python Imaging Library; adds image-processing capabilities to Python Terminal input library HTTP client library
203
ou can install the Lynx Web browser on your Mac OS X system. Lynx is a text-based Web browser that is useful for troubleshooting Web connections and accessing files and information from the Web, especially when you are limited to a text-only environment, such as a telnet or ssh connection. Lynx does not install with the Mac OS X distribution, but you can download it using Fink or FinkCommander. While Lynx does not fill your screen with dancing frogs and pop-up ads, the simplicity of this tool gives you a definite advantage because it is fast. While Lynx recognizes graphics and links, it displays only the text equivalents. For example, in place of a link, you see [Link Name] or [Image Name], as in [company_logo.gif].
You can use Lynx to browse the Web as you would Internet Explorer and Netscape Navigator. To start Lynx, you can type lynx followed by the URL that you want to visit. You can click links, even though they appear as text, to move around within the site. You can use the arrow keys on your keyboard, the spacebar, or a number of single-letter commands. The third line from the bottom of the Lynx screen gives you suggestions as to what you may want to do next. For example, you may see a message such as press space for next page. To move forward in the document, you can press the spacebar, and to move backward you can type the letter b. As a text-only browser, Lynx seems strange at first, but you may find it a handy, and sometimes indispensable, tool. The name Lynx is a homonym for links.
13
You can set numerous options to define how Lynx works for you. The best way to learn about these options is to consult the Lynx User Guide. To do this, type lynx localhost to start Lynx. Your local home page displays. Then type h and press Return. This command activates the Lynx online help, and positions your active link on the Lynx User Guide. When you press Return, the User Guide displays. You can use your arrow keys to move around within the User Guide. When you are done, you can use the Left Arrow key to move to your home page, or type the letter q to quit Lynx altogether.
You can use Lynx to perform basic troubleshooting of Web sites. If you have trouble connecting to a Web site using a traditional browser, you can use Lynx to quickly determine whether the site is working. Because Lynx omits graphics and takes very few resources to run, you can test and display your sites in very little time. If you are responsible for a Web site, you can use Lynx to check whether your site is up and working.
205
ou can browse the Web with Lynx. At first, Lynx may appear to be a browser of limited capability, but as you become familiar with Lynx, you find how useful it is to quickly retrieve information from the Web; in less time than it normally takes you to start Internet Explorer, Lynx has your entire Web site on your screen. You can follow links, search for text, and download pages in a similar manner to using a normal browser. The difference is that, instead of clicking links that hide under images or display as underlined text, you move around with simple keystrokes. The currently active link appears highlighted. For example, the colors reverse so you see white letters on a black background if the rest of your screen is black on white.
With Lynx you can use single-letter commands to navigate the Web. For occasional browsing, you only need a few basic navigational commands, but if you want to learn the more advanced browsing capabilities of Lynx, you can use the Lynx help facility to learn what each of these one-letter commands means. To access the information on these commands, you can type lynx -help | less on the command line. You can also get help on using Lynx by typing the letter h after you have started Lynx. You can then open the Lynx User's Guide by pressing Enter or you can press your down-arrow key and then press Enter, to bring up a listing of the keystroke commands. If you find yourself stuck at any point or change your mind while waiting for a sluggish site to respond, you can type z to stop the current request. This command acts just like clicking the Stop button in Internet Explorer.
Press Return.
13
DESCRIPTION
Display a list of commands Add the current link to bookmarks Download the current link Go to a specified URL Show an index of documents Show a list of single key commands and what they do Return to main screen Set your options Print Quit Search for a string in the current document Go to the next search string
INSTALL WGET
ou can install Wget, an automatic Web-site retriever. Wget is a handy tool for downloading a Web site in order to back it up for safekeeping, or to move it to another host. The best feature of Wget is that you do not have to download your Web pages one at a time; the recursive nature of the tool allows you to download an entire site with a single command. You can download Wget using Fink. When you type the command fink list | grep wget, Fink tells you that the package is available and that it is not yet installed on your system. The current release of Wget is 1.8.2-1. To start the download using Fink, you can type the command fink install wget. Fink then runs the curl command to download the Wget installation file. Fink manages the uncompression, extraction, and installation of the Wget files onto your system.
Because Fink installs software into the /sw directory, Wget installs as /sw/bin/wget. After you complete the installation, you can type which wget and have this pathname returned to you. If not, you must update your search path to include /sw/bin by editing the .tcshrc file in your Home directory. Fink installs man pages in /sw/share/man. If you type man wget and get the response no manual entry for wget, you can add this directory to your MANPATH by adding setenv MANPATH /sw/share/man to your .tcshrc file. To make the changes to your search path and your MANPATH permanent, you should update these paths as they are defined in your .tcshrc file. Keeping these paths up to date with the applications you have installed will save you a lot of trouble in the end.
INSTALL WGET
208
13
ou can download an individual Web page or an entire Web site with Wget. Wget is an extremely fast command-line tool that retrieves files from Web sites using HTTP and FTP. You can download an entire site by typing a single line of text. Wget works well even on slow and troublesome connections, and if you are using a slow dial-up line, you can start the download and let it run. In all likelihood, it will run to completion with no monitoring or other attention. Wget can run in the background, making it an ideal tool to back up a Web site. To start a download, all you have to do is type wget followed by a URL. For example, the command wget http://www.dragonflyditch.com downloads the Dragonfly Ditch Web page; you will see this default document in your browser if you type the same URL.
DOWNLOAD WEB SITES WITH WGET
If you use the recursive option, you can download all of the Web pages and image files from the site. It is a good idea to download sites only if you know how many files you are downloading and how large they are. Downloads from a very large site could consume all of your free disk space. Wget creates a subdirectory by the same name as the URL from which you are downloading, so that if you download from multiple sites, Wget drops the files from each site into separate directories to avoid confusion. The Wget tool includes many options, such as setting a username and password for access, limiting the depth of your retrieval, and determining whether Wget overwrites downloaded files. You can read the Wget man page to learn more about this tool.
DOWNLOAD A PAGE
Type -r followed by a
space.
209
ou can install an Internet Relay Chat (IRC) client on Mac OS X. IRC, or chat, clients allow you to participate in interactive dialog with other people on the Internet. Unlike e-mail dialog in which days may elapse between when you send a message and when the recipient reads the message, chat dialog is immediate. You chat with people who are active chat clients themselves. Chat tools, such as AOL Instant Messenger (AIM), are based on the IRC protocol. IRC relays your message between chat servers. If you do not have iChat on your Mac OS X system or if you want to upgrade your chat client, you can use the Get Mac OS X Software option on your Apple menu to access the download site for Apple binaries. From there, you can scroll down and find the AOL Instant Messenger
application. By right-clicking the download link, you can select the Download Link to Disk option and then click Save to download the BIN file. When you double-click this file, it installs the AOL Instant Messenger software. Whatever chat client you decide to install, you probably want to keep it in the Dock so that you can start it up by clicking the icon. Before you can use any chat client, however, you need to register a screen name. If you are a .Mac subscriber, you can use your .Mac screen name. If you are already an AOL Instant Messenger user, you can use that screen name. Otherwise, you need to register a new screen name so that you can chat and so that other people can find you.
The Mac OS X
210
13
Other IRC clients are available for Mac OS X and offer various features that you may prefer to those of AIM. The site www.irchelp.org is a good place to get information on other chat clients; in particular, the www.irchelp.org/irchelp/mac/ page provides information on other chat clients and links to the sites where you can find these tools. Ircle from www.ircle.com is one of the most popular chat clients for the Mac OS community. You can download the Carbon version of this tool for your Mac OS X system.
You can also download an IRC client using Fink or FinkCommander. To determine what clients are available through FinkCommander, type chat into the text field and select Name and then Description. This should provide you with information on chat tools, such as xchat, that you can download or install with FinkCommander.
211
CHATTING ON IRC
ou can chat with a person when you know their screen name. A screen name enables you to find someone on IRC and determine whether the person is online. When you know the screen name of another user, you can add the user to your buddy list, thereby making it easier for you to open a chat session with the friend. When you first open iChat, your buddy list appears and you can determine which of your buddies are available to chat. You can add buddies to this list by using the Add a Buddy option from your Buddies menu. When you select this option, a form appears that you fill out with information on the new buddy. This information includes the full name and screen name of the buddy. You can also use this form to keep track of the e-mail address of your buddy. After you select a buddy, you can invite that buddy to chat with you by right-clicking the buddy from your buddy list and clicking Invite to Chat.
Because you may not always be in the mood to chat, you can alter your status to control whether others can initiate a chat session with you. When you start iChat, you are listed as Available. You can change this status to Away, or you can even create a custom status to tell your buddies when you are too busy to chat. When you engage a buddy in chat, you can exchange dialog in a chat window. For example, if you start a chat with someone from your buddy list or select New Chat with Person from the File menu, a dialog window then opens in which your dialog with the other person appears with proper annotation so that you can easily see what each of you is typing.
CHATTING ON IRC
Buddies Add A Buddy... A
212
13
If you like working on the Unix command line, you can download and install a command line IRC tool called ircII from www.irchelp.org/ irchelp/ircii. You download a TARGZ file from this site, which you can compile and install. After installation, when you type ircii, your Terminal window splits into two sections. You then use commands such as /server and /join to connect to a chat server and join in a discussion. You can use the /help command to learn some basic commands, and the /quit command to exit the program.
While IRC clients such as iChat provide the means for you to chat with people around the globe, there are other tools that you can use in UNIX to communicate with other users. One of these tools is called talk. Talk allows you to enter a chat-like session with other users on the same system. You can read the man page for more information.
Click Add.
Right-click to select a
buddy from your list.
213
CONFIGURE SENDMAIL
ou can configure sendmail on your Mac OS X system. Sendmail is a mail server; it can listen for e-mail requests from other systems. Sendmail configuration is one of the most difficult tasks in Unix administration. The software itself is complicated and its initial deployment on Mac OS X brings along some additional problems that must be resolved. However, with a little care and some insight, you may get off easily and end up with a mail server that behaves properly. Some of the difficulties related to sendmail on Mac OS X are due to a conflict between the way that Mac OS X and sendmail deal with directory permissions. Where sendmail wants to be sure that directories it uses can only be modified by root, Mac OS X is far more lenient about directory permissions in order to support privileged users who want to do things like dragging files into root-owned directories. If you try to start sendmail using the default configuration, sendmail will balk at world writable directories and not start.
CONFIGURE SENDMAIL
The easiest way to resolve the conflict between sendmail's cautious character and the lenient directory permissions of Mac OS X is to modify the DontBlameSendmail setting in sendmail's configuration file. This name refers to the fact that the developers of sendmail do not want you blaming the software if you reduce its level of security. Modifying the setting will, however, allow sendmail to start and will not reduce your system security. Sendmail's configuration file is stored in /etc/mail and is called sendmail.cf. You should always use care in editing this file as the lines in this file are difficult to understand and easy to mistype. However, it is not especially difficult to generate a new sendmail configuration file and the tools you need to do so are already on your system.
EDIT SENDMAIL.CF
Press Return.
Type sudo vi
/etc/mail/sendmail.cf.
214
13
To ensure that sendmail does not read its configuration file from NetInfo, you may need to type the following commands found in the /etc/mail/README file:
niutil -create . /locations/sendmail niutil -createprop . /locations/sendmail sendmail.cf /etc/mail/sendmail.cf
These commands tell sendmail, whenever it tries to look at NetInfo, to look instead at /etc/mail/ sendmail.cf. If you encounter errors that indicate you cannot write temp files, you must open permissions on the /var/spool/mqueue and /var/spool/ clientmqueue directories. You can do this with the command chmod 777 /var/spool/*mqueue. These directories are used to temporarily store the details and content of e-mail messages before the messages are delivered.
If you have trouble starting or running sendmail, you can check your /var/log/system.log file for messages that may pertain to the problem. If you see an error message that the file /etc/mail/access.db does not exist, you can create this file from /etc/aliases with the command makemap hash /etc/mail/ access.db < /etc/aliases. The /etc/aliases file contains lines such as test: user where test is an alias and user is a real username.
Type :s/#O DontBlame Sendmail=safe/O DontBlame Sendmail=GroupWritableDir PathSafe/ and press Return.
215
You then want to edit this file. The lines of interest are all lumped together at the bottom. After the first line starting with the word define, you should add a line that reads define('confDONT_BLAME_SENDMAIL','GroupWrit ableDirPathSafe'). Then, save file. The next thing you need to do is run m4 to use the specifications that you just edited into a new configuration file. That command would look like this: m4 ../m4/cf.m4 yourdomain.mc > /tmp/sendmail.cf. That leaves your new configuration file in /tmp. You then back up your current configuration file and install your new configuration file in its place. You then start sendmail. To ensure that sendmail starts up every time your system is booted, you need to modify /etc/hostconfig. This file plays a critical role in starting services. You will change MAILSERVER=-NO- to MAILSERVER=-YES-.
13
ou can create and send messages from the command line in Mac OS X, as you can with most UNIX systems. You do not need to open up a mail client. The easiest and fastest way to do this is by using the echo command to create a message and then piping the message to the mail command. For example, you can type the following message on the command line to create a message with the subject line lunch and add it to the inbox of user shs. echo Please do not forget we have a lunch date today | mail -s "lunch" shs If you want to send a longer message, you can run the mail command for example, mail shs and then type your subject line and message. When you are finished typing your message, you enter a period (.) on a line by itself, and the system sends the message.
SEND E-MAIL FROM UNIX
Your recipient can read your message in a variety of ways. If they are a command line user like you, they may opt to use the mail command by typing mail on a line by itself. A list of messages appears, and they can read them one at a time or delete them without reading them. If they want to respond, they can do that, too. The mail command includes the arguments r for reply and d for delete. To read a message, the user simply presses Return or, in the case of multiple e-mails, selects the message number and presses Return. If your system is set up with a mail client, such as pine or elm, you may prefer to open your mailbox using one of these tools.
SEND A MESSAGE
218
13
While the mail command is useful, most UNIX users today prefer to use more versatile tools for sending and receiving e-mail. The simple mail command, after all, cannot properly display e-mail that arrives in HTML format or allow you to fetch and use attachments. The mail command was created before HTML and attachments were used in e-mails. Even so, the mail command continues to provide a service. For example, simple e-mail messages sent from the command line can help you to determine whether a mail server is working. Mail files, typically thought of as inboxes, are stored in /var/mail. Each user on the system with pending mail will have a single file in this directory. The inbox for user would be /var/mail/user.
The mail command is also very helpful for use within scripts. For example, if you write a script to routinely check disk space, you may want the script to send the results of the disk check to you via e-mail. You can use a line of code such as df k | mail s "disk usage" user@mydomain.org in a script that runs once a day through cron to remind yourself to look at your disk space.
READ A MESSAGE
219
ou can examine your Unix inbox without using commands, such as mail or mail clients like Mac OS X's Mail, by locating and displaying your mail file in your file system. Any time your mail setup does not appear to be working properly, knowing where and how to examine this file will help you determine whether mail is arriving as it should. To view your e-mail inbox, you should move into the /var/mail directory. This folder will contain a mail file for each user on your system who has mail in his or her inbox. Even if you have 300 individual messages, your inbox will consist of a single file. Each message in this file will begin with a From line that includes the sender and the time and date that the message arrived. For example, the line From gumby@example.org Mon Feb 17 15:30:02 2003
will indicate the start of the message you received from Gumby on that date. Each message in your inbox will begin with a line that has this form. No other lines in your inbox will begin with the word From followed by a space. These lines allow mail clients to determine where each message starts. The message header lines that begin with tags such as Date:, From:, To:, and Subject: come next and are followed by the text of the message that was sent to you. The end of each message is only indicated by the beginning of another message or the end of the file. If you send a message to yourself on the command line, using a command such as echo testing | mail user, you should see the size of your inbox increase, the timestamp on the file to change, and the content of this message added to the bottom of your mail file.
220
13
ou can fetch e-mail from remote servers using the fetchmail tool. Fetchmail is a retrieval and forwarding tool that supports all of the important protocols for retrieving mail from an e-mail server. These include the most popular protocols POP3 and IMAP as well as a number of others: POP2, RPOP, APOP, KPOP, ETRN, and ODMR. Like many tools, fetchmail uses a configuration file, .fetchmailrc, to store information about your accounts. You can add lines like the following to your .fetchmailrc file: poll mail.mailserver.org protocol POP3 user nici password worx4me is noh In this example, nici is the username for the remote account, while noh is the local user. The server you check for downloadable e-mail is called mail.mailserver.org. As you can see, the password appears in clear text. For this reason, you must set permissions on the .fetchmailrc file so
that only the individual user can read this file. In fact, fetchmail warns you if the permissions on the file are not set to 710. This means that the owner has read, write, and execute permission, while the group has only execute permission, and no one else can access the file. Storing the password in the file saves you from having to enter it each time you use fetchmail. This also allows fetchmail to automatically run through cron for daily or more frequent downloads. Your system must be running sendmail for fetchmail to work properly. Fetchmail works by transferring the mail to the smtp port on your local system. If you are not using sendmail, you can change your .fetchmailrc file to use procmail instead by making it look like this: poll mail.mailserver.org protocol POP3 user nici password worx4me mda "/usr/bin/procmail -d noh"
221
INSTALL PINE
ine is a text-based e-mail program that has been in use on UNIX systems for many years. You can install pine on your Mac OS X system using Fink or FinkCommander. Otherwise, you can download pine from www.Washington.edu/pine/getpine. You can then uncompress and untar the installation file as is described in Chapter 12.
The first time you run pine, it creates a configuration file in your Home directory called .pinerc. This file allows you to modify a number of configuration parameters, such as how your name appears in messages that you send. Like most UNIX configuration files, the .pinerc file contains numerous comments; any line starting with a # symbol is a comment. To make pine easy to use, you should ensure that it is on your search path. This allows you to start pine by typing pine on the command line. You can verify that pine is on your search path by typing which pine. This command returns the full path to the pine executable. Some of the other tools that are compiled along with pine are useful if your system is to act as a mail server. The imapd, ipop2d, and ipop3d tools are servers that allow mail clients to download e-mail. These tools support the IMAP, POP2, and POP3 protocols, respectively.
To create the pine application, you can type build osx. This command takes the place of the normal make command and builds a pine binary for your Mac OS X system. When the build process is finished, you have a directory containing the pine binary along with a series of other programs that you can copy to other locations on your system. You can refer to the README file for directions that may pertain to your installation.
INSTALL PINE
222
13
You can start pine with a new .pinerc file two ways. You can remove your current file by typing rm .pinerc in your home directory. When you start pine the next time, it will greet you as if you had never used the program, setting up a brand new .pinerc file for you in the process. Alternately, you can type the command pine conf > .pinerc in your home directory. This pipes the output of the pine conf command, which generates the settings in a default .pinerc file to the file you specify.
Pine, by default, stores diagnostic information in files called .pine-debug1, .pine-debug2 and so on. These files might prove to be of some interest to you, but they are of no value. The easiest way to turn off this feature is to add the line alias pine "pine d 0". to your .tcshrc file that sets the debug level or pine to 0. The next time you log on or type source .tcshrc, the .pine-debug files will no longer be created. Remember that you have to type ls a to list files that begin with a period.
Type cd and the name of your new directory, and press Return.
223
ou can read your e-mail with pine. Using pine is not difficult after you get used to the pine commands and how pine organizes your e-mail. To start pine, you can type pine on the command line. When in pine, you can access your inbox, read and delete messages, and compose and send e-mail. The first screen of data that you see when you start pine is an upper-level menu that allows you to ask for help, compose a message, view a message in your current folder, list your folders, update your address book, or quit pine. You can access each of these options by typing a single command, such as C to compose a message. This screen is called the main menu. The default choice in the main menu is to list your folders; if you simply press Return, pine lists your folders.
You can then open your inbox or another folder. The upand down-arrow keys move you between messages. You can display a message by pressing Return. To return to the message index, you can type the letter i. You can mark a message for deletion by typing the letter d when that message is highlighted. This means that pine deletes the message when you quit the program. If you change your mind, you can un-delete the message by moving back to it and typing the letter u. While these one-letter commands may seem cryptic at first, pine provides a list of the most common commands at the bottom of the screen. You can return to the main menu by pressing the < key one or more times. You can get help at the main menu by pressing the ? key. To quit pine, you can type q.
224
13
To reply to a message using pine, you can type r when you select the message in the message list or when you view the message. Pine addresses your reply to the sender of the original message and asks you whether you want to include the original message in your reply. You can change your pine options by editing your .pinerc file or by selecting SETUP from the main menu. If you elect to use SETUP, another list appears. Selecting C brings you to a long list of configuration options over several screens. Although these options are numerous, if you are like most pine users, you will stay with the default settings. To move a message to a different folder, you can type s when pine displays the message list or the message itself. Pine then asks you to type in the name of the folder where you want to place the message. It defaults to the saved-messages folder.
225
ou can compose and send e-mail with pine. To compose a message in pine, you can type c while in the main menu. This moves you into a simple texteditor in which pine pre-inserts message parts such as the To and Subject tags. You can move around in this form by using arrow keys, inserting your recipient and your message text. As you type your message, the form area dedicated to the message text grows larger to accommodate your message. To insert a text file into your message, you can press Ctrl + R. Pine then asks you to enter the name of the file that you want to insert into your message. You must supply the name of the text file, including the pathname if it is not located in your Home directory.
Pine allows you to add carbon copy (cc) recipients to your messages and to include attachments. To add an attachment, you can type the name of the file, along with the pathname if it is in a subdirectory, in the Attchmnt line. Pine attaches the file to the message when you send it. You can add additional attachments by pressing Ctrl + J. To change the format of your message to a rich header, you can press Control + R. This adds some additional fields to your message header, such as Bcc and Newsgrps. If you have defined a signature, the contents of your signature file appear at the bottom of your message text. When you are ready to send your message, you can press Control + X. Pine asks if you want to send your message. If you type s, pine sends the message. The Control + X command and other options appear along the bottom of your screen.
Press C.
226
13
Messages that you move to other folders are stored in files in your mail directory. For example, if your username is sbob and your home directory is /Users/sbob, your mail folders are stored in /Users/sbob/mail. Each file within this directory represents one of your mail folders, and pine stores it as a standard UNIX mail file. Messages begin with the string From, followed by the e-mail address of the sender, and a date/time stamp. If you copy a mail file to your mail directory or remove one, pine accomodates and lists the new set of folders. This shows that Pine does not maintain any internal representation of your mail folders. It simply looks at the files in your mail directory and displays them to you as a series of individual messages.
To add a signature to the messages you send with pine, you can create a .signature file in your Home directory. Pine reads the contents of this file and appends your signature to the bottom of every message that you compose. You can create a signature file using any text editor or on the command line.
Example:
echo "-" > .signature echo "Fred T. User, Minstrel" >> .signature
Press Control + X to
send your message.
227
INTRODUCTION TO APACHE
pache is the most popular Web server on the Internet today. Accounting for roughly 60 percent of Web servers and probably 80 percent of the available Web-server books, Apache is one of the open source products that has become a part of the foundation of the Internet. It is well used, well understood, and well implemented.
The purpose of the Apache Web server is to listen for requests from Web browsers and serve up the pages requested. Like any important Internet service, Apache runs on a dedicated port. This port is dedicated not to Apache, but to the HTTP protocol that Apache and browsers use to communicate with each other. After you install and run a Web service, curious visitors can type your URL into their Web browsers and peruse what your site has to offer. Whenever a visitor types an address such as www.dragonflyditch.com into a Web browser, the address is first passed on to a DNS server for translation into an IP address. Then, a request is made to port 80 on the remote system. This request is essentially GET / a request for the home page or default document on your site.
When a Web server receives such a request, it looks at certain configuration variables to determine which page it should send back to the client. For Apache servers, that page is usually called index.html, though with the prevalence of Java and other tools on the Web, it may just as likely be mainpage.jsp. If the home page is a static HTML file, the server transfers it to the client immediately. Many other types of pages are created only after the request arrives on the server, with information read from cookies on the computer of the client or from a database on the server. This information allows customized pages to be created for each user. In any case, when the page is ready, it is sent to the client. This all happens in a matter of seconds even when the server is halfway around the world.
Apache is popular largely because it is free to any user, although this is not the only reason. Apache is also extensible through a collection of modules and can be customized for an intended use. You can add or remove modules at build time, so the resulting binary contains only the features that you need. Apache also supports
all of the features that anyone might expect in a Web server. Configuring Apache for name-based virtual servers, where multiple sites all run on the same machine while appearing to be independent, is easy in Apache. Configuring security and tuning the server for expected traffic are also simple processes.
228
14
Web servers depend on the Domain Name System (DNS) to function, just like other Internet services. When you type a URL such as http://www. dragonflyditch.com, you are simultaneously specifying a number of things. By typing http, you are designating that HTTP is the protocol the limited language that describes communications between client and server used to communicate with the server. This is the primary protocol used by the Web, but not the only
one. By typing www.dragonflyditch.com, you are identifying a particular server and relying on the services of DNS to translate this textual name into an IP address so that the DNS can use the IP of the address to locate and communicate with that server. By typing nothing more, you are indicating that you want to communicate with the server running on the default port for Web servers, port 80, and you are saying that you want the home page or default document for the site.
APACHE CONFIGURATION
The configuration on the server end determines which directory on the server contains the documents and files available for viewing. For Apache, this directory is called the document root. On a properly configured Web server, visitors cannot view or download files outside of this directory. The configuration on the server end also determines which file the server transfers to you when you type www.dragonflyditch.com in the URL field. Whenever
you enter a URL that does not contain a filename, Apache looks through a list of default documents for one that matches a document in the requested directory. If the default documents list contains index.html and login.jsp, and the document root contains neither of these files, Apache returns to you one of two things: an error code or a directory listing. The choice depends on whether directory browsing is enabled.
While a GET / request may at first appear to be a very modest service request, retrieval of the home page for most Web sites results in a number of requests as each frame and each image contained in the file is subsequently requested. Until your browser obtains all the parts of a page from the server, the Web page is incomplete. While the earliest Web servers delivered static Web pages to their clients, Web servers today often produce custom pages. For example, they may offer forms for you to fill out whose contents are posted, or sent to the server for additional processing, or they may call on encryption services to hide sensitive data from prying eyes as the data transfers to the server for processing.
While the protocol that the Web uses to move files and data back and forth is itself fairly simple, with only a handful of commands such as GET and POST, the communications between client and server often include a lot of additional information. Much of this is contained in the headers that you send with your simple requests. Through the use of these headers, clients and servers can compare notes on what each of them is capable of doing. For example, a Web server does not send you a file in a format that your browser cannot display. When multiple sites are supported on a system, and differentiated only by their names such as the difference between dragonflyditch.com and idyllmtn.com the server knows which site you are requesting because the site name is included in the headers.
229
START APACHE
ou can start your Apache server after you install the software. The Apache installation includes a script that facilitates starting and shutting down the service. When Apache is not running, you can start it by typing apachectl start. The Apache bin directory must be on your search path for this command to work without a pathname. You will probably find Apache installed in /sw/apache, or usr/local/apache, and the script is bin/apachectl, but you can determine if it is on your search path by typing which apachectl. If you are using the Apache server that ships with Mac OS X, look in /usr/sbin. When Apache starts, you can examine the processes running on your system; you can expect to see several processes named httpd. In a normal configuration, one of these processes is started by root, while another five to eight are started by a user called nobody. Nobody is a special user with no particular privileges on a Unix system. By running Apache processes as nobody, you ensure that a hacker
START APACHE
cannot commandeer these processes, and that these processes do not offer up files that only a privileged user should access. By starting up multiple servers, Apache can handle considerable traffic. While all connection requests from clients arrive at the same port, Apache turns over each request to one of the idle httpd processes. When all of the processes are occupied, Apache can start others. The ratio of busy to idle processes depends on specifications in the Apache configuration file. The number of processes grows and shrinks in such a way that the server is always prepared for additional traffic, but not so over-prepared that the overhead is excessive. When you install Apache, it is generally configured to start automatically when the server boots. However, if you change the Apache configuration file and want the changes to take effect immediately, you must restart the server with the apachectl restart command.
Type ps -ax followed by a space. Type | grep http and press Return.
230
14
STOP APACHE
ou can stop your Apache server at any time. To stop Apache, you can use the apachectl script with a stop argument. This stops all of the Apache processes. Both the stop and start commands are arguments to the script that you supply to Apache to control the operation. This script can also respond to restart and status arguments. The restart command shuts down and restarts Apache, while the status command tells you whether or not Apache is running. When you stop Apache, you terminate the server process. The server is no longer listening on the port assigned to HTTP, and clients who continue requesting service receive a message indicating that their browser has encountered a DNS error, or that it cannot find the server. This indicates that the client is not finding a responsive process on the HTTP port.
Before you attempt to stop Apache, you may first want to confirm that it is running. You can do this in one of two ways. You can use the apachectl script with a status argument; however, this technique only works if you also have lynx installed. You can also run the command ps aux | grep httpd to view the processes that are running. If you run this command, you must be careful not to mistake your grep command for an Apache process. You can also determine whether the HTTP port is listening for client requests. If Apache is not running, no processes should be listening for connections on port 80. You can perform this test with the netstat command. The command netstat -a | grep http returns a LISTEN message when Apache is running. The output looks like this: tcp46 0 0 *.http *.* LISTEN
STOP APACHE
Type a followed by a
space.
231
CONFIGURE APACHE
ou can configure Apache to run according to your specifications. Configuration parameters for Apache reside in a single configuration file, and you can make configuration changes by editing this file. This configuration file is called httpd.conf, and it contains a great deal of explanatory text and examples to simplify the process of configuring your server. In fact, if you want to set up a Web site very quickly, you can simply install your custom Web pages in the default document directory and start Apache with the apachectl start command.
The default location for Web pages is the htdocs directory in your Apache directory for example, /sw/apache/ htdocs. When you install Apache, the installer puts a small set of files into this directory to act as a placeholder for your intended content. If you start Apache and visit your Web site without doing anything else, you see these documents. The logs directory stores log files that contain records reflecting each page that transfers from your site, including information on the client such as when they visit and from what system. The configuration directory, containing your all-important httpd.conf file, is called conf for example, /sw/apache/conf.
APACHE DIRECTIVES
Configuration commands in Apache are called directives. The basic form of a directive is the name of the directive followed by the value that Apache assigns, such as User nobody. Each directive controls some aspect of how your Web server runs. While there are several hundred possible directives, you are not likely to make many changes in your default configuration file. If you are curious, you can access a complete list of Apache directives by visiting www.apache.org. The set of available directives depends, in part, on the version of Apache that you are running. The most critical directives are DocumentRoot and DocumentIndex. The DocumentRoot directive tells your Apache server where to go to retrieve pages when requests arrive from clients. The DocumentIndex directive is a list of files that tells your server what files to look for when a client does not include a filename in
their request. If you do not set these two variables correctly, your Web server does not work as you intend. The ServerRoot is the directory in which the configuration and log file directories reside. If your Apache ServerRoot is /sw/apache, your configuration files reside in /sw/apache/conf, and your log files in /sw/apache/logs. In fact, your Apache binary is likely to reside there as well, in /sw/apache/bin. Although there are many other critical directives, most, if not all of these, default to very reasonable and secure settings. There are two forms of Apache directives: simple directives and block directives. Simple directives set a value for a specific setting, such as the port the server runs on. Block directives group other directives into a set, such as the settings you want to apply to a virtual Web server.
Mac OS X ships with a built-in Apache server that you can configure and run without having to download and compile it from source code files. To start the server, you can click System Preferences Sharing. When the Sharing panel appears, you can select Personal Web Sharing, and then click Start. If you open a Web browser and type http://127.0.0.1 in the URL field, a test page appears. The built-in Apache server is identified on your system as /usr/sbin/httpd. If you type /usr/sbin/httpd V, a list appears which contains information about the settings
that Apache uses, including the location of your default configuration file. The location of this file appears in a line that reads D SERVER_CONFIG_FILE=/etc/httpd/ httpd.conf. You can use the command grep ^LoadModule /etc/httpd/httpd.conf to list any modules that are enabled. For example, cgi_module appears in the output of the grep command, indicating that CGIs are enabled. It is a good practice to store CGIs that you develop in the /Library/WebServer/CGI-Executables directory.
232
14
To enable PHP, you can remove the initial # symbol from the following lines in your httpd.conf file: # LoadModule php4_module; # AddModule mod_php4.c; # AddType application/xhttpd-php .php; and # AddType application/ x-httpd-php-source .phps. You must then stop and restart Apache. After restarting, you can create the PHP test file and save it as /Library/WebServer/test.php. To confirm that PHP is working, you can type http:// 127.0.01/test.php into the URL field of your browser; if PHP is working, a table appears containing information about PHP.
PHP Test File <html> <body> <? phpinfo()?> </body> </html> The built-in Apache server also initializes personal Web sites for your users. For example, the personal Web site for the user Smith, is defined in the file /Users/smith/ Sites/index.html. You can find the access and error logs for the built-in Apache server in the /var/log/httpd file.
APACHE DIRECTIVES
The directives in the table below are some of the most critical in setting up your Web site in the way that you
want it to work. Most, if not all, of these reside in your httpd.conf file, though some appear in comment lines.
OPTION Options <Directory name> and </Directory> DirectoryIndex DocumentRoot ErrorLog HostnameLookups KeepAlive Listen LogFormat LogLevel MaxClients ScriptAlias ServerAdmin ServerRoot StartServers StartThreads Timeout User nobody UserDir <VirtualHost pattern> ... </VirtualHost>
DESCRIPTION
Specifies options, such as whether directory browsing is enabled Block directive for handling a specific directory Lists default documents, like index.html Specifies directory where Web pages reside Specifies log directory relative to ServerRoot Specifies whether reverse lookups should be performed Determines whether sessions endure beyond the first request Specifies port that server listens on, usually port 80 Defines content for the access log file Determines what level errors should be logged Sets a limit on the number of simultaneous connections Connects a virtual name such as /cgi-bin/ with an actually directory Provides e-mail address of Web site admin Identifies directory containing your Web pages Determines how many server processes run when the server starts Determines how many threads a single process may support Limits time that an inactive session is maintained Specifies userid under which Web processes run Identifies directory name that is used for personal Web sites Block directive for virtual hosts
233
ou can build a simple site using a single directory, or organize your Web pages using a series of directories. The document directory or document root that you set up for your Apache server holds all the files that are part of your site. These files can all reside in the directory that you assign to the DocumentRoot directive, or you can, instead, divide your files into a series of directories to make them easier to organize. For example, if you use a lot of image files, you may want to keep these in a separate images directory apart from your HTML files. Most people find that it is distracting to have hundreds of files in a single directory. The single point of entry for most visitors to your site is the page that you set up as your default document, assigned to the DirectoryIndex directive in your configuration file. Called index.html by default, this is the document that your Web server sends to visitors whenever they type your URL into their browsers.
SET UP YOUR DOCUMENT DIRECTORY
If your default document contains references to other files, such as image files, the links in your document must correspond to the directory structure that you create. For example, if you refer to an image called mylogo.gif that resides in the images directory within your document directory, you must refer to this file as images/mylogo.gif. Your default document, index.html, not only has relevance to your document root, but it also plays a role in every directory that you create. Any time a visitor types in a URL ending in a directory name, your Web server attempts to send back a default document from that directory. If it does not find one, it returns a directory listing or an error, depending on whether you have disabled directory browsing.
234
14
ou can create a simple Web site in less than an hour. After you install Apache on your system, you can create a Web site by using a text editor to enter text and a few formatting commands, and by copying image files as you need them. Static Web pages contain special formatting commands in a language called HTML, along with the text or content of your pages. For example, if you create a Web site that you want to call My Life Story in 50 Words or Less, you can enter your title and your text and then proceed to insert the commands necessary to display the content as you want it to appear. If you type multiple paragraphs into your Web document without HTML formatting, the text that appears in a browser looks like a single long paragraph. To break this text into separate paragraphs, you must insert an HTML tag, <p>, in between your paragraphs.
CREATE A SIMPLE WEB SITE
Web pages must have the extension .html or .htm, and must start with a tag, <html>, that identifies the content as HTML. Most formatting commands in HTML have both an opening and a closing tag. For example, you start a Web page by typing the opening tag <html> and end it by typing the closing tag </html>. All closing tags in HTML follow the convention of starting with a forward slash (/). The simplest Web page, therefore, starts with <html>, contains text, and <p> markers to indicate paragraph breaks, and ends with </html>. A document as simple as this can constitute a Web site. There is no requirement that you insert images or links that point to other sites, or other pages in your own Web site.
Type </html> and press Return. Save your text, and exit
Pico.
235
INTRODUCTION TO HTML
ou can create Web pages using the most basic HTML markup code. While you can use the HTML language to create extremely complex and extensive Web pages, you can also create attractive and functional pages by inserting a few simple HTML tags into your documents. These tags allow you to change the font of selected text, making it bold or turning it into a heading that stands out. They allow you to insert images, build tables, and insert links to other pages on your site or to other Web sites. You can also mark selected text as preformatted so that Apache does not wrap the text lines together. Most HTML tags come in pairs. That is, there is an open tag as well as a close tag. For example, if you want to underline a phrase in your document, you indicate the text you want to underline by inserting <ul> where the underlining should start, and </ul> where it should end.
In some cases, you do not require tag pairs to format the text you want to change, but it is considered good form to use them. For example, if you mark the beginning of a paragraph by inserting <p>, you should also mark the end of the paragraph with </p>. Similarly, list items should begin with <li> and end with </li>. To insert an image into your Web page, you can use the <img src=url> command. In the simplest form, this command provides the location of an image file that you want to display within your Web page. However, you can also specify additional commands to control the size and placing of the image. To add a link to another page or Web site, you can insert a command such as <a href="http://www.idyllmtn.com">click here</a>.
INTRODUCTION TO HTML
236
14
Type <img src=" followed by the name of an image file in your documents folder or images directory. Type width= followed by a
number and height= followed by a number to control the size of your image. Then type "> and press Return.
237
ou can create a structured Web page by inserting HTML tags in the proper sequence. While you can build a very simple Web page with almost no formatting commands, you can add to the functionality of your Web page by creating some additional structure.
One simple but important rule that you must keep in mind is that when you use tag pairs, such as <b> and </b>, you should use them in conjunction with other tag pairs such as <li> and </li> in such a way that one set of tags fully encapsulates the other. For example, to create a list item that is in bold, you should type <li><b>Last one to leave must turn off the coffee pot!</b></li>. While this rule is not strictly enforced for all tags, it is generally a good rule to follow.
A well-formed Web page has an overall structure that identifies the major portions of the page and follows this order of encapsulation: The outermost tags are <html> and </html>. Within these tags, you may have a section that starts with <head>, ends with </head>, and contains your title between <title> and </title> tags. Following the head, you may have a body that starts with <body> and ends with </body>. You then insert your paragraphs and links within the body section. The major sections of a Web page therefore follow a pattern as follows: <html>, <head>, <title>, </title>, </head>, <body>, </body>, and </html>. In between these major tags that provide the overall structure to your Web page, you insert the title, headings, links, and text that define the content as well as the look of your Web page.
Type <title>testing my new site</title> and press Return. Type </head> and press Return.
The text that you type
between the title tags appears at the top of browser windows.
14
239
ou can add simple styles to give your Web pages a more interesting and uniform look. The Cascading Style Sheets (CSS) model allows you to define styles within or independent of your Web pages, and to apply these styles to your Web pages in conjunction with HTML formatting. A style is simply a rule that associates display properties such as bold and blue with a particular HTML tag. The simplest way to define an internal style is to insert the style definition into your document. For example, to specify that a single heading is to be both bold and blue, you can type. <h2 style="color: blue; font-style=bold">From Birth Until Now</h2>. This style only applies to the text between the <h2> and </h2> tags. To force all of your <h2> level headings to be bold and blue, you can type the command h2{font-weight: bold; color: blue;} within the head of your document.
ADD SIMPLE STYLES TO YOUR WEB SITE
You can also define in one centralized file, or external style sheet, the formatting and layout for multiple Web pages. This approach allows you to apply consistent styles without having to recreate them in every page. In addition, if you need to make a change in the overall style of your Web site, you only need to change one file. To create a separate style sheet, you must create a file that contains the style definitions that you want to use. You identify this file with the extension .css. A CSS file contains style definitions such as the following: h1{font-weight: bold; color: black;} h2{font-weight: bold; color: blue;} You can then use a link or an @import command to use your cascading style sheet in your Web pages.
240
14
While using an internal style sheet may seem to be the easiest approach, you must define the style in every document you create, and you save little time and effort if you only use the style once. You place an internal style sheet in the head section of a document.
Example:
<head> <title>My life story in 50 words or less</title> <style type="text/css"> <! /* H2 headings are bold and blue */ h2{font-weight: bold; color: blue;} > </style> </head>
To access the same external style sheet using the @import command, you can enter text similar to the following:
Example:
<head> <title>life story</title> <style> <! @import url(styles.css); > </style> </head>
Type echo "h1{font-weight: bold; color: black;}" > styles.css and press Return. Type echo "h2{font-weight: bold; color: blue;}" >> styles.css and press Return.
ou can install Common Gateway Interface, or CGI, scripts to make your Web site interactive. CGIs enable your Web pages to exchange information with other programs running on your system. Many CGI programs collect information from visitors to your Web site, usually through a form, and pass that information to a program that processes the data. Other CGI programs simply collect data and display it. You can find many CGI programs on the Web and install them on your system. These programs can include counters that increment each time a new client visits your site, and forms that allow your visitors to sign a guest book. To use CGIs on your Web site, you must enable them in your httpd.conf file, and you must store them in the proper directory. CGIs normally reside in the cgi-bin directory, most likely /sw/apache/cgi-bin on your system.
You must set CGI programs to be executable before you can run them from your Web site. This means that they must have execute permission enabled so that anyone can execute them. You can add Execute permission using the chmod a+x command. Programmers usually write CGIs in Perl, because Perl is one of the most versatile and popular programming languages. You can, however, write CGIs using many different languages. There are many Web sites from which you can download pre-existing CGI scripts. You can also create your own CGI scripts; there are many books and Web sites that can teach you what you need to know to code in Perl and to build effective CGIs. An excellent book is Perl: Your visual blueprint for building Perl scripts, by Paul Whitehead, Wiley Publishing. You can also find a Web tutorial at www.cgi101.com/class/.
Type #!/usr/bin/perl w
and press Return twice.
Type use CGI qw(:standard); and press Return, then type print header; and press Return
again.
Type print start_html("this is a CGI"); and press Return, then type $greet="Thanks for visiting"; and press Return
twice.
press Return.
242
14
Most of the print lines in this simple CGI script are actually calls to the CGI module. When you type print header, for example, a routine in the module composes a proper HTML header. When you type print h1 and include a text message or a string variable inside parentheses, another module composes HTML code for a level-1 HTML heading.
243
ou can download and install additional Apache modules to expand the capabilities of your Apache server. While the default Apache installation sets up a very adequate and responsive Web server, the default set of modules that are included may not meet all of your needs. You can obtain a list of the modules that your installation of Apache already supports by typing httpd l. To upgrade your Apache server to include additional modules, you must download the new modules. If your Apache installation includes the mod_so module, you can install additional modules without having to recompile Apache. This is normal with recent installations of Apache. The mod_so module provides Apache with support for dynamic shared objects (DSO). This means that you can use an external module without changing Apache itself that is, without having to recompile. DSO modules load when Apache starts up.
After you compile a module into a DSO, you can use the LoadModule command that is part of the mod_so module in your httpd.conf file. This causes the module to load when you start or restart Apache. The exact line that you enter depends on the module that you are installing. The instructions that you obtain with the module, often found in a file called README or INSTALL, tell you which line to enter. To build a module into your Apache binary, you need to download the module, install the files into the modules directory for your Apache distribution, and recompile. Again, the exact process depends on the module that you are installing. Read the README and INSTALL files for Apache and the module that you are installing. Fortunately, the Apache Web site offers a list of modules along with a description of each one. This information helps you to find a module that can add the functionality that you require.
Open Internet Explorer from the Dock. Type http://modules. apache.org/ in your URL
field, and press Return.
244
14
Most, if not all, Apache modules arrive as gzipped TAR files. This means that you must use the gunzip and tar xf commands to extract your source files. You must then type cd into the target directory and look for a README or INSTALL file, which should contain detailed instructions for installing the module. To install a module using DSO, you follow directions similar to these:
Example:
$ ./configure with-apxs $ make $ make install
Most Apache modules contain fairly detailed instructions that tell you the commands you must type to install your new module. If you install modules using the dynamic method, you must confirm that your Apache daemon supports mod_so; to do this, type the command httpd l and look for mod_so in the output. If you prefer the static method, whereby the new module is built into your apache binary, or if your Apache daemon does not support DSO, you must first compile the new module, then follow instructions to move the compiled files into your Apache source tree, and then recompile Apache.
245
ou can develop PHP applications for use in your Web site. PHP is a relatively new language that integrates easily with the Apache Web server. When you can code in PHP, you can dramatically reduce the time that it takes for you to develop Web applications. In order to use PHP, your Apache binary must support it. To understand the similarities between PHP and HTML, you have only to look at some sample code. For example, to print a variable on a Web page, PHP mimics the style of HTML commands while using special tags that only belong to PHP: <html> <head><title>Latest Counts</title></head> <body><?php echo $grp1cnt<br>; ?></body> </html> PHP files do not need to be executable, and the output appears indistinguishable from HTML.
WRITE PHP APPLICATIONS
You must always enclose PHP scripts between two PHP tags. The tag pairs can be in one of several forms, such as <? and ?> or <?php and php?>, although some programmers use <?php and ?>. PHP uses many commands, including printing, looping, if commands, arrays, and forms, but if you are already familiar with HTML, you should grasp the fundamentals of PHP quite easily. PHP is a server-side scripting language. This means that the interpreter has to be installed and configured on the server before it can be used. No special client-side setup is required. The language combines features from Perl, Java, and C, so most people who have programmed in any of these languages will feel at home with PHP. All text to be written to the screen must be enclosed in double-quotes and almost all commands will end in a semicolon. Pages containing PHP commands should be saved with the extension .php.
TEST PHP
246
14
You can mix PHP and HTML easily in a single file. When you do so, you enclose each of your PHP statements in a pair of PHP tags, as in the sample below:
Example:
<?php $season="summer"; ?> We are now accepting reservations for our <?php print $season season; ?> Call 1-800-FUN-VACS today.
Basic comparison operators include all those listed in the table below. OPERATOR
== != = * / + . && ||
DESCRIPTION
Equal Not equal Assignment Multiplication Division Addition Subtraction Concatenation Logical AND Logical OR
This code segment assigns a value to $season and then uses this value to customize the content of the remainder of the display. In a similar manner to Perl, PHP allows you to create simple data types, like $season, and arrays in which you can use both a variable name and an index, such as $season[1].
CREATE A PHP
Type } and press Return, then type ?>. Save your file. 247
ou can analyze your Web traffic using a tool called Analog. Analog is a free, open source program that you can use to analyze Web traffic based on records stored in your log files. Analog can produce as many as 32 different reports. For example, it can provide you with charts that highlight heavy traffic times for instance, times of the day or days of the week. It can also show you which of your files visitors access most frequently, which files are not found, or where visitors are coming from when they follow links to your Web site. Analog has a configuration file, called analog.cfg. Fink installs this file into the /sw/etc/analog directory. Like most configuration files, analog.cfg is full of helpful comments, and has a number of configuration options. The most important of these options is the line that identifies where
you store your Web log files. If you store your Web logs in /sw/apache/logs, you must change the line that starts with LOGFILE to read LOGFILE /sw/apache/logs/access_log. If you do not have the correct log file location, Analog cannot analyze your Web traffic. Analog analyzes Web traffic by individual file requests, as this is the manner in which your system records Web traffic in your log files. Traffic can be reported hourly, daily, weekly, or monthly by turning report options on and off. For example, to turn monthly reports off, you can add MONTHLY OFF to your configuration file. To turn weekly reports on, you can add WEEKLY ON. To produce one of the many types of reports available from Analog, you can scan a list of the available reports and insert commands such as REFERRER ON in your configuration file.
CONFIGURE ANALOG
248
14
DESCRIPTION
One line for each month One line for each week One line for each day One line for each hour of the day A general summary Files that are requested Files that are not found Where visitors come from using links Sites from which visitors follow broken links Phrases and words visitors use to find your site Count of each type of success and failure
RUN ANALOG
249
ou can use Perl to write a simple script that does not require compiling. Perl is an interpreted language. However, Perl looks like a compiled language in a number of ways. For example, each statement in Perl ends in a semicolon, and a $ symbol precedes variable names, even when you first declare them and assign them a value. More importantly, Perl allows you to build subroutines, pass variables, and return values like most compiled languages. Perl also has sophisticated array handling. However, the feature that most distinguishes Perl from other languages is the versatile use of regular expressions. If your only experience with regular expressions comes from working in one of the Unix shells, you may be amazed at the versatility of the Perl language. For example, you can use regular expressions in Perl to do fuzzy matching. With fuzzy matching, instead of asking whether one number is
WRITE A SIMPLE PERL SCRIPT
greater than another, or looking for a number in a string, you can ask if a line of text contains an e-mail address or a date/time stamp by describing these items as patterns. Although the use of regular expressions can make Perl code difficult to interpret at first, when you become more familiar with each of the symbols, you can begin to appreciate the succinct form of the language. The elements of a Perl pattern are referred to as metacharacters. For example, \s represents a single whitespace character a blank or a tab and \S represents any non-whitespace character. You can also amend these patterns to match some or none or a string of any size. Where \d represents a digit, \d+ represents any number of digits and \d* represents any number of digits, but will also match no digits at all.
250
15
As with most Unix scripting languages and configuration files, you create a comment in Perl by placing a # symbol at the beginning of the line. You can place a comment on a line by itself or append it to the end of a line of code. Either of these forms is correct:
Example:
# say hello print "Hello, World "; # say hello
The "\n" shown in the screens below indicates a newline character. If this character were omitted from our print statement, the script would print the output without moving to the new line, and the next system prompt would be on the same line. You usually include newline characters in the print statements along with text that you want to print. For example, you can type the line print "Hello, World\n"; in a Perl script to print the message and move to the next line.
When you create a complex script, you should include some comments that explain what your script is doing, but avoid superfluous comments that may annoy someone who reads your code. In Perl, comments are often used to explain complex regular expressions.
251
ou can run a Perl script by using it as an argument to the Perl interpreter, or by making it executable. After you create a Perl script, you can instruct Perl to interpret and execute the script, for example, by typing perl myscript.pl. This is the simplest way to run a script, but not the most convenient. Most users prefer to run scripts as though they are new commands, and without having to know anything about the language in which they are written. Thus, they may not want to type perl before the name of the script. For the convenience of users, and to avoid errors that may generate if they type the name of the script on a line by itself, you can insert a line at the top of the script that identifies your file to the shell as a Perl script, and you can make the script executable. You refer to this line as the
shebang line, and the syntax for this line is #! followed by the name of the interpreter. For a Perl script, you can type #!/usr/bin/perl. If you make your Perl script executable without the shebang line, the system cannot determine what tool to use to run the script, and it attempts to run the commands using your shell. This action generates a number of errors, as tcsh does not include a print command. If you mistype your shebang line, your system cannot find the interpreter and issues an error such as "not found: myscript.pl". You can force yourself to use rules that are more restrictive in your Perl coding by adding use strict; to the top of your scripts. While adding this to your scripts may generate warning messages, these messages may help you avoid many potential errors in your code.
15
You can use the command line option -w on the shebang line by typing #!/usr/bin/perl -w to instruct Perl to issue warnings regarding your syntax. For example, if you define a variable, such as $counter, and then never use it, Perl warns you that this variable appears only once in your code. By doing this, Perl is telling you that you have made a mistake or, at least, strayed from your original intent in writing the script. Perl warnings are very useful when you are first learning the language, as they can help you to spot problems that prevent your script from running, or represent poor scripting style.
The shebang line tells the shell which language you used to write the script and, consequently, what tool the shell can use to run the commands. For the script to run, the shebang line must contain the full path to the Perl interpreter. This is the case whether or not the Perl binary is on your search path. Also, this line must be the first line in the script and must start with #!.
253
ou can use the ability of Perl to recognize patterns to help you manipulate text. If you are able to describe a pattern that you are looking for in a stream of text, then you can represent it as a Perl regular expression with which you can easily extract and manipulate it.
include as characters you want to match with an escape character. The escape character tells Perl to take the following character literally and not to interpret it as part of the Perl syntax. Thus, \/ represents / in your search pattern. Perl has many special character sequences, such as \d, to help you to locate and manipulate text. Users refer to these character sequences as metacharacters or escape sequences. Many metacharacters have both a positive and negative form. For example, while \d represents a digit, \D represents a non-digit any character that is not a digit. While \s+ represents any amount of whitespace, \S+ represents any string of characters that does not contain any whitespace. The biggest challenge to most Perl beginners is to remember what each of the metacharacters represents.
For example, if you are looking for dates that look like 05/01/03, you can tell Perl that you want strings that match the pattern \d{2}\/\d{2}\/\d{2}. While this expression may look complicated, a quick breakdown makes it easier to understand. The string \d matches a digit, and when changed to \d{2}, it matches a two-digit number. The date above includes three of these strings. The two extra forward slashes in the search pattern indicate that the strings you are searching for contain slashes. Because slashes are a part of the Perl syntax, you must precede any slashes that you
Type #!/usr/bin/perl w
and press Return twice.
Type while ( <> ) { and press Return, then type if ( /\d{2}\/\d{2}\/\d{2}/ ) { and press Return. Type print $_; and press Return, type } and press Return, and then type } and press Return.
254
15
Perl recognizes many different metacharacters, allowing you to closely describe text that you are looking for and to manipulate it. The table below METACHARACTER \d \d+ \d* \D \e \f \l \n \r \s MATCHES
A digit. One or more digits. Zero or more digits. A non-digit. The escape character. A form feed. A lowercase letter. A newline. A carriage return. A whitespace character.
shows some of the most common metacharacters and what they represent. You can use the + and * qualifiers with any of the metacharacters. METACHARACTER \s+ \S* \t \u \w \W \O? \x? MATCHES
Any amount of whitespace. Some whitespace or no whitespace. A tab. An uppercase character. A word character a letter, digit, or underscore. A non-word character. An octal character. A hexadecimal character.
Type chmod a+x finddates.pl and press Return. Type ./finddates.pl followed by a space.
255
$tothrs=0; foreach day ( Mon,Tue,Wed,Thu,Fri ) { print "hours worked on $day> "; $hrs = <STDIN>; $tothrs = $tothrs + $hrs; } print "You only worked $tothrs hours!"; This script prompts the user to enter the number of hours that they work each weekday, and computes a total. However, this script generates an error message if the user enters anything other than a number, because the addition fails. You can insert a while statement inside the foreach statement to repeat the prompt until the user enters a number.
Type #!/usr/bin/perl w
and press Return twice, then type print "Enter your favorite number> "; and press Return.
256
15
There are times when you do not want to use data exactly as a user enters it. For example, when you tell the user that their favorite number just happens to be your favorite number, too, as in the favnum.pl script, your message displays on two lines instead of three. This unintended line break results when Perl reads the input line, including the linefeed, and retains the linefeed. As a result, when the output displays to the user, the linefeed is still present in the $favnum variable. You can remove these unwanted linefeeds by using the chomp command. The chomp command simply removes the linefeed from the end of the line. The format for the chomp command is chomp($variable). Thus, you can add the line chomp($favnum); to the script immediately after the line that reads the response from the user. When the chomp command removes the linefeed, the output changes to reflect this. BEFORE:
What a coincidence! 111 is my favorite number too. Maybe we should go out.
AFTER:
What a coincidence! 111 is my favorite number too. Maybe we should go out.
257
is good practice if you want to ensure that the files that you read are preserved, as it opens the file only for reading, and disallows any write operations. Just as the < symbol indicates that a command is opening a file for reading, the > symbol indicates that a command is opening a file for writing. Using the > symbol indicates that a command is opening a file for appending. In other words, you write from the end of the file, preserving the current contents of the file. To be sure that your scripts do not malfunction when input files do not exist or are unreadable, you can add an or die clause to your open command. The command open(INFILE,"<myfile.txt") or die "Cannot open myfile.txt for reading"; displays the cautionary message if the input file is unreadable, and exits the script.
Type #!/usr/bin/perl w
and press Return twice.
258
15
Another way to read files in Perl is to use backticks. For example, if you want to read the contents of a file into an array, you can use a command such as @lines=`cat myfile.txt`;. This command runs the cat command, collects the output, and stores each line in that output as an element in the array @lines. While this operation is as simple as the more formal open commands, it also involves more overhead especially for very large files as it stores the data it reads into memory. When the operation reads a file one record at a time, it stores one record at a time. Backticks are a good way to get information from your system. For example, if your script needs to use the current date, you can assign the date to a variable using a line such as $date=`date +%m%d%y`;. This command stores a date of the form 05/01/03 to the $date variable. You can then use this variable to name output files or to add records with a date stamp to a file you are creating. For example, you can open an output file with a command such as open(OUTFILE,">myfile.$date");.
259
ou can write files with Perl as easily as you can read files with Perl. In fact, the command for opening a file for writing is almost the same as that for opening a file for reading. The command open(OUTFILE, ">myfile.out") or die "Cannot open myfile.out for writing"; attempts to open the specified file for writing and exits the script if this cannot be done. Changing the > symbol to the >> symbol appends any subsequent output to the file instead of overwriting it.
If you write text that does not contain linefeeds, you will not have separate lines in your output file. The print operation does not add linefeeds whether it is writing to the screen or to a file. When you are finished writing to a file or reading from a file, you can close the file. The close command is very similar to the open command except that you only need to use the file handle, and you do not need to specify the filename. For example, if you want to close the file associated with the file handle OUTFILE, you type the command close OUTFILE; and the file closes and is no longer available for reading. If you are creating a temporary file and you want to remove it when you finish with it, you can use the unlink command in place of the close command. The unlink command removes the file from the file system.
After a file is open for writing, you can use the print command to write to it. While a command such as print "Maybe we should go out\n"; prints to the screen, the same line with an additional argument print OUTFILE "Maybe we should go out\n"; writes the line to the output file.
USE A WHILE LOOP
Type pico write1 and press Return. Type #!/usr/bin/perl w and press Return twice. Type open(INFILE, "<my file.txt"); and press Return, then type open(OUTFILE, ">myfile.out"); and press
Return twice, then type
$counter=0; and press
Return twice.
260
15
One of the advantages of using Perl over other scripting languages is that it allows you to read and write any number of files at the same time. For each file that you want to use, you type an open command, specify the filename, indicate whether you are opening the file for reading, writing, appending, or both reading and writing, assign a file handle, and write records to the file. When you are done, you type a close or an unlink command.
For readability, your file handles should be meaningful. If you use a temporary file, calling it TMP or TMP1 makes it clear to anyone reading your code that you do not intend to preserve the file. If you use temporary files, you must always remember to unlink them when you are done; otherwise, your script may not run the next time you try to use it because it may not be able to open a file that already exists. In addition, scripts that leave unnecessary files behind when they finish running create clutter in your file system. Giving temporary files random names, such as myfile$$, reduces conflict over filenames.
Type open(LOG,">>$log);
and press Return, then type
print LOG "$date: $tothrs hours\n"; and press Return again, and then type close LOG; and save your file.
261
and examples of how the module can be used. After you click on the link that takes you to the page describing the module you want, you can scroll down the page to find a description of the module along with information on usage, debugging, parameters, and more. There are many Perl libraries and modules already installed on your system. You can list the installed modules with the command find/System/LibraryPerl name "*.pm" print. This directory even includes a module for making the process of downloading other Perl modules from CPAN even easier. You can look at CPAM.pm or read about this on the CPAN Web site to find out more.
262
15
Before you can use a Perl module in your script, you must load it with the use command. The command use diagnostics; loads the module diagnostics.pm from your /System/Library/Perl directory. The command use Net::Telnet; loads /System/Library/Perl/Net/Telnet.pm. You can also build your own Perl modules. If you develop Perl code that may be used in many scripts or by many users, you may want to turn the reusable code into a module and install it into the /System/Library/Perl directory.
You must use the package command to create Perl modules, and you must organize them as subroutines, and name them with the file extension .pm. Construction of a module also requires the use of commands to export items that you create in the module. For more information about creating Perl modules, you can consult Perl: Your visual blueprint for building Perl scripts, by Paul Whitehead.
CONTINUED
263
ou can install Perl modules to increase your productivity as a Perl programmer. There are many Perl modules that you can download and install to increase the sophistication of your Perl scripts. Each Perl module contains a number of routines that are relevant to a particular type of processing. For example, the CGI module reduces the code that you must produce to create CGI scripts. Most modules are free, and you can modify them, if needed, to suit your application. Modules are contributed by their authors who consider them useful enough to be generally valuable. If you are now or become a proficient Perl programmer, you might consider contributing modules that you develop to the Perl community. You may sometime acquire a Perl modules in the form of a gzipped TAR file. When this is the case, the process of installing looks much like the process of compiling open
source software from the same kind of file. However, because Perl is not compiled, the make step will not result in a compilation. The steps for installing a Perl module packaged as a tar.gz file are as follows: gzip <module-name.tar.gz> tar xf <module-name.tar> cd <module-name> perl Makefile.PL make make test make install Some Perl modules will require other modules to be installed before they can be used. When a module that you are trying to install has a prerequisite, you will get a message when you type the perl Makefile.PL command.
264
15
A pragma is a special Perl module that comes with your installation of Perl. If you have tried the use strict; command, you have already used one of these special modules. You can learn more about the pragmas that are included in your release of Perl with the command man perlmodlib. Perl has a search path that it uses to look for modules. You can view this by issuing the perl e 'print "@INC"' command as shown here. TYPE THIS:
[ferro:~] user% perl -e 'print "@INC"'
If you are interested in the format and other technical details of how Perl modules are organized, the Perl mod man page will provide you with many insights. In a Terminal window, type man perlmod and press Return.
RESULT:
/System/Library/Perl/darwin /System/Library/Perl /Library/Perl/darwin /Library/Perl /Library/Perl /Network/Library/Perl/darwin /Network/Library/Perl /Network/Library/Perl .[ferro:~] user%
Telnet.pm
In a Terminal window,
type sudo cp Telnet.pm
/System/Library/Perl/Net
or copy your Perl module to the proper location in /System/Library/Perl using the name of the module to determine if the library belongs in a directory.
265
ou can write a CGI script to create a Web page that interacts with your visitors. While the term CGI identifies a class of script that allows Web pages to interact with the system on which the script is running, most scripts are written in Perl. This is because the versatility of Perl makes it a good language to use on the Web. The basic function of a CGI script is to perform a process and then to prepare the output in HTML format so that it can display in a Web page.
The CGI module uses functions to generate HTML code. These include header and start_html functions that create the HTML header and tags such as <html> and <body>, which you need to format an HTML page. Other functions include h1, hr, and end_html. As you see, these commands resemble HTML codes. A command such as print h1("My Life in 50 Words or Less"); takes the place of a print command containing the beginning and ending tags for heading level 1 text. You can use CGI scripts to build pages that contain dynamic text, because you can use Perl commands to gather information from the system or vary the contents of the page in other ways. You can also build CGI scripts that create a form allowing the user to enter text, and then process that text.
To use the CGI module that installs on your system, you can use the Perl command use CGI;. This command loads the CGI module into your script. For most CGI scripts, you amend this command by specifying that you want to use the most command functions. The altered use command then becomes use CGI qw(:standard);. This allows you to access HTML, form generation, and CGI functions.
WRITE A CGI SCRIPT
In the Pico text editor, type #!/usr/bin/perl w and press Return twice. Type use CGI
qw(:standard); and press
Type print header; and press Return. Type print start_html("this is a test"); and press Return
twice.
Type print h1("This is a CGI"); and press Return. Type print hr; and press Return twice.
Return.
266
15
To create a Web form with CGI, you can use commands that create form elements such as text fields. While you can create these elements without the assistance of the CGI module, the CGI commands simplify the work considerably. For example, to create a text field into which a user types information, you can use a command such as print textfield('comment','Enter your comment',70,80);. This command creates a text field, displays the phrase "Enter your comment" in the text field, and sizes the field to 70 text characters. You can add a submit button with a command such as print submit("submit comment");. What happens next depends on the remainder of your code. When you run this script, it submits the comments to a process called process_comments.pl.
Example:
#/usr/bin/perl use CGI qw(:standard); print header; print start_html; print h1("We want your comments"); print start_form(get,'process_comments.pl'); print textfield('comment','Enter your comment here',70,80); print end_html;
267
ou can install and use the X Window System to enhance the capabilities of your Mac OS X system. The X Window system is a windowing system that facilitates the sharing of windows on a network. For example, you can run an application on one system and send the display of that application to another system.
FULL SCREEN VERSUS ROOTLESS
In addition, if you install X Windows on your Mac OS X system, you can take advantage of numerous tools that were specifically built to work on the system. X is a windowing system that works through the cooperation of separate components. The native windowing system on Mac OS X is called Aqua.
The X Window System, often referred to simply as X Windows or X, can be run in one of two modes. The first is full-screen mode. In full-screen mode, the X window server takes over your desktop, replacing Aqua.
The second is called rootless mode. In rootless mode, the X windows live side by side with your Aqua tools rather than taking over the screen.
WHICH X IS WHICH?
There are several versions of X Windows that you can run on Mac OS X. XDarwin is a port of the XFree86 software and is free. You can also get an X11 implementation from Apple that is also based on XFree86 and is a relative newcomer to the X scene. There is a commercial X
Window System implementation called XTools available from Tenon. All X servers perform the same function and support the X protocol. Given the significant efforts, installing an X server on your Mac OS X system should not be difficult.
In the world of X Windows, the terms server and client take on new meanings. The X server is your display the screen in front of you that you can think of as serving you windows and the environment in which your X applications run. The X client is any application that produces output for the server to display. Another important player in the world of X Windows is the window manager. A window manager, such as twm or Enlightenment, adds a layer of control to your desktop and stylistic elements to your windows. Desktops attempt to provide a more complete interface to the
system and generally provide a suite of integrated tools and applications. Many Unix desktop environments support X Windows natively. This is true, for example, of the common desktop environment (CDE) run on Solaris, and GNOME and KDE on Linux systems. Aqua does not provide support for X Windows without add-on software such as XFree86 any more than Microsoft Windows does. For these systems, you may acquire and install X server software separately.
268
16
DESKTOPS
While you will probably install only one version of X Windows on your system, the choice of which window manager and desktop to use is up to you. Two of the more popular desktops are GNOME and KDE, both of which are popular with the Linux community and increasingly available for Mac OS X users. The XonX project, which refers to X Windows on Mac OS X, is a good source of information and software. You also have a choice of what clients to run on your server. The xterm client is a terminal tool much like the
Terminal application on your Mac OS X Aqua desktop, except that xterm runs on an Xserver. Similarly, xclock is an X Windows clock. While these tools are fairly basic and part of every X Windows implementation, they do not define the limits of what an installation of X Windows can do for you. Many powerful applications, such as OpenOffice, an office automation tool much like Microsoft Office, and the Gimp, a sophisticated image-editing tool, are available to you free if you first install X Windows.
HISTORY OF X WINDOWS
The X Windows System was originally developed at MIT with support from DEC. It was originally meant to provide a distributed hardware-independent user interface for the Athena project. The software reached
version 11, sometimes referred to as X11, before a general interest had developed. Control of X11 has since been taken over by the X Consortium which now maintains the standard.
When using X Windows, your display has an address that is associated with the environment variable DISPLAY. If you print the value of this variable by typing echo $DISPLAY in a Terminal window while running an X server, you will notice that the value will be set to 0:0.0 or simply 0.0. While this address may seem to have no significance, it actually refers to the first screen associated with the first X server on your system. The address of your display from the perspective of another system on your network would be ferro:0.0 if your hostname were ferro. When you are generating a display on one system and sending it to another, you need to do two things: 1) Set your DISPLAY variable on the system where the client is running; this is the system generating the display.
2) Run the xhost command on the X server to give permission to the remote system to write to your screen. The xhost command can be run in such a way that it only adds the specific client or so that it allows any system to write to its display. It is generally more secure to restrict access to your screen but this, of course, depends on your situation with respect to the security of the network to which you are connected. To send the output from an X client system to the X server running on ferro, you would type setenv DISPLAY ferro:0.0 on the client system and xhost + on ferro to allow any system to update your display. Enter a specific hostname instead of the plus sign (+) if you want to restrict this access.
269
When you scroll down the page, you will find a section that provides information on the latest file releases. This will provide you with the current release information you need. When you click the View ALL Project Files link, you will see a list of the current files. The largest file in this list, the SIT file, will be the major release of XFree86. You will need to install this release before the ZIP files, which update the major release with patch files. When there are two or more for the same sub-release, as there are with 4.2.0.1, you will only need to install one of these files. You will install each of the patch releases in order. That is, you will install the oldest sub-release first. After installing the major release and each of the sub-releases, you will have 4.2.1.1 of XFree86 installed on your system.
270
16
When downloading software such as XFree86 to your system for subsequent installation, it is good practice to store all of your downloaded files in a single directory. While file systems like that which Unix uses are meant to help keep your personal files and application software organized, it is easy to allow your file holdings to become disorganized and difficult to clean up sufficiently after the fact.
Some files, like the XFree86 XInstall_10.1.sit file are large and will take a long time to download on a dial-up connection. If you are installing this software on a personal system and using a dial-up line, you may want to consider starting late at night and checking in the morning to see if the download completed properly. The ZIP files needed to bring this release up to the current release are relatively small and do not take long to download. The sourceforge.org site is a good site to bookmark. This site is one of the major places for learning about and obtaining open source software.
Click Download
Link to Disk.
Click Save.
The file saves to the
location you chose in step 6.
Right-click
XInstall_10.1.sit.
CONTINUED
271
provided X Windows with a legitimacy that furthered its importance in the commercial world. At the same time, the XFree86 Project continued development of X for the open source community. The Open Group formed X.org in 1999 to continue fostering the development of X. Today, XFree86 is one of the most critical of the open source projects. It provides X windowing support to a large portion of the open source Unix systems and ships with most Linux distributions. Currently in Release 4.2.1.1 and available for the latest Mac OS X release, XFree86 is a solid implementation of X Windows and one that will continue to develop along with the open source community. The name XFree86 was first used in 1992, replacing the name X386 used in the preceding year of development.
Click Save.
The files save to the
location you chose in step 10.
272
16
Getting XFree86 on CD-ROM If the procedure for downloading XFree86 seems overly complex or time-consuming, you can obtain XFree86 on CD-ROM. For a modest fee, the same version of XFree86 that you can download from the Web is available on CD. Purchasing the CD will save you the trouble of downloading the proper set of files from the Web. Visit www.xdarwin.org for information on purchasing the CD and for other information on the XDarwin project.
XDarwin is the name of the X server for Mac OS X that is included in the XFree86 distribution. XonX is a SourceForge project used by XFree86 for Darwin developers to share code. You can get all of the XFree86 source code from www.xfree86.org. After your XFree86 software is installed, you start it by double-clicking the XDarwin icon. You will probably find that keeping XDarwin in the Dock is the most convenient way to use the software.
Click Save.
The files save to the
location you chose in step 14.
273
INSTALL AN X SERVER
ou can install an X server on your Mac OS X system. After X Windows is installed, you can then run many applications built to run in X Windows.
To install XDarwin, the port of XFree86 to Mac OS X, you will need to download a series of files or procure an installation CD. As of this writing, you will need to install XFree86 4.2.0 followed by two patch releases 4.2.0.1 and 4.2.1.1 to get a trouble-free installation for Mac OS X 10.2. This gives you a basic X environment. You will probably then want to quickly move beyond the default window manager, twm, to one that provides a more attractive and useful desktop. One of the simplest ways to install Xfree86 is to acquire the 4.2.0 release in the form of a SIT file from sourceforge.net. The URL sourceforge.net/projects/xonx where "xonx"
INSTALL AN X SERVER
means X Windows on Mac OS X is the place to start. The XFree86 4.2.0 file is roughly 56 Mbytes in size, so be prepared for a long download time if you are using a dial-up connection. Check the XonX site for updates. Any X server that is more than six months old is likely to have new patches available or have moved to a new release. After this file is downloaded, you can double-click the SIT file to install the initial X Windows server and then install each of your patch files in release order. The patch files are available as ZIP files. You can install these updates, or patches, by double-clicking the icons. If you are working on a dial-up Internet connection, you might prefer to install XFree86 from a CD-ROM. You can acquire CDs at minimal cost from sites such as www.gnu-darwin.org.
In the Finder, open the folder containing your downloaded XFree86 SIT file.
274
16
While the procedure described below installs basic X Windows, keep in mind that the version of XFree86 that you should install will change as time passes. Consult the XonX site and amend the filenames and your procedure according to the information available on this site. You can also install an X server using Apple's Get MacOS X Software... link from your Apple menu. Apple's X server is called X11 for Mac OS and, at this writing, is a Public Beta release. Apple's implementation of X Windows is also based on XFree86.
Files used in X Windows include .Xdefaults, which sets default preferences for windows services, and .xinitrc, which establishes your initial screen setup. A typical .xinitrc file might start several windows on your display. These will often include the more typical X clients, such as xterm a terminal emulator; xlock a simple analog clock; and xeyes a pair of eyeballs that follow your cursor around the screen.
Click OK.
Continue through the
remainder of the installation.
275
ou can install XFree86 upgrades to bring your XFree86 installation up to the current release from the base release. Upgrades will usually bring bug fixes and performance improvements and are generally worth the time that it takes to install them. Because the ZIP files containing the modified files are generally small, the process of downloading and installing them takes little time and little effort. The upgrade installations complete the installation and assume that the two upgrade files have been downloaded as described in the "Get X Software for Mac OS X" section. While one specific upgrade is being installed in this section, this process is repeated for both of the upgrades downloaded in the previous section and for other upgrades that you may need to install in the future. XFree86 upgrades are distributed as ZIP files. The easiest way to install one of these files is to double-click the icon in
INSTALL XFREE86 UPGRADES
the Finder. This will unzip the file and create an install file. When you double-click the install file, your upgrade installation will begin. As with most installations of this type, you will be required to authenticate yourself so that the system can verify that you are an administrator on the system and have the authority to install applications. The process will then run through a couple of additional steps. You will have to select the disk on which the software is to be installed. You should select your Mac OS X system disk to simplify administration. Click Next to proceed with the installation and click Install before the software starts to load onto your drive. The installation can be restarted if needed. Whenever you install more than one upgrade, be sure to install them in the order in which they were created.
16
After XFree86 is installed on your system and you have verified that it works properly, you can remove the ZIP and install files for the upgrades along with the SIT file for the major release. If you do not need the space, keeping these files available in case a re-install is needed is probably a good idea. There is little reason to keep these files after you install and verify a new major release, like XFree86 4.3. While XFree86 is an extremely useful tool and enables you to run many applications previously not available on Mac OS X, the look and feel of your X environment depends on the window manager that you decide to use. For most X users, installing XFree86 is just the beginning of setting up a versatile X Windows environment.
If you need help with XDarwin, you can take advantage of the discussion forum on the www.xdarwin.org site. You can also look for in-depth information on technical issues at the SourceForge/projects/XonX site. The XonX site provides a public discussion forum as well as several mailing lists that are devoted to such topics as porting Unix software to Mac OS X.
A summary description of
the software appears.
277
ou can start up your X Windows server in rootless mode. This allows you to run X applications side-by-side with Mac OS X applications.
Each time you start XDarwin, the system will ask whether you want to run in full-screen or rootless mode. If you will always be running in one mode or the other, you can select your mode and click the check box so that the application stops asking you this question. Both modes have their advantages, however. To start in rootless mode, click the Rootless button after double-clicking the icon for your XFree86 application or after starting it from the Dock. The X Windows that launch when you do this depend on the contents of your system's .xinitrc file or on your personal .xinitrc file if you have one. For example, the following lines from an .xinitrc file would start up several xterm windows and a clock: xclock -geometry 50x50-1+1 & xterm -geometry 80x50+0+0 & xterm -geometry 80x20+400-0 & exec xterm -geometry 80x66+0+0 -name login
START X86FREE IN ROOTLESS MODE
You will notice these windows when you start your X session. The numbers associated with the xterm command define the number of columns, the number of rows, and the screen location. For example, the first xterm defined in the lines above will have 80 columns and 50 rows; 80 columns wide is equivalent to the width of 80 mono-spaced characters side-by-side. Its upper-left corner will be placed in the upper-left corner of the screen. The most convenient way to start X Windows is to elect to keep it in the Dock after you first bring it up. You can then customize the windows that start by making a copy of the system-wide .xinitrc file and installing that copy as .xinitrc in your home directory. When you first install XFree86, you will be using the default window manager. It is called twm and, while it adds some window controls to your windows, it is a dull window manager.
Click Rootless.
278
16
You can update your search path to include X Windows tools. This will allow you to start X tools by entering their names without a full pathname. X tools will usually install in the directory /usr/X11R6/bin. By including this path in your PATH variable, you instruct your shell to look in that directory when you enter a simple name such as xeyes. Your search path, defined in your .tcshrc file, will look something like this:
Example:
setenv PATH /usr/bin:/bin:/sbin:/ sw/bin:/usr/local/bin:/usr/X11R6/bin
You can change the colors used on a xterm window by modifying the parameters used in your .xinitrc file. The command "xterm -n xtermblahblahblah -bg black -fg white geometry 80x25+0+0 &", for example, generates a window named "xterm-blahblahblah" with a black background and white letters. The Terminal window would be 80 columns wide (standard width) and 25 lines long beginning in the upper-left corner of the screen.
279
ou can install the GNOME desktop on your Mac OS X system if you have first installed an X server such as XFree86.
gnome-wm & exec gnome-session The next time you start X Windows after making these changes, your desktop will start running with GNOME. As with XFree86 out of the box, you can run GNOME in rootless or full-screen mode. When you run rootless, your X Windows will take on the appearance of GNOME windows, using the GNOME window dressings. The rest of your windows will retain their Aqua look. You will be able to start additional X tools from your xterm windows. For example, you can start the xeyes tool by typing /usr/X11R6/bin/xeyes in an xterm window and pressing Return. When you start GNOME in full screen mode, as is generally the case, GNOME will take over your desktop. All vestiges of your Aqua tools and menus will disappear from view. GNOME menus will be available on your desktop for starting any of a number of X applications.
GNOME is one of the most popular X Window System desktops. Developed for the Linux community, GNOME now runs on Solaris and Mac OS X systems as well. Because this porting effort is recent, installing Gnome can be a slow and somewhat problematic installation especially on a slow dial-up connection. You can also acquire binaries on CD-ROM. The following sites provide information on X Windows for Mac OS X. http://sourceforge.net/projects/xonx http://www.xdarwin.org After GNOME is installed on your system, you can use it as your X Windows desktop. To use GNOME, you should edit your .xinitrc file and add the line exec gnome-session to the bottom of the file. Be sure to comment out the line that starts the default window manager, twm. The bottom of your .xinitrc file, after editing, might look like this:
RUN THE GNOME DESKTOP
280
16
Many of the applications available through the GNOME desktop are traditional X tools such as xterm, a terminal emulator, and xcalc, a simple calculator. Other applications, such as xv and the GIMP are quite sophisticated tools for manipulating images. GNOME supports the concept of virtual desktops. The small object in the bottom left hand corner of the screen represents each of four virtual desktops. You can move from one desktop to the next by clicking any of the four rectangles. The upper left rectangle represents your default screen. If you do not like working with a cluttered desktop, you can start different applications on each of the four virtual desktops and move from one to the other as needed.
To exit the GNOME desktop, click Desktop Log Out. You can also start other X applications, those not included in the GNOME menus but installed on your system, by typing their names in an xterm window.
that full-screen mode will take over your screen, and telling you how to return to the Mac OS X desktop.
XDarwin launches in
full-screen mode.
281
ou can take advantage of an impressive collection of useful tools and applications when you run the GNOME desktop.
image editing program; and xv, a program for viewing and modifying image files. Each of these tools can be an extremely useful addition to your desktop. The look of your GNOME desktop will vary quite a bit depending on the window manager that you decide to use. Several are available to you and others can be obtained. Enlightenment and Window Maker are used in screenshots in this book. These two window managers have extremely different appearances, but will, of course, run the same applications. The third choice, twm, is also available. To alter your window manager, click Settings Desktop Window Manager. When you change your window manager, you will have an opportunity to save your new settings. Xterm windows are similar in character and to Terminal windows; therefore, you should be able to use these windows in the same manner that you would use the Terminal application when you are running in Aqua.
The GNOME desktop includes a number of utilities and applications that are built into the desktop. That is, you can start up these tools by selecting them from the menus available to you on your GNOME desktop. Some of these tools are simple applications that can make your system a little nicer to use. Others will make a tremendous difference in what you are able to accomplish on your system. The GNOME Programs menu contains a number of submenus, each with a variety of tools. The Applications menu includes tools such as emacs a highly configurable editor, and Gnumeric a spreadsheet program. The Utilities menu provides access to a simple calculator, a color browser, and other tools. The graphics menu provides access to GNOME Ghostview, a tool for viewing PostScript files; the GIMP, an
EXPLORE GNOME APPLICATIONS
Programs Applications
Programs
Click Programs
Applications.
282
16
If your GNOME desktop opens without the panels at the top and bottom of the screen, type panel no-xshm in an xterm window. Clicking the globe in the bottom panel will open Mozilla, the Web browser. With this tool, you can browse the Web the same as you would using Internet Explorer or Safari on your Mac OS X desktop. You can make the bottom panel slide over to the edge of your screen by clicking either end where the small arrow is displayed.
The Window Maker window manager gives your GNOME desktop an entirely different look and feel. If you selected this desktop by clicking Settings Desktop Window Manager, your desktop will change character. You can start up additional virtual desktops or workspaces by right-clicking in the background and clicking Workspaces New. You will then be able to navigate between these workspaces by clicking the backward and forward buttons on the icon in the upper-left corner of your screen. Within each workspace, you can then start different tools as if you had a number of work surfaces for working on different projects.
Programs
Graphics
Click Programs
Graphics.
283
INSTALL OROBOROSX
ou can install the OroborOSX desktop to take advantage of X tools on your Aqua desktop. OroborOSX allows you to run X applications while maintaining the look and feel of your normal Mac OS X desktop. The OroborOSX window manager actually provides several graphical themes. One of these mimics the look of your Aqua desktop and gives your Mac OS X and your X applications a seamless appearance. OroborOSX also provides a drop-down menu of applications that can be launched from your desktop when you are running OroborOSX. This menu appears at the top of your OroborOSX screen and is titled Launch. One of these tools is the GIMP, the impressive open source image-editing tool that rivals the capabilities of PhotoShop. Installing OroborOSX is a smooth process after XFree86 has been installed. The OroborOSX application can be retrieved from any of several places http://oroborosx.sourceforge. net/download.html and both binary and source distributions
INSTALL OROBOROSX
are available. This section outlines the process of installing the binary file, which is downloaded as a gzipped TAR file. When you double-click this file, you will walk through the installation process. OroborOSX will be installed in a matter of minutes and will be ready for use. You might want to keep OroborOSX in the Dock to facilitate its use. You will then be able to start X applications by first clicking on OroborOSX in the Dock and then starting your X application through the Launch menu or by entering the pathnames for the binaries in an xterm window. When you launch OrorborOSX, it will in turn launch XDarwin. OroborOSX is a good choice for anyone who wants to work in their normal Mac OS X desktop while adding some applications that only run in X Windows. Installation is trouble-free and extremely quick.
Double-click the
OroborOSX-Folder icon.
284
16
After OroborOSX is started, you can keep it in the Dock to make it easier to start when you want to use it again. Because OroborOSX works so well with your Mac OS X desktop, you may sometimes forget that you are running X Windows simultaneously with your Mac desktop. If you would like your inactive windows to appear dimmed, you can accomplish this by clicking Options Dim Inactive Windows. OroborOSX does not make use of your .xinitrc file. However, you can get it to read and execute the commands in this file if you click Launch xinitrc.
When you are running OroborOSX, all of the windows that you have open will be listed at the bottom of your Windows menu. To move from one to the next, you can click the window of your choice as you would normally do, or you can choose the window that you want to make active by clicking Windows and the name of the window that you want to make active. OroborOSX is an Aqua-like window manager based on a window manager named Oroborus.
Double-click the
OroborOSX icon.
OroborOSX launches
XDarwin.
285
ou can use xv, an interactive image manipulation program for X Windows, to display, crop, stretch, and dither images of many different types. To start xv, type xv in an xterm window. If you are using GNOME, you will find the program in the Graphics menu. A colorful fishout-of-the-water banner will greet you. Near the bottom of the page, you will see the message Press <right> mouse button for menu. To view the control panel for xv, press Control + click. To load an image, click the Load button. This will open a file browse window that allows you to select the image that you want to load. The image will load on your screen after you
click OK. You can use the options under the Image Size button to control the size of the image on your screen. The algorithms included in the Algorithms menu include a number of image manipulation routines that you can apply to the image. These include blur, sharpen, edge detect, emboss, oil painting, and copy and clear that rotate the image with and without blanking out the corners, pixelize, spread, and despeckle. For dabblers, there is also an Undo All option that reverses any changes you have made, bringing you back to the original image. xv operates on GIF, JPEG, TIFF, PBM, PGM, XPM, X11 Bitmap, Sun rasterfile, Targa, RLE, RGB, BMP, PCX, FITS, and PM image files. It can also generate postscript.
Type xv in an xterm
window and press Return.
Click Load.
286
17
The program can be downloaded from www.trilon.com/xv/downloads.html in source form and is included in binary format in the Darwin Collection: Free Software for Darwin OS and Mac OS X CD set for those who don't want to compile their own code. The program is available in binary form on the trilon site, but not for Mac OS X. Manuals are available in PostScript, PDF, and HTML format. You can close the xv controls panel any time you like. To get it back again, press + click in the displayed image.
After you have modified an image, you can save it using the Save button. The Format menu in the upper-right corner allows you to select the format for your saved image and, depending on the image type you select, asks if you want to use compression. You can load a number of images and flip through them using the Next and Prev buttons. You can crop an image by first selecting the area you want to retain using your left mouse button and then pressing Crop in the xv controls.
287
ou can use the GIMP to manipulate photo quality images. The GIMP, which stands for GNU Image Manipulation Program, is a freely distributed software tool that allows you to retouch photos and compose interesting images using a massive set of features. The tool is available from www.gimp.org/download.html and is often loaded when you install an X desktop, such as GNOME. GIMP is also included on the CD that accompanies this book. In an X windowing environment such as OroborOSX or GNOME, you can launch the GIMP through a menu. To launch the GIMP in OroborOSX, you click Launch MacGimp. Unlike most of the tools that you will use in X Windows, the GIMP opens a number of windows on your desktop. The toolbox provides the main controls by offering a grid of icons, each of which represents a different function, such as selecting a portion of the image, zooming in or out, and painting on top of the image with brush strokes.
EDIT IMAGES WITH GIMP
Launch
The toolbox also contains the File menu that provides for opening and saving images. It also allows you to modify preferences, such as the default image size and resolution, that apply each time you use GIMP. The toolbox is like a toolbar that lies along the top of most applications. Because it is a separate window, you can open and close it as needed. For serious image work, you will probably find layers essential. The best way to think of layers is to picture your image as composed of a number of transparencies, each which contributes a portion of the overall image, and yourself as looking through all of them at once. As you work with your images, the layers that you create will display in the Layers, Channels & Paths window that opened when you first started the GIMP. The active layer will always appear highlighted.
MacGimp
288
17
You can delete a layer by pressing and holding down the right mouse button in the Layers, Channels & Paths window and sliding down to Delete Layer. The ability to delete a layer is one of the best reasons to work with layers in the first place. They allow you to easily remove elements that you add to an image if they do not look as you had intended. If you have many layers, you can switch between them, determining which layer you are editing at any point in time, by selecting the layer in the Layers, Channels & Paths window. When you are completely satisfied with the overall image that you have created, you can collapse your image into a single layer. After performing this step, you cannot manipulate layers separately.
To save an image, press + click within the image window and click File Save As from the pop-up menu. If you want to save an image in the original format, you can leave the option for Determine File Type by Extension as is and type in your new filename. GIMP's format is called XCF. If your image has layers, you will have to collapse the layers using the Layers Flatten Image option or export the image to save it in a format that does not support image layers. You can preserve the layers by using GIMP's xcf format.
Background oldhouse.jpg
A thumbnail of the
CONTINUED
289
people who use GIMP make a habit of preserving their original images and saving their modified images using different names so that they can always start over. To crop an image, select the crop tool from the toolbox. The icon resembles a craft knife. Then left-click within the image window. When you click twice, you should notice two sets of corners appear like the diagonal corners of a box that move independently. The space between these corners, or elbows, defines the portion of the image that will remain after you click the Crop button. While you might find quite a bit of information on using the GIMP on the Web because this is a very popular tool using the tool is the best way to unveil all of the manipulations that are possible and which of them is going to work best with your own graphical style.
Type the text that you want to appear in your new layer.
Click OK.
290
17
The 5 x 5 element toolbox allows you to easily access the tools available for use within the GIMP. Pausing your cursor over any of the icons will cause a brief description to appear. The magnifying glass tool allows you to quickly zoom in on an image so that you can see more detail and have a finer degree of control over your work. To zoom back out, double-click the magnifying glass and click Zoom out in the Tool Options. Then click the image again. The effect of the magnifying glass will then cause you to zoom out. You can toggle between zooming in and zooming out as needed.
If you want to draw on top of an image, you can use the pencil tool. The Tool Options window for this tool allows you to modify the opacity of your pencil stroke and to select a color for your pencil strokes. The icon in the middle of the toolbox that looks like an eyedropper allows you to pick colors from your image. This allows you to work with colors that match the colors in your image instead of trying to match the colors by selecting them from a palette.
291
ou can display and edit Word documents with AbiWord. AbiWord is an intuitive word processing application with the same basic features as Microsoft Word. You start AbiWord when you are running an X Windows server by typing abiword in an xterm window. The tool will open up on your screen, allowing you to begin entering the text of your document. You can also open a pre-existing Word file. You use the AbiWord program in the same way as you would use other GUI word processors such as MS Word or Corel Word Perfect. If you trained on older, keyboardoriented word processing systems, you must get used to clicking on icons to make things happen. For example, formatting a page for right or left justification of text requires an easy click near the upper-right corner of the screen where pictograms display your choices. Other icons may be less obvious but clicking on any of them will usually bring up a menu with a logical suite of choices. For instance, if you want to save your work, you
click File in the top menu bar and see a menu with Save and Save As choices along with open and print options. Moving your cursor over the diskette icon causes the description to appear Save the document. If you select the diskette with a pencil pointing at it instead, you can rename the document. To concentrate on writing, you can easily remove most of the clutter of your AbiWord menus by clicking on View and then checking the Full screen box; only the menu at the top of the screen will then remain along with your text. You can manipulate tabs and margins with menus, or adjust their bars and pointers along the edges of the screen, as though you were using a real typewriter. As with any program, the fastest way to do something may be revealed only after some experimentation with different menus and patterns of keystrokes that suit your style of typing. If you are an experienced wordsmith, you can use these tricks intuitively in AbiWord and save a bundle of money by not purchasing expensive commercial products.
292
17
If you are writing a newsletter or other publication, you can choose one, two, or three columns to suit the style of your publication. You can find documentation for AbiWord, including an overview and a tutorial, at www.abisource.com/help. If you have any questions about quirks in the program, contact the authors at AbiSource.com. As with other open source products, news about problems experienced can be sent upstream to the community and tips and tricks can be downloaded from other users via discussion groups or FAQ pages.
AbiWord enables you to import images into your document by using the icon that looks like a landscape snapshot. It is probably wise to begin a document with this step and then write around the image. You can open Microsoft Word files, identified by their .doc file extensions, directly in AbiWord and then edit and save the files in the Rich Text Format.
Click a filename.
293
ou can use Gnumeric for simple calculations to complex numerical analysis. Gnumeric is a free spreadsheet released under the GNU General Public License. It has all the features that you would expect in a quality spreadsheet application, including a built-in manual, support for graphs, an extensive range of functions, cell formatting, and printing. It also has a powerful set of import and export filters that allow it to work with Excel, Lotus 1-2-3, Sylk and other spreadsheet formats. Graphic support, however, requires that you also have Guppi installed. To start Gnumeric, you can type Gnumeric in an xterm window. The tool will open with an empty spreadsheet. Entering data is as simple as clicking in a cell and typing text or a number. To enter a formula, you start by typing = and then you enter the formula, such as cos(100) or sum(A2:A20)
where A2:A20 defines a range of cells. If you are not used to spreadsheets, you will have to get accustomed to this nomenclature. The columns in a spreadsheet are labeled A, B, C, and so on while the rows are numbered 1, 2, 3, and so on. A2 is the cell defined by the second row in the first column. You can also select data by holding down your left mouse button and sliding over it. This often simplifies the process. Gnumeric, like most modern spreadsheets, will allow you to copy and paste a formula, adjusting the cell addresses in the process. If you sum A2:A20 and then copy your formula from A21 to B21, the new formula will sum B2:B20. If you are familiar with any spreadsheet application, you will probably be perfectly at home using Gnumeric.
294
17
You can turn a number in a cell into a percentage simply by clicking the percentage sign in the toolbar after clicking on the particular cell. This speeds up the process of modifying the format of your numbers, but uses the default format with two decimal points. Similarly, you can convert a number to display in monetary format by clicking the symbol that looks like a stack of dollar bills. You can use the green and red arrow keys near the upper-right corner of the spreadsheet to sort a series of cells in alphabetic or reverse alphabetic order. Simply select the cells that you want to sort and click the arrow representing the sort order of your choice.
The undo operation is available both as Edit Undo and through use of the curved arrow in the toolbar. Anytime you make a mistake, you can quickly reverse your most recent operation. You can add arrows and other annotations to your spreadsheet by selecting these tools from your toolbar. Icons in the toolbar allow you to change the justification of data in cells to right, left, or center justified. Click Help Gnumeric Manual to open a very handy user's guide.
295
ou can use Open Office to create documents, spreadsheets, illustrations, and presentations. You can also open documents that were created by other applications, such as Microsoft Office. Open Office is a suite of office applications that includes a word processor, spreadsheet, drawing program, presentation package, data source editor, HTML editor, formula editor, and macro and scripting language. Each tool is a professional and fullfeatured office automation tool that has years of development behind it from talented volunteers from around the world. Completely free, Open Office is based on code from StarOffice and 15 years of development by Sun Microsystems. It runs on Sparc systems as well as Windows and Linux and, as of this writing, is in the final stages of development for Mac OS X. To use Open Office, you need to first install X Windows. The word processor that is included in the Open Office suite is called Writer. You can use it to read, write, and
VIEW OFFICE DOCUMENTS WITH OPEN OFFICE
modify Microsoft Word documents. Open Office comes with spell check, clip art, and many of the same formatting features that you would expect in other professional word processing applications. When you start Open Office from the Dock or by doubleclicking on its icon in the Finder, the tool opens with Writer. From this application, you start the other applications as well. For example, File New Spreadsheet launches the spreadsheet application. Open Office will start XDarwin if it is not already running. Most of the items in the toolbar along the top and down the left side of the Writer's window will look familiar to you if you have used Microsoft Word or another word processor. If you are unsure of the meaning of any of the icons, position and hold your cursor over them and a short description appears.
File
Open...
Control+O
296
17
To view nonprinting characters, click View Nonprinting characters or press Control + F10. If you press Control + F10 several times in a row, you will notice how the nonprinting characters toggle on and off. Depending on the type of document you are creating, autocorrection can be a blessing or an annoyance. Tools AutoCorrect/AutoFormat . . . allows you to control the extent to which autoformatting and autocorrection are used in your documents. You can save documents created in Writer in many formats, such as OpenOffice text or template, Word 6.0, 95, or 97/2000/XP, StarWriter, Rich Text Format, and HTML.
You can turn the spell checker on and off by clicking the symbol that contains the letters ABC with a wavy line underneath. You can choose to see your spelling mistakes as you type or spell check later. You can insert tables by clicking Insert Table . . . or by clicking on the table icon near the top of the left window border. You can easily number the lines in your document and have control over the frequency with which lines are numbered. For example, you can number every fifth or tenth line in a document. Line numbering is selected through Tools Line Numbering.
Click Open.
297
ou can create spreadsheets using Open Office or import spreadsheets created by other popular spreadsheet applications. The spreadsheet that is included with Open Office is called Calc and, like Gnumeric, is likely to be familiar and, thus, easy to use if you have used any spreadsheet application. The labeling of the rows and columns and the symbols in the toolbars are generally self-explanatory and, if you pause over them with your cursor, a short description will appear to explain their functions.
As with other spreadsheets, you can enter data or formulas in cells and can copy and paste these items to avoid having to enter the same data more than once. Calc also includes graphing. If you select data and click the Insert Object icon, a short series of forms for creating a number of graphs, such as pie charts and scatter diagrams, will appear. Insert Graphics lets you import images into your spreadsheets. Like Gnumeric, Calc has one-click options for transforming the format of a cell to a percentage or monetary figure. Edit Repeat:Attributes is a very useful function that allows you to repeat changes that you make in one cell to others. If you change one cell to bold and then use this function, the new cell or group of cells will also take on the changed attribute.
To start Calc, click File New Spreadsheet from Writer. This will open an empty spreadsheet in another window on your screen. Clicking the Help button will bring up a useful guide on how to use Calc along with a panel in which you can enter or browse search terms, look through the contents of the Open Office documentation or create and use bookmarks.
CREATE SPREADSHEETS WITH OPEN OFFICE
File
Spreadsheet
33 12 4 28 2
298
17
Spreadsheets created in Calc can be stored in Open Office format or you can choose from other formats which include several versions of MicrosoftExcel, StarCalc, Data Interchange Format, dBASE, and SYLK. You can also create HTML documents in Open Office by clicking File New HTML Document. This tool will allow you to enter text and will provide the HTML code. You can insert links and create tables using options from the Insert menu. While you work with the context of the page, the HTML code is being constructed for you.
You can create a slide presentation by clicking File New Presentation from Writer or from Calc. The presentation package is called Impress and is a multimedia presentation tool that includes clip art, animation, and high-quality drawing tools. When you start Impress, you will complete a series of forms in which you make selections for your presentation such as whether to use wipes of some type as your slide show moves from one slide to the next. Impress simplifies preparation of a presentation and includes many features for creating a dynamic slide show.
Click Create.
299
ou can develop applications in C and C++ on your Mac OS X system. Developing applications in C or related languages, such as C++, depends largely on your ability as a programmer, although the Mac OS X environment offers excellent support for your development efforts. The gcc compiler that accompanies the Mac OS X developer tools is the default compiler for C, C++, Objective-C, and Objective-C++. Before you begin working in any of the programming languages available on Mac OS X, you should update your MANPATH to include /usr/share/man. This ensures that the man pages for the developer tools are available to you. If you type the line setenv MANPATH /sw/share/man:/usr/ local/man:/usr/share/man into your .tcshrc file, these and other pages appear when you use the man command.
them to properly indent source code. However, you should use the text editor that allows you to work most effectively. After typing your source code, you can compile it using gcc, or you can use the make command, which manages the compilation process. The make command only compiles a program if the associated binary code is older than the source code. In other words, it only recompiles your program if you have changed the source code. If your application consists of multiple source files, you must create a Makefile to describe the relationship between those files. make calls gcc to compile C programs. make works with many different programming languages, although it is most often used with C. In fact, make is not limited to compiling software. You can read the make man page to learn about this versatile command.
You should use the text editor to create your source code. Many developers prefer emacs because they can configure
DEVELOP C AND C++ APPLICATIONS
twice.
The include command adds the standard IO header file to your program.
Type main () { and press Return, then press the Tab key and type printf("Hello, World\n"); and press Return again. Type } and press Esc, then type :wq.
vi saves your source code.
300
18
Whenever you develop an application using multiple source files, you can build a Makefile to define the dependency relationships between files. If you have ever installed any applications from source code, you have probably used a Makefile to orchestrate the compilation process. With a simple program like hello.c, a Makefile is unnecessary. However, when you are compiling tools such as fetchmail, the Makefile ensures that you compile all of the proper files and that you create the final executable fetchmail. You can also write Makefiles to include installation and cleanup instructions. This allows the user to use the make install and make clean commands to install an application and remove object files. When you use a Makefile, you do not need to type commands such as make hello.c. The make command uses the Makefile in your current directory. With the following Makefile, you only need to type make to compile hello.c. Be careful to use tabs after the : and before gcc.
Example:
hello: hello.o gcc hello.o -o hello
Makefiles allow you to control the compilation and installation processes. If someone else is installing your application, you can give the installer the source files and a Makefile, to ensure their installation is successful.
301
ou can develop Java applications on your Mac OS X system. You run Java applications with the java interpreter, but you first compile them with a program called javac. Examination of the HelloWorld program below illustrates why you need a compiler to compile Java code into a special intermediate form called bytecode, and an interpreter to run the compiled code. The following lines of code represent the HelloWorld program written in Java. The single print command is similar to the printf command in C. The second line defines the main method and is the entry point for every Java application. In Java, each method or function exists within a class or an object, where an object is an instance of a class. Thus, you must enclose this simple program for printing a single line of text within a class definition. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
DEVELOP JAVA APPLICATIONS
You normally precede code like this with a line or two of comments. Java comments start with /* and end with */ and can span multiple lines. Single-line comments can start with // and need nothing else. Comments that start with /** are special comments, and a tool called javadoc which is intended to provide automated code documentation extracts the text from these comments. The javadoc command produces documentation for public classes. To compile the HelloWorld.java program, use the javac command. The command javac HelloWorld.java reads your source code and produces a class file, HelloWorld. class. You can then run this program with the command java HelloWorld. Java applications are often distributed as Java archive (JAR) files, and you can list the contents with the jar command.
302
18
You can create a Java archive from your HelloWorld application with the jar command. Syntactically, the jar command is like the tar command. To create a JAR file, you can use the jar cvf command. To extract from a JAR file, you can use the jar xvf command. To list the contents of a JAR file, you can use the jar tvf command. TYPE THIS:
[ferro:~] user% jar cvf HelloWorld.jar HelloWorld.class [ferro:~] user% jar tvf HelloWorld.jar
You can create a Web page containing the javadoc comments from your HelloWorld application by using the javadoc command. Javadoc comments provide easy to access documentation for Java programs and are generally considered essential to proper Java programming. These comments are especially critical when multiple programmers work on the same project. To view extracted javadoc comments, use the open command, as in open HelloWorld.html. This will open the javadoc Web page in a browser. TYPE THIS:
[ferro:~] user% javadoc HelloWorld.java [ferro:~] user% ls -l HelloWorld*
RESULT:
0 Thu May 29 21:18:32 EDT 2003 META-INF/ 67 Thu May 29 21:18:32 EDT 2003 META-INF/MANIFEST.MF 427 Thu May 29 20:57:50 EDT 2003 HelloWorld.class
RESULT:
-rw-rr 1 user staff 427 May 29 20:57 HelloWorld.class -rw-rr 1 user staff 6967 May 29 20:58 HelloWorld.html -rw-rr 1 user staff 754 May 29 21:18 HelloWorld.jar -rw-rr 1 user staff 181 May 29 20:57 HelloWorld.java
303
be transitional languages, because they allow you to write programs while you are only beginning to grasp the concepts of object-oriented programming. Languages like C and scripting languages like Perl are procedural languages. This means that portions of code are organized into functional elements called procedures or subroutines that you can use in the remainder of the code. Object-oriented languages work differently in that they define objects and then a set of operations that you can perform on these objects. You refer to these operations as methods. Where Perl prints to a file using a command such as print LOG "$num records processed";, Python uses a command such as out_file.write("Testing, testing, 1, 2, three\nThat's all folks\n"). While, on the surface, these commands may not seem very different, the implementation and coding method are radically different, and you encounter these differences as you write your own methods.
304
18
Type chmod a+x write2file and press Return. Type ./write2file and press
Return.
ou can quickly develop object-oriented applications in Ruby. Like Python, Ruby is an object-oriented scripting language that installs with the Mac OS X developer tools. In fact, there is considerable debate about which of the two is the better language. The interpreter is /usr/bin/ruby, and the syntax is relatively easy to use and, like Perl, extensible. The language is similar to SmallTalk, a programming language that is object-oriented. For example, in Ruby, you can use the command 3.times { print "Hello, World!" } to print "Hello, World!" three times in a row. Because the language has many built-in types, you can accomplish a lot with just a few lines of code. Some of these types include match and replace commands that are similar to commands that you use in Perl. For example, the
DEVELOP RUBY APPLICATIONS
command string.gsub!(/this/,"that") replaces this with that. If you do not find a built-in type that meets your needs, you can define your own using the def command. Because Ruby is interpreted, you can run scripts by using them as arguments to the interpreter such as ruby HelloWorld.rb or by including the shebang line in your script and making the script executable. The command ruby v tells you what version of Ruby you are using. Print commands in Ruby look much like print commands in Perl or C, but do not require the use of a semicolon at the end of the line. New lines are represented with \n. While file extensions are not critical on Unix systems, Ruby scripts are generally given the file extension .rb to indicate that they are Ruby programs.
Type ruby ./HelloWorld.rb and press Return. Type chmod a+x HelloWorld.rb and press
Return.
306
18
You can print a string in Ruby with or without a carriage return at the end, just as you can in Perl and Python. The syntax that each language uses is different, as shown in the comparison below. PERL
print "Hello World"; print "Hello World\n";
RUBY
print "Hello World" puts "Hello World"
PYTHON
print "Hello World", print "Hello World"
You can iterate through a sequence of values in Ruby by defining an iterate method such as that shown below. TYPE THIS:
def iterate(max) i = 0 while i < max yield i i += 1 end end iterate(5{|val| puts "#{val}: Hello World"}
RESULT:
0: 1: 2: 3: 4: Hello Hello Hello Hello Hello World World World World World
Type n * fact(n-1) and press Return, then type end and press Return, then type end again, and press Return. Type print
fact(ARGV[0].to_i), "\n".
307
ou can install and run a database on your Mac OS X system. In fact, you can choose between two free relational database packages MySQL and PostgreSQL. When you install PostgreSQL, you first download a gzipped TAR file and go through the steps of unzipping and untarring this file. You must read the INSTALL file that comes with the installation files before you run the configure command, as it contains many options that you can use to modify your installation. These options include the location where you want to install the software and whether you want to include readline support if you have already installed readline. You can then run the configure command with or without options, followed by the make command. The make install command installs the software on your system. By default, the software installs in the directory/usr/local/pgsql.
Installing the PostgreSQL software does not automatically enable you to start issuing SQL commands. You must follow a series of steps to create your database. The first thing you must do is to add a special database user to your system. For PostgreSQL, this user is usually called postgres. Your database software runs under this account. The next thing you must do is to log onto the postgres account and enter the initdb command to create a database. You must not use this command as root or with the sudo command. If you install into the default location, your binaries including initdb go into this /usr/local/pgsql/bin directory. You must therefore add this directory to your path so that you can easily invoke any of the PostgreSQL commands. After you run initdb from the postgres account, you can create tables, add data, and enter queries.
Type tar xf followed by the name of your TAR file, and press Return.
Your TAR file is extracted.
Type cd followed by the name of your install directory, and press Return.
308
18
To allow other users to use your new database software, you must enable them from the postgres account. Otherwise, the users will get an error of this type: psql: FATAL: user "kbartlett" does not exist. To enable a new user, use the su command to access the postgres account by typing su - postgres. Then connect to the database using the psql testdb command. After you establish the connection, add the user with a create user username; command, where you replace username with the username of the user you want to enable. After connecting to PostgreSQL to create tables or run queries, you need to disconnect from the database. To do this, type \q. This command returns you to your normal system prompt.
To add the man pages for your new database software to your search list, append /usr/local/pgsql/man to your MANPATH environment variable. This path may contain a number of directories separated by colons. The following example adds all the man directories shown to your search path for man pages.
Example:
setenv MANPATH /sw/share/man:/usr/local/ man:/usr/share/man:/usr/local/pgsql/man
CONTINUED
309
The basic query command is select. When you issue a query that selects phone from contacts, phone is a column in a table named contacts. If you select phone from contacts where areacode is equal to 415, you are listing your contacts in San Francisco. In this case, you are asking to view one particular column from particular rows in your table of contacts. While SQL, the standard language used for relational databases, is not exactly free-flowing English, it is still easy to use and understand. The command select phone from contacts where areacode=415; is about as close to flowing speech as computer syntax comes. SQL also allows you insert data into tables with insert, remove data from tables with delete, modify data in tables with update and sort data with order by.
Note: To complete step 7, you must have already created an adduser script. If not, see Chapter 11.
310
18
You can get help during your psql session by typing \?. When you enter this command, a list of slash commands, such as \l for creating a list of your databases, appears. You can use the \h command to get help on a particular command. For example, typing \h select describes the syntax and use of the select command. To exit your psql session, type \q. SQL syntax provided by the help function will display optional portions of a command inside square brackets. If you type \h modify, for example, you will notice that the word ONLY appears within square brackets [ ONLY ]. This part of the command is, therefore, optional. Similarly, [ WHERE condition ] means that you can optionally specify a condition, such as where areacode=415.
Type nohup /usr/local/ pgsql/bin/postmaster -D /usr/local/pgsql/data </dev/null >>server.log 2>&1 </dev/null &
and press Return.
311
ou can issue SQL commands to your PostgreSQL database. To use all of the features of your database software, you need to learn a number of SQL commands. In particular, you need to learn how to create tables, insert and remove records from these tables, and run queries to extract information from these tables. The command for creating a table is create table tablename. When you define a table, you need to specify the number of columns you want to add. For example, the SQL command for adding a book table to the database may look like this: create table books ( author title publisher pubyear ISBN ); varchar(32), varchar(64), varchar(16), int, varchar(13)
You define each column in the table as having a particular type. Most of these types are character fields of a specified length. After you define a table, you can add records to it. You can do this one record at a time, or you can bulk load a table from a flat text file. To add a single record, you can identify the table and the value you want to assign to each column in the new record. For example, you may say insert into books values('Paul Whitehead and Eric Kramer','Your visual blueprint for building Perl scripts','Wiley Publishing',2000,'0-7645-3478-5'); paying particular attention to the semicolon at the end. You can list the contents of the books table in its entirety with the command select * from books; or you can select some of the records by running a select command with a where clause. For example, to list the titles of the books in your table that were published in the year 2000, you can type select title from books where pubyear = 2000;.
Type psql testdb and press Return. Type create table pets (
and press Return.
Type name varchar(12), and press Return. Type type varchar(6), and
press Return.
312
18
You can enter the following to load the data into the database:
psql d testdb f /Users/user/pets.sql
To count the records in a table, you can use an SQL count command. TYPE THIS:
select count(*) from pets;
RESULT:
count -------3
313
ou can access data in your databases from PHP and include this information in your Web pages. While the setup required to provide information stored in a postgres database on a Web page is not intuitive, you can provide this functionality when you have the proper tools.
You need to install PostgreSQL on your server. You also need to use a Web server that supports PHP for example, an installation of Apache that supports PHP dynamically or statically. In addition, your PHP build must support PostgreSQL; that is, you must build it with the -withpgsql configuration parameter. Lastly, for a Web site to use PostgreSQL commands, the database must be running. When you are sure that you have these prerequisites, you can create a Web page that incorporates information from your database. The first step is to identify the database that you are using, as follows:
You can then open a connection to the database with a command such as $connect = pg_connect ("host= $host dbname=$db user=$user password=$pass password=$pass");. You can then determine if your connection is successful by testing the $connect value. Next, you can create the query that you want to run for example, $query = "select * from pets"; and execute that query with a command such as $result = pg_query($connect, $query) or die("Query failed: $query");. If your query is successful, the command stores the data that you just fetched in $result. You can now decide how to process and display the data that the command returns from the database.
Start the Pico editor to create a file named /sw/apache/htdocs/testpg.php and press Return.
The Pico screen appears.
Return.
Return.
314
18
Type if (!$connect) { die("could not open a connection to db server"); } and press Return.
Type pg_close($connect); and press Return, then type ?> and press Return.
315
APPENDIX
different versions of the same program, contact the program's manufacturer. For the latest and greatest information, please refer to the ReadMe file located at the root level of the CD-ROM as well as the manufacturer's Web site.
SYSTEM REQUIREMENTS
To use the contents of the CD-ROM, your computer must have the following hardware and software: For Macintosh: Mac OS X v.10.2 or higher with a 400 MHz or faster CPU At least 256MB of total RAM installed on your computer; for best performance, we recommend at least 512MB A network card A CD-ROM drive
Chimera
For Mac OS X. Freeware/Open Source. Chimera is a browser for Jaguar, Mac OS X v.10.2. From The Mozilla Organization, www.mozilla.org/projects/chimera.
Fink
For Mac OS X. Freeware/Open Source. Fink enables Mac OS X to import and fix open source Unix software. From The Fink Project, http://fink.sourceforge.net.
GIMP
For Unix, Mac OS X, and Windows. GNU Freeware/Open Source and Binary. Requires X Windows. The GIMP is the GNU Image Manipulation Program for photo retouching, image composition, and image authoring. From GNOME, www.gimp.org.
ACROBAT VERSION
The CD-ROM contains an e-version of this book that you can view and search using Adobe Acrobat Reader. You cannot print the pages or copy text from the Acrobat files. The CD-ROM includes an evaluation version of Adobe Acrobat Reader.
GNOME Core
For Unix and Linux. Freeware/Open Source. Requires X Windows. GNOME Core contains the core components needed to run the GNOME desktop environment. From GNOME, www.gnome.org.
GnuCash
For Mac OS X and Linux. GNU Freeware/Open Source. GnuCash is a finance software that enables you to manage your bank accounts, stocks, income, and expenses, and more. From The GnuCash Project, www.gnucash.org.
AbiWord
For Unix, Linux, and Windows. GNU Freeware/Open Source. Requires X Windows. AbiWord is a cross-platform word-processing program that enables you to perform the same task as Microsoft Word. From AbiSource c/o SourceGear Corporation, www.abisource.com.
KDEbase
For Unix, Linux, and Solaris. Freeware/Open Source. Requires X Windows. KDEbase contains the basic applications that are used with the KDE desktop environment. From The KDE Project, www.kde.org.
Acrobat Reader
For Macintosh and Windows. Freeware. Adobe Acrobat Reader allows you to view the online version of this book. For more information on using Acrobat Reader, see the section "Using the E-Version of the Book" in this Appendix. From Adobe Systems, www.adobe.com.
KDElibs
For Unix systems. Freeware/Open Source. Requires X Windows. KDElibs contains libraries needed by the K Desktop Environment. From The KDE Project, www.kde.org.
316
Lynx
For Unix, VMS, Windows 95 and higher. GNU Freeware/Open Source and Binary. Lynx is a text-based Internet Web browser originally developed at the University of Kansas. http://lynx.browser.org.
TROUBLESHOOTING
The programs on the CD-ROM should work on computers with the minimum of system requirements. However, some programs may not work properly. Many of the tools on the CD require that you first install an X Windows server, such as the XFree86 software included on the CD. The two most likely problems for the programs not working properly include not having enough memory (RAM) for the programs you want to use, or having other programs running that affect the installation or running of a program. If you receive error messages such as Not enough memory or Setup cannot continue, try one or more of the methods below and then try using the software again: Turn off any anti-virus software Close all running programs Have your local computer store add more RAM to your computer Mac OS X requires more memory than previous versions of Mac OS. For acceptable performance, you should run at least 256MB of RAM. Execution of programs that you install may depend on having the proper environment. Your search path should include the directory in which your software has been installed, for example, /sw/bin or /usr/local/bin. You may also have to adjust your dynamic library search path to enable these applications to find and use the runtime libraries they need. The environment variable DYLD_LIBRARY_PATH may have to be updated to include directories such as /sw/lib or /usr/local/lib. In addition, any application that is not installed with an installer program will open slowly the first time it is run. This is normal. If you still have trouble installing the items from the CD-ROM, call the Wiley Publishing Customer Service phone number: 800-762-2974 (outside the U.S.: 317-572-3994). You can also contact Wiley Publishing Customer Service by e-mail at techsupdum@wiley.com.
Mozilla
For Unix and Linux systems. Freeware/Open Source. Mozilla is an open-source Web browser and toolkit. From The Mozilla Organization, www.mozilla.org.
OpenOffice.org
For all platforms. Freeware/Open Source. Requires X Windows. OpenOffice.org is an office suite that will run on all major platforms. From OpenOffice.org, www.openoffice.org.
PostgreSQL
For Unix and Linux systems. Freeware/Open Source. An advanced object-relational database management system (ORDBMS) with utilities needed to create and maintain the database server. From PostgreSQL, www.postgresql.org.
Screen
For Unix. GNU Freeware/Open Source. Screen is a utility that allows you to have multiple logon screens in a single terminal. From The GNU Project, www.gnu.org.
Vim
For Unix, Linux, and Mac OS X. Freeware/Open Source. vim (VIsual editor iMproved) is an enhanced text editor. From The VIM Group, www.vim.org.
XFree86
For Unix, Linux, Solaris, Mac OS X. Freeware/Open Source. XFree86 is an X Windows server. It provides a client/server interface between display hardware and the desktop environment, while providing both the windowing infrastructure and a standardized application interface. From The XFree86 Project, Inc, www.xfree86.org. For Mac OS X ports, go to sourceforge.netprojectsXonX.
Xmms
For Unix systems. Freeware/Open Source. X MultiMedia System (Xmms) is a multimedia player that supports MPEG,
317
APPENDIX
ou can view Unix for Mac: Your visual blueprint to maximizing the foundation of Mac OS X on your screen using the CD-ROM included at the back of this book. The CD-ROM allows you to search the contents of each chapter of the book for a specific word or phrase. The CD-ROM also provides a convenient way of keeping the book handy while traveling. You must install Adobe Acrobat Reader on your computer before you can view the book on the CD-ROM. This program is provided on the disc. Acrobat Reader allows you to view Portable Document Format (PDF) files, which can display books and magazines on your screen exactly as they appear in printed form.
To view the contents of the book using Acrobat Reader, insert the CD-ROM into your drive. The autorun interface will appear. Navigate to the eBook, and open the book.pdf file. You may be required to install Acrobat Reader 5.0 on your computer, which you can do by following the simple intallation instructions. If you choose to disable the autorun interface, you can open the CD root menu and open the Resources folder, then open the eBook folder. In the window that appears, double-click the eBook.pdf icon.
ZOOM IN
Click
318
To install Acrobat Reader, insert the CD-ROM disc into a drive. In the screen that appears, click Software. Click Acrobat Reader and then click Install at the bottom of the screen. Then follow the instructions on your screen to install the program. You can make searching the book more convenient by copying the .pdf files to your own computer. Display the contents of the CD-ROM disc and then copy the PDFs folder from the CD to your hard drive. This allows you to easily access the contents of the book at any time.
Acrobat Reader is a popular and useful program. There are many files available on the Web that are designed to be viewed using Acrobat Reader. Look for files with the .pdf extension. For more information about Acrobat Reader, visit the Web site at www.adobe.com/products/ acrobat/readermain.html.
prefix
FIND TEXT
Click
appears.
319
APPENDIX
WILEY PUBLISHING, INC. END-USER LICENSE AGREEMENT
READ THIS. You should carefully read these terms and conditions before opening the software packet(s) included with this book Unix for Mac: Your visual blueprint to maximizing the foundations of Mac OS X. This is a license agreement "Agreement" between you and Wiley Publishing, Inc. "WPI". By opening the accompanying software packet(s), you acknowledge that you have read and accept the following terms and conditions. If you do not agree and do not want to be bound by such terms and conditions, promptly return the Book and the unopened software packet(s) to the place you obtained them for a full refund. 3. Restrictions on Use and Transfer.
(a) You may only (i) make one copy of the Software for backup or archival purposes, or (ii) transfer the Software to a single hard disk, provided that you keep the original for backup or archival purposes. You may not (i) rent or lease the Software, (ii) copy or reproduce the Software through a LAN or other network system or through any computer subscriber system or bulletin-board system, or (iii) modify, adapt, or create derivative works based on the Software. (b) You may not reverse engineer, decompile, or disassemble the Software. You may transfer the Software and user documentation on a permanent basis, provided that the transferee agrees to accept the terms and conditions of this Agreement and you retain no copies. If the Software is an update or has been updated, any transfer must include the most recent update and all prior versions.
1. License Grant.
WPI grants to you (either an individual or entity) a nonexclusive license to use one copy of the enclosed software program(s) (collectively, the "Software," solely for your own personal or business purposes on a single computer (whether a standard computer or a workstation component of a multi-user network). The Software is in use on a computer when it is loaded into temporary memory (RAM) or installed into permanent memory (hard disk, CD-ROM, or other storage device). WPI reserves all rights not expressly granted herein.
2. Ownership.
WPI is the owner of all right, title, and interest, including copyright, in and to the compilation of the Software recorded on the disk(s) or CD-ROM "Software Media". Copyright to the individual programs recorded on the Software Media is owned by the author or other authorized copyright owner of each program. Ownership of the Software and all proprietary rights relating thereto remain with WPI and its licensers.
(a) WPI warrants that the Software and Software Media are free from defects in materials and workmanship under normal use for a period of sixty (60) days from the date of
320
purchase of this Book. If WPI receives notification within the warranty period of defects in materials or workmanship, WPI will replace the defective Software Media. (b) WPI AND THE AUTHOR OF THE BOOK DISCLAIM ALL OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THE SOFTWARE, THE PROGRAMS, THE SOURCE CODE CONTAINED THEREIN, AND/OR THE TECHNIQUES DESCRIBED IN THIS BOOK. WPI DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE SOFTWARE WILL MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE SOFTWARE WILL BE ERROR FREE.
(c) Because some jurisdictions do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation or exclusion may not apply to you.
(c) This limited warranty gives you specific legal rights, and
you may have other rights that vary from jurisdiction to jurisdiction. 6. Remedies.
8. General.
This Agreement constitutes the entire understanding of the parties and revokes and supersedes all prior agreements, oral or written, between them and may not be modified or amended except in a writing signed by both parties hereto that specifically refers to this Agreement. This Agreement shall take precedence over any other documents that may be in conflict herewith. If any one or more provisions contained in this Agreement are held by any court or tribunal to be invalid, illegal, or otherwise unenforceable, each and every other provision shall remain in full force and effect.
(a) WPI's entire liability and your exclusive remedy for defects in materials and workmanship shall be limited to replacement of the Software Media, which may be returned to WPI with a copy of your receipt at the following address: Software Media Fulfillment Department, Attn.: Unix for Mac: Your visual blueprint to maximizing the foundation of Mac OS X, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, or call 1-800-762-2974. Please allow four to six weeks for delivery. This Limited Warranty is void if failure of the Software Media has resulted from accident, abuse, or misapplication. Any replacement Software Media will be warranted for the remainder of the original warranty period or thirty (30) days, whichever is longer. (b) In no event shall WPI or the author be liable for any damages whatsoever (including without limitation damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising from the use of or inability to use the Book or the Software, even if WPI has been advised of the possibility of such damages.
321
APPENDIX
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991 Copyright 1989, 1991 Free Software Foundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Also, for each authors protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow.
PREAMBLE
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free softwareto make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
1.
You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and
322
disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2.
You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: (a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. (b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. (c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
3.
You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: (a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, (b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, (c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
323
APPENDIX
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
7.
4.
You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5.
You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6.
Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8.
If the distribution and/or use of the Program is restricted in certain countries either by patents or by
324
copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF
CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
9.
The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
325
INDEX
Symbols
* (asterisk), 16, 26, 47 \ (backslash), 10 ` (backtick), 51, 115 {} (braces), 116 ^ (caret), 26, 40, 47 : (colon), 72 $ (dollar sign), 47 . (dot) alias, 21 .. (dot-dot) alias, 21 -- (double dash), 23 = (equal symbol), 24 ! (exclamation point), 74, 90 / (forward slash), 16 - (minus symbol), 24 . (period), 47 | (pipe), 50 + (plus symbol), 24, 47 # (pound sign), 109 ? (question mark), 26, 47 ; (semicolon), 114 [] (square brackets), 47 ~ (tilde) alias, 21 directives, 232233 document directory, 234 install, 244245 server, 232233 Apache Web server about, 228229 configuration, 229 start, 230 stop, 231 append to path, 88 Apple resource forks, 128129 Applescript, 130131, 131 applications install, 190191 run from Terminal application, 15 Aqua applications open from shell, 122123 clipboard, 126127 interface, 3 arguments in command line, 10 escape, 10 as command, 184 asterisk (*), 16, 26, 47 Authenticate dialog box, 181 autocorrect variable, 85 autoindent option, vi, 65 autologout variable, 85 awk command, 116117
A
a, 24 -A option, 17 AbiWord, 292293, 316 access privileges, 154 Accounts tool, 158 Adobe Acrobat Reader, 124, 316 Advanced Package Tool, 198 AIM (AOL Instant Messenger), 210 alias command, 8283 alias dot (.), 21 alias dot-dot (..), 21 aliases delete, 83 special pathnames, 21 Analog, 248249 analyze Web traffic, 248249 anonymous ftp, 146147 AOL Instant Messenger (AIM), 210 Apache compile, 196197 configure, 232233
B
back up files, 164165 background (bg) command, 101 backslash (/), 10 backtick (`), 51, 115 bash, 92 Bell Labs, AT&T, 2 Berkeley Software Distribution (BSD), 2 binary files about, 147 download, 151 view, 40 block directives, 232 Bourne, Steven, 94 Bourne-again shell, 92, 94 braces ({}), 116 BSD Unix system, 2, 3 built-in commands, 11 builtins command, 11
326
C
C applications development, 300301 C++ applications development, 300301 -C2 options, 10 Calc, 298 capture screenshots, 124125 caret (^), 26, 40, 47 cat command, 40, 41, 4849 cd command, 10, 3031 CD-ROM, 316317 CGI (Common Gateway Interface), 242243 CGI script, 266267 chain text commands together, 5051 change shell, 93 character count in text, 54 characters value, 54 charsc command, 29 chat, Internet Relay Chat (IRC), 212213 chgrp command, 166 Chimera, 316 chmod command, 2425, 110111 chomp command, 257 chown command, 166 chpass command, 93 clickable shell scripts, 132 clients, X Window System, 268 clipboard, 126 Close button, 14 close command, 261 Close Window, 14 colon (:) vi, 72 Color settings, 7 column command, 55 columns, 55 command line arguments in command line, 10 Perl scripts on, 256257 command mode, vi, 66 command output to clipboard, 126 .command suffix, 132 comments for command and scripts, 109 Common Gateway Interface (CGI), 242243 compare text files, 5253 compile Apache, 196197 program with make command, 194195 complete variable, 85
compress command, 176177 compress files, 176177 concatenate, 40 conditional logic, 114 conditional shell scripts, 114115 configure Apache, 232233 Apache Web server, 229 DontBlameSendmail, 216217 sendmail, 214215 Terminal, emacs, 79 Terminal application, 67 configure command, 195, 308 connect to Internet, 134135 console.log, 174 Control+D keys, 27 copy Apple resource forks, 128129 command output to clipboard, 126 directory, 37, 129 files, 20, 128 text file to clipboard, 126 Web page, 150 copy command, 126 cp command, 20, 37, 128 CpMac command, 129 create table command, 312 cron command, 120121 crontab -e command, 120 crontab files, 120 crop images, 290 crossword puzzles, grep command for, 46 .css file extension, 74 curl command, 150151 custom permissions, set, 25 cut-and-paste, vi, 73 CVS, 184
D
Darwin, 3 databases access databases from PHP, 314315 run, 308311 date command, 100 days, find files by, 29 Debian, 198 default prompt, 80
327
INDEX
delete aliases, 83 applications run form Terminal application, 15 directory, 3435 files, 23 text in vi, 7071 designate files by pathname, 21 Developer Tools CD, 180 directory, 182183 Easy Install screen, 183 df command, 39, 170171 DHCP (Dynamic Host Configuration Protocol), 134 dial-up Internet, 134135 diff command, 5253 diff3 command, 5253 digital subscriber line (DSL) Internet connection, 134 directives, Apache, 232233 directory change, 3031 copy, 37, 129 create, 3233 size, 3839 disk free space, 170 disk usage check, 170171 Display settings, 7 ditto -rsrcFork command, 129 ditto command, 128129 DNS mail exchanger (MX) record, 138 DNS records, 139 .doc files, 293 document directory, Apache, 234 DocumentIndex directive, 232 DocumentRoot directive, 232 documents, Open Office, 296297 dollar sign ($), 47 domain information look up, 138139 Domain Name System (DNS), 134, 136137 dot (.) alias, 21 dot-dot (..) alias, 21 DotBlue.tif, 185 DotGray.tif, 185 double dash (--), 23 download binary files, 151 Web files, 150151 Web sites with Wget, 209 drag pathnames to Terminal window, 133 DSL (digital subscriber line) Internet connection, 134 du command, 3839, 57, 170 dump command, 164165 dunique variable, 85 duplicate items, eliminate, 57 dyld, 184 Dynamic Host Configuration Protocol (DHCP), 134
E
e-mail from other servers, 221 Pine, 224225 send, 218219 e-version of book, 318319 Easy Install screen, Developer Tools, 183 ed command, 53 edit file, emacs, 7879 file, Pico, 6263 file, vi, 64 images, GIMP, 288291 screenshot, 125 .tcshrc file, 89 text, vi, 7273 eliminate duplicate items, 57 emacs edit file, 7879 exit, 78 tutorial, 78 Emulation settings, 7 encryption, 148 enscript command, 58 environment variables set, 8687 equal symbol (=), 24 error correction correct mistake in last command, 91 shell commands, 9 escaping arguments, 10 exclamation point (!), 74, 90 executable files, 11 execute commands as root, 162163 execution permissions, set, 25 exit emacs, 78 shell, 92 exit command, 14
328
export command, 94 .exrc file extension, 75 extract information, awk command, 116117 extract text from files, 4647
F
-F option, 16, 17 -f option, 5657, 62 fetchmail tool, 221 fi, 114 fields, 116 file attributes, 1819 file mode, 19 file permissions, 2425 filemode, 29 filename, 29 files binary files, 40 compress, 176177 copy, 20, 128 delete, 23 designate by pathname, 21 edit, Pico, 6263 edit file in vi, 64 executable, 11 find by arguments, 29 find by name, 2829 move into directory, 36 number directory count, 54 ownership change, 166167 rename, 22 selection, completion, 27 selection with wildcard characters, 26 structure, 16 text, 40 vi, 65 fill columns, 55 find by name, 2829 text, Pico, 62 text, vi, 67 find and replace text in vi, 72 find command, 28, 66, 96, 100 Finder, 4 Fink about, 186, 189, 316 install, 198
install wget, 208 list, 198 selfupdate, 199 FinkCommander, 200201 folders, 16 foreach command, 112113 foreach number command, 112 foregound processing, 100 foreground (fg) command, 98 forward slash (/), 16 -fr option, 35 Free BSD, 2 free operating systems, 2 Free Software Foundation, 2 ftp command, 134, 146147, 152 full pathnames, 21 function keys, Pico, 62
G
g, 24 gcc 3.1 compiler, 181 GET command, 229 GIMP, 288291, 316 glob, 26 glob-patterns, 26 GNOME Core, 316 GNOME desktop about, 280281 applications, 282283 GNU general public license, 322325 GNU Image Manipulation Program (GIMP), 288289 GNU project, 2 GNU public license, 188 GnuCash, 316 Gnumeric spreadsheets, 294295 graphical user interface systems, 3 greater than symbol, 52 grep -l command, 47 grep -v command, 47 grep command, 10, 4647, 48 -group argument, 29 group of file change, 166167 groupname find files by, 29 gunzip, 176177 gzip command, 176177
329
INDEX
H
halt command, 156157 hang up, 103 hard link, 168169 head command, 4445, 48 hidden files, 26, 35 history codes, 91 history command, 90, 92 history variable, 85 .html file extension, 74 HTML files, 122 HTML markup code, 236237 httpd command, 152 Interactivity, web site, 242243 Internet address, 136137 dial-up Internet, 134135 digital subscriber line (DSL) Internet connection, 134 Internet Control Message Protocol (ICMP), 142 Internet Relay Chat (IRC) chat, 212213 Internet Service Provider (ISP), 135 intervening directories, 33 IP address, 135, 136137 iused, 171
J
Jaguar Terminal application, Mac OS X 10.2, 5 jar command, 302303 Java applications, 302303 Java archive (JAR) files, 302 jobs command, 9899 join text, vi, 73 .jpg file extension, 122
I
-i option, 10, 36 if command, 114 ifconfig command, 140 ifree, 171 image crop, 290 edit images, GIMP, 288291 files open, 122 -iname argument, 29 incremental backup, 164 init process, 102 inodes, 171 input mode, vi, 66 insert command, 313 Insert mode, vi, 69 insert text, emacs, 77 install Apache modules, 244245 application packages, 190191 developer tools, 180185 Internet Relay Chat (IRC) client, 210211 libraries, 202203 Lynx Web browser, 204205 OroborOSX, 284285 Perl modules, 262265 pine, 222223 tar archives, 192193 Wget, 208 X server, 274275 XFree86 upgrades, 276277 install command, 190191
K
-k option, 39 KDEbase, 316 KDElibs, 316 Keep in Dock, 4, 5 keystroke commands delete text in vi, 71 emacs, 77, 79 Insert mode, vi, 69 to move through files, 43 Pico, 61 keyword search manual, 13 kill command, 102103 kill process by job number, 102 by name, 103 by process ID, 102 killall command, 102
L
-l option, 18 LAN (local area network) connection, 134 ld, 184 less command, 4243, 51 less than symbol, 52
330
libraries list, 203 Library directory, 17 libtool, 184 lines, and words in text, 54 Linux, 2 list active processes, 104105 aliases, 83 current shell variables, 84 files, 16 option, vi, 65 LoadModule command, 244 local area network (LAN) connection, 134 log files, 45 log on to remote system, 144145 logoff command, 144 logout command, 145 loopback address, 140 looping shell scripts, 112113 lpq command, 172173 lpr command, 5859, 172173 ls command, 10, 16, 17, 108 Lynx, 206207, 317
modes, 66 monitor top processes, 106107 mouse use, emacs, 78 move files into directory, 36 text, Pico, 63 in vi, 6667 Mozilla, 186, 317 -mtime argument, 29 multiple files, move, 36 multiprocess, 97 mv command, 22, 36 MyMac command, 129 MySQL, 308
N
-n option, 5657 name Terminal application, 6 Net BSD, 2 NetInfo database, 93, 160, 178179 netstat command, 140141 network connection view, 140141 Network Information Center (NIC) database, 138 new user creation, 158159 NF variable, 116 nidump command, 158159, 178179 niload command, 158, 178179 niutil command, 158159, 178179 nobeep variable, 85 noclobber variable, 85 non-empty directory, delete, 34 non-text binary file, 58 NR variable, 116 nslookup command, 136137, 138 number option, vi, 65
M
M- (Meta) characters, 40 Mac OS X, 2, 3 Mac OS X 10.2, Jaguar Terminal application, 5 magnifying glass, 291 mail command, 218219 mail inbox, 220 mailto command, 123 make clean command, 195 make command, 196197, 300301 make install command, 195 man -k command, 13 man command, 1213, 4243 man enscript command, 59 manage software installation with Fink, 198199 manual access, 1213 match patterns with grep, 51 metacharacters, 254255 metadata, 122 Microsoft Word, 122, 293 minutes, find files by, 29 mkdir command, 3233 -mmin argument, 29
O
-o option, 59 object-oriented programming, 304 open file with emacs, 7677 file with Pico, 6061 file with vi editor, 6465 new line of text, 69 from shell, Aqua applications, 122123 Open BSD, 2 open command, 122123
331
INDEX
Open Office documents, 296297 spreadsheets, 298299 Open Scripting Architecture (OSA) standard, 130 open source code, 2 Open Source Initiative (OSI), 189 Open Source software, 188, 189 OpenOffice, 186 OpenOffice.org, 317 options after command name, 10 OroborOSX, 284285 osascript command, 130 Pico edit files with, 6263 enter text, 61 keystrokes, 61 Pine install, 222223 send e-mail, 226227 .pinerc file, 223 ping command, 142143 pipe (|), 50 piping, 50, 127 .plist file extension, 74 POP3 protocol, 145 popd command, 31 ports, 141 POST command, 229 PostgreSQL, 308311, 317 PostScript printer, 58 pragma, 265 Preview, 122 -print argument, 28, 29 Print Center, 173 print command, 58, 302 print file on line printer, 58 print file on postscript printer, 59 print queue, 172173 print text on printer, 5859 print underlay, 59 printenv command, 86 printf command, 302 process, 96 process run in background, 100101 Processes settings, 7 prompt format codes, 81 format sequence, 80 set, 8081 prompt2 set, 80 ps -a command, 104105 ps -aux command, 104105 ps -u command, 104105 ps -x command, 104105 ps command, 104105 pushd command, 31 pwd command, 10, 3031 Python applications, 304305, 307
P
p command, vi, 73 package command, 263 pager command, 4243 paste buffer, Aqua, 126 paste buffer, vi, 73 paste clipboard in text file, 127 paste clipboard to standard output, 127 PATH environment variable, 88 path on hard drive, 11 path set, 88 path value, 88 path variable, 85 pathname designate files by, 21 drag to Terminal window, 133 patterns in Perl, 254255 pbcopy command, 126 pbpaste command, 126 .pdf file extension, 124 Perl about, 242243, 307 install modules, 262265 patterns, 254255 script run, 252253 scripts on command line, 256257 write script, 250251 -perm argument, 29 permissions, set, 25 Photoshop, 122 PHP about, 186 access databases, 314315 applications, 246247
332
Q
question mark (?) wildcard, 26, 47 quit command, 74 quit Pico, 63 quotations marks in command line, 10
S
save file different name, vi, 74 emacs, 78 and exit vi, 75 Pico, 63 sorted text, 57 vi, 7475 Window settings, 6 schedule scripts to run automatically, 120121 Screen, 317 screencapture command, 124125 screenshot capture, 124125 edit, 125 scroll bars, Terminal application, 5 search for text in files with grep command, 10 second prompt, 80 section of screen capture, 124125 sed command, 118119 selection of files with completion, 27 send e-mail, 218219 e-mail Pine, 226227 sendmail, configure, 214215 sequential commands run, 96 server Apache, 232233 X Window System, 268 set autolist command, 27 prompt, 8081 value of shell, 85 Window Title, 6 set command, 9, 8283, 84 set environment variable, 94 set noclobber command, 49 setenv command, 86 setopt command, 95 sftp command, 148149 shebang line, 253
R
-R option, 37 -r option, 35 read access, file, 24 read files, Perl, 258259 reboot command, 156157 recall command history, 9091 shell commands, 8 redirect text to file, 4849 regexps, 46 regular expressions, 46 relative pathnames, 21 remote access enable, 152153 remote system reachable, 142143 secure access, 148149 rename files, 22 repeat last command, 90 reply to e-mail, Pine, 225 resource forks, 128129 restart computer, 156157 restart process, 9899 restore command, 165 rlogin command, 15, 144145 rm command, 10, 23, 82 rmdir command, 23, 3435 root account, 157 root user account enable, 160161 rootless mode, start XFree86, 278279 .rtf files, 293 Ruby applications, 306307 ruler option, vi, 65 run from Terminal application, 15 rw-, 19
333
INDEX
shell prompt, 4 settings, 7 talk, 130 variables set, 8485 shell commands about, 3, 1011 enter, 89 error correction, 9 Terminal application and, 4 use, 11 shell scripts clickable, 132 conditional, 114115 extend with sed command, 118119 run, 110111 write, 108109 show file attributes, 1819 hidden files, 17 showmode option, vi, 65, 68 shut down computer, 156157 shutdown command, 156157 SIGHUP, 103 SIGKILL, 103 signals, 103 SIGTERM, 103 simple directives, 232 size, directory, 3839 -size argument, 29 slogin command, 15 SmallTalk, 306 "sniffing" packets, 148 SOA (statement of authority) record, 138 Software License Agreement, Developer Tools, 182 sort command, 5657 sort text, 5657 source code, 2 source command, 110111 split windows, Terminal application, 5 spreadsheets Gnumeric, 294295 Open Office, 298299 SQL commands, 312313 ssh command, 15, 142 ssh log on, 148 standard output, 48 start Apache Web server, 230 bash from tcsh, 94 start command, 231 start new shell, 92 start zsh from tcsh, 95 stat command, 145 statement of authority (SOA) record, 138 stop Apache Web server, 231 stop command, 231 stop shutdown, 157 stopped job, 96 stopped process, 102103 styles, add to Web site, 240241 subnet mask, 136137 sudo command, 93, 153, 157, 162163 sudoers file, 162 suspend current process, 9697 symbolic links, 168169 system administration, 154155 system administrator, 154 system logs inspection, 174175 system.log file, 175
T
tail command, 4445 tar command, 164, 192193 .tar files, 177 .tar.Z files, 177 TCP/IP (Transmission Control Protocol/Internet Protocol), 134 TCP protocol, 141 tcsh shell, 92, 115 .tcshrc file, 89 telnet command, 15, 134, 142, 144145, 152 TERM file, 6, 7 Terminal application about, 3 configure, 67, 79 start, 45 Unix shells run in, 4 windows run at same time, 4 Terminal Inspector panel, 6 Terminal window change appearance, 6 exit, 1415 launch, 4
334
text chain commands together, 5051 in columns, 55 delete, 7071 edit, 7273 enter in vi, 6869 extract from files, 4647 text editors, 60 text files compare, 5253 copy to clipboard, 126 create, 41 open in TextEdit, 123 view, 40 TextEdit, 122 .tgz files, 177 then, 114 tilde (~) alias, 21 top command, 14, 106107 traceroute command, 142143 transfer files, 146147 Transmission Control Protocol/Internet Protocol (TCP/IP), 134 true condition, 112 .txt file extension, 74
vi edit file, 64 editor options, 65 keystroke options, 67 text editor, 60 view binary files, 40 images, xv, 286287 portions of text files, 4445 text files, 40 text files as pages, 4243 Vim, 317 visiblebell variable, 85 visual editor, 6465
W
wc command, 54 Web browse Lynx, 206207 Web files download, 150151 Web forms, CGI script, 267 Web page copy, 150 structured, 238239 Web server creation, 152153 Web site add styles, 240241 create, 235 Darwin source code, 3 interactivity, 242243 open source software, 189 with Wget, 209 Web traffic analyze, 248249 Wget, 208209 which command, 11 while command, 112113 whois command, 138 wildcard characters, 26 Wiley Publishing end-user license agreement, 320321 Window Settings Panel, 6 word count command, 54 word processing, 292293 words search for in files, 43 in text count, 54 write access, file, 24 write files, Perl, 260261
U
u, 24 uncompress command, 177 uniq command, 5657 University of California, Berkeley, 2 Unix applications on Web, 186187 UNIX history, 2 Unix manual, 1213 unlink command, 261 unset autolist command, 27 unset shell variable, 85 unsetenv command, 86 uptime command, 107 Utilities folder, Applications folder, 4, 5
V
-v option, 40 value of environment variable, 87 verbose option, vi, 65
335
INDEX
X
X11, 268 X client, 268 X server, 3, 268, 274275 X Window System about, 3 clients, 268 desktop, 269 display, 269 full screen, 268 history, 269 servers and clients, 268 software, 270273 version, 268 XDarwin, 268 XFree86 about, 186, 273, 317 install upgrades, 276277 rootless mode, 278279 xhost command, 269 Xmms, 317 XTools, 268 xv, view images, 286287
Z
Z shell, 92, 95 .zip files, 177 zsh, 92
336
337
For experienced computer users, developers, and network professionals who learn best visually.
Title
Price
$26.99 $26.99 $26.99 $26.99 $26.99 $26.99 $26.99 $26.99 $26.99 $26.99 $26.99 $29.99 $26.99 $26.99 $29.99 $26.99 $26.99 $26.99 $26.99
Active Ser ver Pages 3.0: Your visual blueprint for developing interactive Web sites ASP.NET: Your visual blueprint for creating Web applications on the .NET Framework C#: Your visual blueprint for building .NET applications Excel Programming: Your visual blueprint for building interactive spreadsheets Flash ActionScript: Your visual blueprint for creating Flash-enhanced Web sites HTML: Your visual blueprint for designing effective Web pages Java: Your visual blueprint for building portable Java programs Java and XML: Your visual blueprint for creating Java-enhanced Web programs JavaScript: Your visual blueprint for building dynamic Web pages JavaSer ver Pages: Your visual blueprint for designing dynamic content with JSP Linux: Your visual blueprint to the Linux platform MySQL: Your visual blueprint to open source database management Perl: Your visual blueprint for building Perl scripts PHP: Your visual blueprint for creating open source, ser ver-side content Red Hat Linux 8: Your visual blueprint to an open source operating system Unix: Your visual blueprint to the universe of Unix Visual Basic .NET: Your visual blueprint for building versatile programs on the .NET Framework Visual C++ .NET: Your visual blueprint for programming on the .NET platform XML: Your visual blueprint for building expert Web pages
Nov 02
ISBN
0-7645-3425-4 0-7645-6048-4 0-7645-6050-6 0-7645-6046-8 0-7645-6036-0 0-7645-6045-X 0-7645-3436-X 0-7645-3668-0 0-7645-0855-5 0-7645-3696-6 0-7645-3580-3 0-7645-3454-8 0-7645-3599-4 0-7645-3541-2 0-7645-3610-9 0-7645-3426-2 0-7645-3496-3 0-7645-3621-4 0-7645-6024-7 0-7645-6034-4 0-7645-3421-1
want an all-in-one reference/tutorial that delivers more in-depth information about a technology topic.
1-800-762-2974.
Outside the US, call
317-572-3993
Welcome to the only guidebook series that takes a visual approach to professional-level computer topics. Open the book and youll discover step-by-step screen shots that demonstrate over 160 key Unix tasks you can do on Mac OS X, including:
Using the terminal application Navigating the file system Working with pico, vi, and emacs
text editors
Customizing the shell Writing shell scripts Sharing files between computers
*85 5 -IGFG c
ISBN 0-7645-3730-X
www.wiley.com/compbooks
,!7IA7G4-fdhdab!:p;m;Q;t;T