BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Learning Unix for Mac OS X
Learning Unix for Mac OS X By Dave Taylor, Jerry Peek
May 2002
Pages: 156

Cover | Table of Contents


Table of Contents

Chapter 1: Getting Started
With a typical Unix system, a staff person has to set up a Unix account for you before you can use it. With Mac OS X, however, every install automatically creates a default user account. The account is identified by your username , which is usually a single word or an abbreviation. Think of this account as your office—it's your personal place in the Unix environment.
When you log in to your OS X system, you're automatically logged into your Unix account as well. In fact, your Desktop and other customized features of your OS X environment have corresponding features in the Unix environment. Your files and programs can be accessed either through the Mac Finder or through a variety of Unix command-line utilities that you can reach from within OS X's Terminal window.
To get into the Unix environment, launch the Terminal application. (That's Finder Applications Utilities Terminal. If you expect to use the Terminal a lot, drag the Terminal icon from the Finder window onto the Dock. You can then launch Terminal with a single click.) Once Terminal is running, you'll see a window like the one in Figure 1-1.
Figure 1-1: The Terminal window
Once you have a window open and you're typing commands, it's helpful to know that regular Mac OS X cut and paste commands work, so it's simple to send an email message to a colleague showing your latest Unix interaction, or to paste some text from a web page into a file you're editing with a Unix text editor such as vi.
You can also have a number of different Terminal windows open if that helps your workflow. Simply use -N to open each one, and -~ to cycle between them without removing your hands from the keyboard.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working in the Unix Environment
To get into the Unix environment, launch the Terminal application. (That's Finder Applications Utilities Terminal. If you expect to use the Terminal a lot, drag the Terminal icon from the Finder window onto the Dock. You can then launch Terminal with a single click.) Once Terminal is running, you'll see a window like the one in Figure 1-1.
Figure 1-1: The Terminal window
Once you have a window open and you're typing commands, it's helpful to know that regular Mac OS X cut and paste commands work, so it's simple to send an email message to a colleague showing your latest Unix interaction, or to paste some text from a web page into a file you're editing with a Unix text editor such as vi.
You can also have a number of different Terminal windows open if that helps your workflow. Simply use -N to open each one, and -~ to cycle between them without removing your hands from the keyboard.
If you have material in your scroll buffer you want to find, use -F (select Find Panel from the Edit menu) and enter the specific text. -G (Find Next) lets you search down the scroll buffer for the next occurrence, and -D (Find Previous) lets you search up the scroll buffer for the previous occurrence. You can also accomplish this by highlighting a passage, entering
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Syntax of Unix Command Lines
Unix command lines can be simple, one-word entries such as the date command. They can also be more complex; you may need to type more than the command or program name.
A Unix command can have arguments. An argument can be an option or a filename. The general format for a Unix command line is:
command option(s) filename(s)
         
There isn't a single set of rules for writing Unix commands and arguments, but these general rules work in most cases:
  • Enter commands in lowercase.
  • Options modify the way in which a command works. Options are often single letters prefixed with a dash (- , also called "hyphen" or "minus") and set off by any number of spaces or tabs. Multiple options in one command line can be set off individually (such as -a -b). In some cases, you can combine them after a single dash (such as -ab), but most commands' documentation doesn't tell you whether this will work; you'll have to try it.
    Some commands also have options made from complete words or phrases and starting with two dashes, such as --delete or --confirm-delete. When you enter a command line, you can use this option style, the single-letter options (which each start with a single dash), or both.
  • The argument filename is the name of a file you want to use. Most Unix programs also accept multiple filenames, separated by spaces or specified with wildcards (see Chapter 3). If you don't enter a filename correctly, you may get a response such as "filename: no such file or directory" or "filename: cannot open."
    Some commands, such as telnet and who (shown earlier in this chapter), have arguments that aren't filenames.
  • You must type spaces between commands, options, and filenames. You'll need to "quote " filenames that contain spaces. For more information, see Section 3.1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Types of Commands
When you use a program, you'll want to know how to control it. How can you tell it what job you want done? Do you give instructions before the program starts, or after it's started? There are several general ways to give commands on a Unix system. It's good to be aware of them.
  1. Some programs work only within the graphical window environment (on Mac OS X, this is called Aqua). On Mac OS X, you can run these programs using the open command. For instance, when you type open /Applications/Chess.app at a shell prompt, the chess game starts. It opens one or more windows on your screen. The program has its own way to receive your commands—through menus and buttons on its windows, for instance.
  2. You've also seen in Section 1.2, that you can enter many Unix commands at a shell prompt. These programs work in a window system (from a terminal window) or from any terminal. You control those programs from the Unix command line—that is, by typing options and arguments from a shell prompt before you start the program. After you start the program, wait for it to finish; you generally don't interact with it.
  3. Some Unix programs that work in the terminal window have commands of their own. (If you'd like some examples, see Chapter 2 and Chapter 3.) These programs may accept options and arguments on their command lines. But, once you start a program, it prints its own prompt and/or menus, and it understands its own commands; it takes instructions from your keyboard that weren't given on its command line.
    For instance, if you enter ftp at a shell prompt, you'll see a new prompt from the ftp program. Enter FTP commands to transfer files to and from remote systems. When you enter the special command quit to quit the ftp program, ftp will stop prompting you. Then you'll get another shell prompt, where you can enter other Unix commands.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Unresponsive Terminal
During your Unix session, your terminal may not respond when you type a command, or the display on your screen may stop at an unusual place. That's called a "hung" or "frozen" terminal or session. Note that most of the techniques in this section apply to a terminal window, but not to non-terminal windows such as a web browser.
A session can hang for several reasons. For instance, your computer can get too busy; the Terminal application has to wait its turn. In that case, your session starts by itself after a few moments. You should not try to "un-hang" the session by entering extra commands, because those commands will all take effect after Terminal comes back to life.
If the system doesn't respond for quite a while (how long that is depends on your individual situation; ask other users about their experiences), the following solutions usually work. Try the following steps in the order shown until the system responds:
  1. Press the Return key once.
    You may have typed text at a prompt (for example, a command line at a shell prompt) but haven't yet pressed Return to say that you're done typing and your text should be interpreted.
  2. Try job control (see Chapter 9); type Control-Z.
    This control key sequence suspends a program that may be running and gives you a shell prompt. Now you can enter the jobs command to find the program's name, then restart the program with fg or terminate it with kill .
  3. Use your interrupt key (found earlier in this chapter in Section 1.1.4; typically Control-C).
    This interrupts a program that may be running. (Unless the program is run in the background, as described in Section 9.1, the shell waits for it to finish before giving a new prompt. A long-running program may thus appear to hang the terminal.) If this doesn't work the first time, try it once more; doing it more than twice usually won't help.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Using Unix
Once you launch Terminal, you can use the many facilities that Unix provides. As an authorized system user, you have an account that gives you:
  • A place in the Unix filesystem where you can store your files.
  • A username that identifies you, lets you control access to your files, and is an address for your email (although it may not be your main address).
  • An environment you can customize.
A file is the unit of storage in Unix, as it is in the Mac environment. A file can hold anything: text (a report you're writing, a to-do list), a program, digitally encoded pictures or sound, and so on. All of those are just sequences of raw data until they're interpreted by the right program.
In Unix, files are organized into directories. A directory is actually a special kind of file where the system stores information about other files. (A Unix directory is identical to a Mac folder.) You can think of a directory as a place, so that files are said to be contained in directories, and you work inside a directory.
This section introduces the Unix filesystem. Later sections show how you can look in files and protect them. Chapter 3 has more information.
When you launch Terminal, you're placed in a directory called your home directory. This directory, a unique place in the Mac OS X filesystem, contains the files you use almost every time you log in. In your home directory, you can create your own files. As you'll see, you can also store your own directories within your home directory. Like folders in a file cabinet, this is a good way to organize your files.
Your
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Unix Filesystem
A file is the unit of storage in Unix, as it is in the Mac environment. A file can hold anything: text (a report you're writing, a to-do list), a program, digitally encoded pictures or sound, and so on. All of those are just sequences of raw data until they're interpreted by the right program.
In Unix, files are organized into directories. A directory is actually a special kind of file where the system stores information about other files. (A Unix directory is identical to a Mac folder.) You can think of a directory as a place, so that files are said to be contained in directories, and you work inside a directory.
This section introduces the Unix filesystem. Later sections show how you can look in files and protect them. Chapter 3 has more information.
When you launch Terminal, you're placed in a directory called your home directory. This directory, a unique place in the Mac OS X filesystem, contains the files you use almost every time you log in. In your home directory, you can create your own files. As you'll see, you can also store your own directories within your home directory. Like folders in a file cabinet, this is a good way to organize your files.
Your working directory (also called your current directory) is the directory in which you're currently working. Every time you launch Terminal, your home directory is your working directory. When you change to another directory, the directory you move to becomes your working directory.
Unless you tell Unix otherwise, all commands that you enter apply to the files in your working directory. In the same way, when you create files, they're created in your working directory unless you specify another directory. For instance, if you type the command
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Looking Inside Files with less
By now , you're probably tired of looking at files from the outside. It's akin to visiting a bookstore and looking at the covers, but never getting to read a word. Let's look at a program for reading text files.
If you want to "read" a long file on the screen, you can use the less command to display one "page" (a Terminal window filled from top to bottom) of text at a time.
If you don't like less, you can try a very similar program named more. (In fact, the name less is a play on the name of more, which came first.) The syntax for less is:
less option(s) file(s)
         
less lets you move forward or backward in the files by any number of pages or lines; you can also move back and forth between two or more files specified on the command line. When you invoke less, the first "page" of the file appears. A prompt appears at the bottom of the Terminal window, as in the following example:
% less ch03
A file is the unit of storage in Unix, as in most other systems.
A file can hold anything: text (a report you're writing,
 .
 .
 .
:
The basic less prompt is a colon (:); although, for the first screenful, less displays the file's name as a prompt. The cursor sits to the right of this prompt as a signal for you to enter a less command to tell less what to do. To quit, type q.
Like almost everything about less, the prompt can be customized. For example, using the -M starting flag on the less command line makes the prompt show the filename and your position in the file (as a percentage). If you want this to happen every time you use less, you can set the LESS environment variable to M (without a dash) in your shell setup file. See Section 4.2.
You can set or unset most options temporarily from the less prompt. For instance, if you have the short less prompt (a colon), you can enter -M while less is running. less responds "Long prompt (press Return)," and for the rest of the session,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Protecting and Sharing Files
Unix makes it easy for users on the same system to share files and directories. For instance, everyone in a group can read documents stored in one of their manager's directories without needing to make their own copies, if the manager has allowed access. There might be no need to fill peoples' email inboxes with file attachments if everyone can access those files directly through the Unix filesystem.
Here's a brief introduction to file security and sharing. If you have critical security needs, or you just want more information, talk to your system staff or see an up-to-date book on Unix security such as Practical Unix and Internet Security (O'Reilly).
Note that the system's superuser (the system administrator and possibly other users) can do anything to any file at any time, no matter what its permissions are. So, access permissions won't keep your private information safe from everyone—although let's hope that you can trust your system administrator!
Your system administrator should also keep backup copies of users' files. These backup copies may be readable by anyone who has physical access to them. That is, anyone who can take the backup out of a cabinet (or wherever) and mount it on a computer system may be able to read the file copies. The same is true for files stored on floppy disks and any other removable media. (Once you take a file off a Unix system, that system can't control access to it anymore.)
A directory's access permissions help to control access to the files and subdirectories in that directory:
  • If a directory has read permission, a user can run ls to see what's in the directory and use wildcards to match files in it.
  • A directory that has write permission allows users to add, rename, and delete files in the directory.
  • To access a directory (that is, to read or write the files in the directory or to run the files if they're programs) a user needs execute permission on that directory. Note that to access a directory, a user must
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Graphical Filesystem Browsers
Because you've the luxury of running Unix within the Mac OS X environment, there's also a terrific graphical way to do some of the things you can do with files from the command line. A filesystem browser , such as the Finder, lets you see a graphical representation of the filesystem and do a limited number of operations on it. Figure 2-6 shows the Finder in its default icon view. Other views that are helpful are listing and directory views, each offering more information about the directories above and below the current directory.
Figure 2-6: Mac OS X Finder, icon view
The Finder can be handy for seeing what's in the filesystem. Unfortunately, because the Finder takes you away from the shell you're using for other work, it can limit what you're able to do with Unix. (You'll see additional information about why this is true when we cover more advanced features such as input/output redirection in Section 6.1.1.) We recommend learning more about the Finder, but also learning what you can do at the more powerful Unix command line.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Completing File and Directory Names
Most Unix shells can complete a partly typed file or directory name for you. Different shells have different methods. If you're using the default shell in Mac OS X, tcsh, just type the first few letters of the name, then press Tab. If the shell can find just one way to finish the name, it will; your cursor will move to the end of the new name, where you can type more or press Return to run the command. (You can also edit or erase the completed name.)
What happens if more than one file or directory name matches what you've typed so far? You will get a list of all possible completions; try pressing Tab and you may see a list of all names starting with the characters you've typed so far. Here's an example from the tcsh shell:
% maTab
mach_init      mailq          make           makemap        man
machine        mailstat       makedbm        makepsres
mail           mailstats      makedepend     malloc_history
% ma
At this point, you could type another character or two—an i, for example—and then press Tab once more to list only the mail-related commands.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: File Management
Chapter 2 introduced the Unix filesystem. This chapter explains how to name, edit, copy, move, and find files.
As Chapter 2 explains, both files and directories are identified by their names. A directory is really just a special kind of file, so the rules for naming directories are the same as the rules for naming files.
Filenames may contain any character except /, which is reserved as the separator between files and directories in a pathname. Filenames are usually made of upper- and lowercase letters, numbers, "." (dots), and "_" (underscores). Other characters (including spaces) are legal in a filename, but they can be hard to use because the shell gives them special meanings. However, spaces are a standard part of Macintosh file and folder names, so while we recommend using only letters, numbers, dots, and underscore characters for filenames, the reality is that you will have to figure out how to work with the spaces in file and directory names. The Finder, by contrast, dislikes colons (which it uses as a directory separator, just as Unix uses the slash). If you display a file called test:me in the Finder, the name is shown as test/me instead.
If you have a file with spaces in its name, the shell will be confused if you type its name on the command line. That's because the shell breaks command lines into separate arguments at the spaces. To tell the shell not to break an argument at spaces, either put quotation marks (") around the argument or preface each space with a backslash (\).
For example, the rm program, covered later in this chapter, removes Unix files. To remove a file named a confusing name, the first rm command in the following snippet doesn't work, but the second one does. Also note that you can escape spaces (that is, avoid having the shell interpret them inappropriately) by using a backslash character, as shown in the third example:
% ls -l
total 2
-rw-r--r--   1 taylor  staff   324 Feb  4 23:07 a confusing name
-rw-r--r--   1 taylor  staff    64 Feb  4 23:07 another odd name
% 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File and Directory Names
As Chapter 2 explains, both files and directories are identified by their names. A directory is really just a special kind of file, so the rules for naming directories are the same as the rules for naming files.
Filenames may contain any character except /, which is reserved as the separator between files and directories in a pathname. Filenames are usually made of upper- and lowercase letters, numbers, "." (dots), and "_" (underscores). Other characters (including spaces) are legal in a filename, but they can be hard to use because the shell gives them special meanings. However, spaces are a standard part of Macintosh file and folder names, so while we recommend using only letters, numbers, dots, and underscore characters for filenames, the reality is that you will have to figure out how to work with the spaces in file and directory names. The Finder, by contrast, dislikes colons (which it uses as a directory separator, just as Unix uses the slash). If you display a file called test:me in the Finder, the name is shown as test/me instead.
If you have a file with spaces in its name, the shell will be confused if you type its name on the command line. That's because the shell breaks command lines into separate arguments at the spaces. To tell the shell not to break an argument at spaces, either put quotation marks (") around the argument or preface each space with a backslash (\).
For example, the rm program, covered later in this chapter, removes Unix files. To remove a file named a confusing name, the first rm command in the following snippet doesn't work, but the second one does. Also note that you can escape spaces (that is, avoid having the shell interpret them inappropriately) by using a backslash character, as shown in the third example:
% ls -l
total 2
-rw-r--r--   1 taylor  staff   324 Feb  4 23:07 a confusing name
-rw-r--r--   1 taylor  staff    64 Feb  4 23:07 another odd name
% rm a confusing name
rm: a: no such file or directory
rm: confusing: no such file or directory
rm: name: no such file or directory
% 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File and Directory Wildcards
When you have a number of files named in series (for example, chap1 to chap12) or filenames with common characters (such as aegis, aeon, and aerie), you can use wildcards to specify many files at once. These special characters are * (asterisk), ? (question mark), and [ ] (square brackets). When used in a file or directory name given as an argument on a command line, the following is true:
*
An asterisk stands for any number of characters in a filename. For example, ae* would match aegis, aerie, aeon, etc. if those files were in the same directory. You can use this to save typing for a single filename (for example, al* for alphabet.txt) or to choose many files at once (as in ae*). A * by itself matches all file and subdirectory names in a directory, with the exception of any starting with a period. To match all your dot files, try .??*.
?
A question mark stands for any single character (so h?p matches hop and hip, but not help).
[]
Square brackets can surround a choice of single characters (i.e., one digit or one letter) you'd like to match. For example, [Cc]hapter would match either Chapter or chapter, but chap[12] would match chap1 or chap2. Use a hyphen (-) to separate a range of consecutive characters. For example, chap[1-3] would match chap1, chap2, or chap3.
The following examples show the use of wildcards. The first command lists all the entries in a directory, and the rest use wildcards to list just some of the entries. The last one is a little tricky; it matches files whose names contain two (or more) a's.
% ls
chap10       chap2        chap5     cold
chap1a.old   chap3.old    chap6     haha
chap1b       chap4        chap7     oldjunk
% 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating and Editing Files
One easy way to create a file is with a Unix feature called input/output redirection, as Chapter 5 explains. This sends the output of a program directly to a file, to make a new file or add to an existing one.
You'll usually create and edit a plain-text file with a text editor program. Text editors are somewhat different than word processors.
A text editor lets you add, change, and rearrange text easily. Three popular Unix editors included with Mac OS X are vi (pronounced "vee-eye"), Pico ("pea-co"), and Emacs ("e-max").
Since there are several editor programs, you can choose one you're comfortable with. vi is probably the best choice because almost all Unix systems have it, but Emacs is also widely available. If you'll be doing simple editing only, Pico is a great choice. Although Pico is much less powerful than Emacs or vi, it's also a lot easier to learn. For this book, however, we'll focus on the rudiments of vi as it's the most widely available Unix editor, and there's a version of vi included with Mac OS X.
None of those editors has the same features as popular word-processing software within the graphical face of Mac OS X, but vi and Emacs are sophisticated, extremely flexible editors for all kinds of plain-text files: programs, email messages, and so on. Of course, you can opt to use an Aqua-based editor such as BBEdit or TextEdit with good results too, if you'd rather just sidestep editing while within the Terminal application. If you do, try using the open command within the Terminal to launch the editor with the proper file already loaded. For example: open -e myfile.txt.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Managing Your Files
The tree structure of the Unix filesystem makes it easy to organize your files. After you make and edit some files, you may want to copy or move files from one directory to another, or rename files to distinguish different versions of a file. You may want to create new directories each time you start a different project. If you copy a file, it's worth learning about the subtle sophistication of the cp and CpMac commands: if you copy a file to a directory, it automatically reuses the filename in the new location. This can save lots of typing!
A directory tree can get cluttered with old files you don't need. If you don't need a file or a directory, delete it to free storage space on the disk. The following sections explain how to make and remove directories and files.
It's handy to group related files in the same directory. If you were writing a spy novel, you probably wouldn't want your intriguing files mixed with restaurant listings. You could create two directories: one for all the chapters in your novel (spy, for example), and another for restaurants (boston.dine).
To create a new directory, use the mkdir program. The syntax is:
mkdir dirname(s)
            
dirname is the name of the new directory. To make several directories, put a space between each directory name. To continue our example, you would enter:
% mkdir spy boston.dine
            
If you're about to edit a file, you may want to save a copy first. That makes it easy to get back the original version. You should use the cp program when copying plain files and directories. All other Macintosh files (that is, those with resource forks) should be copied with CpMac (available only if you have installed Apple's Mac OS X developer CD).

Section 3.4.2.1: cp

The cp program can put a copy of a file into the same directory or into another directory.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Customizing Your Session
One of the great pleasures of using Unix with Mac OS X surrounding it is that you get the benefit of a truly wonderful graphical application environment and the underlying power of the raw Unix interface. A match made in heaven!
This chapter discusses how to customize your Terminal environment both from the graphical user interface using Terminal Preferences and from the Unix shell by using shell configuration files.
Launch Terminal and you have a dull, uninspiring white window with black text that says "Welcome to Darwin!" and a shell prompt. But that's okay. We can fix it.
To change the display preferences in the Terminal application, go to the Terminal menu and choose Preferences.... You see a display similar to Figure 4-1.
Figure 4-1: Startup Preferences
Along the window's top, notice that a number of different preferences are configurable: Startup, Shell, Window, Text & Colors, Buffer, Emulation, and Activity. The icons suggest what each does, but let's have a closer look anyway, particularly since some of these settings definitely should be changed in our view. It's worth pointing out that these changes affect new windows not the current window.

Section 4.1.1.1: Startup Preferences

When you first open Terminal Preferences, the Startup Preferences are displayed, as shown in Figure 4-1. The default behavior is to launch a new blank shell window each time the program is started, so you're ready to start typing commands immediately. Unless you're an advanced user, don't change this behavior. Instead, let's look at what's on the other preference screens, which you can view by clicking on each icon at the top of the Preferences window.

Section 4.1.1.2: Shell Preferences

As Figure 4-2 reveals, there are a number of behavioral choices you can make on this panel, including whether you want each window to have its own login shell associated with your account, or whether all Terminal windows should run a specified shell (in this case,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Launching Terminal
Launch Terminal and you have a dull, uninspiring white window with black text that says "Welcome to Darwin!" and a shell prompt. But that's okay. We can fix it.
To change the display preferences in the Terminal application, go to the Terminal menu and choose Preferences.... You see a display similar to Figure 4-1.
Figure 4-1: Startup Preferences
Along the window's top, notice that a number of different preferences are configurable: Startup, Shell, Window, Text & Colors, Buffer, Emulation, and Activity. The icons suggest what each does, but let's have a closer look anyway, particularly since some of these settings definitely should be changed in our view. It's worth pointing out that these changes affect new windows not the current window.

Section 4.1.1.1: Startup Preferences

When you first open Terminal Preferences, the Startup Preferences are displayed, as shown in Figure 4-1. The default behavior is to launch a new blank shell window each time the program is started, so you're ready to start typing commands immediately. Unless you're an advanced user, don't change this behavior. Instead, let's look at what's on the other preference screens, which you can view by clicking on each icon at the top of the Preferences window.

Section 4.1.1.2: Shell Preferences

As Figure 4-2 reveals, there are a number of behavioral choices you can make on this panel, including whether you want each window to have its own login shell associated with your account, or whether all Terminal windows should run a specified shell (in this case, /bin/tcsh). In Mac OS X you're probably the only person who uses your computer, so if your login shell is acceptable to you, leaving the shell setting to reference the login shell is your best bet.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customizing Your Shell Environment
The Unix shell reads a number of configuration files when it starts up. These configuration files are really shell programs , so they are extraordinarily powerful. Shell programming is beyond the scope of this book. For more detail, see Paul DuBois' book, Using csh and tcsh (O'Reilly). Because Unix is a multiuser system, there are two possible locations for the configuration files: one applies to all users of the system and another to each individual user.
The system-wide setup files that are read by tcsh, the default shell for Mac OS X, are found in /usr/share/init/tcsh. You only have permission to change these system-wide files if you are logged in as root. However, you can create an additional file called .tcshrc in your home directory that will add additional commands to be executed whenever you start a new Terminal window. (If you configure Terminal to use another shell, such as the Bourne shell, the C shell, or the Z shell, you'll need to set up different configuration files, which we don't discuss.) The system-wide setup files are read first, then the user-specific ones, so commands in your .tcshrc file may override those in the system-wide files.
The .tcshrc file can contain any shell command that you want to run automatically whenever you create a new Terminal. Some typical examples include changing the shell prompt, setting environment variables (values that control the operation of other Unix utilities), setting aliases, or adding to the search path (where the shell searches for programs to be run). A .tcshrc file could look like this:
set prompt="%/ %h% "
setenv LESS 'eMq'
alias desktop "cd /Users/taylor/Desktop"
date
This sample .tcshrc file issues the following commands:
  • The line with set prompt tells the shell to use a different prompt than the standard one. We'll explain the details of prompt setting in Section 4.2.1 later in this chapter.
  • The line with setenv
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further Customization
There's not much more you can do with the Terminal application than what's shown in this chapter, but there's an infinite amount of customization possible with the tcsh shell (or any other shell you might have picked). To learn more about how to customize your shell, read the manpage. Be warned, though, the tcsh manpage is over 5,800 lines long!
Oh, and in case you're wondering, manpages are the Unix version of online help documentation. Just about every command-line (Unix) command has a corresponding manpage with lots of information on starting flags, behaviors, and much more. You can access any manpage by simply typing man cmd. Start with man man to learn more about the man system.
For more information on customizing tcsh, see Paul DuBois' book, Using csh and tcsh, or Unix Power Tools, Second Edition , by Jerry Peek, Tim O'Reilly, and Mike Loukides, both available from O'Reilly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Printing
Working in the Macintosh environment, you're used to a simple and elegant printer interface, particularly in OS X, where Print Center makes it a breeze to add new printers and configure your existing printers. The Unix environment has never had a printing interface that even comes close in usability, and while the standard print command in Unix is lpr, getting it to work on OS X involves reconfiguring your system and a number of tricky system administration tasks best avoided if you're not a Unix expert.
If you do want to try, see Configuring Your Printer at the end of this chapter for some suggestions on how to proceed.
The good news is that Apple has included a couple of alternative command-line interfaces to printers, notably atprint for AppleTalk-based printers, and Print, a program that's supposed to inject your print jobs into the regular Aqua print queue.
Regardless of what program you're going to use for printing, before you print a file on a Unix system, you may want to reformat it to adjust the margins, highlight some words, and so on. Most files can also be printed without reformatting, but the raw printout might not look quite as nice. Further, some printers accept only PostScript, which means you'll need to use a text-to-PostScript filter such as enscript for good results. Before we cover printing itself, let's look at both pr and enscript to see how they work.
The pr program does minor formatting of files on the terminal screen or for a printer. For example, if you have a long list of names in a file, you can format it onscreen into two or more columns.
The syntax is:
pr option(s) filename(s)
            
pr changes the format of the file only on the screen or on the printed copy; it doesn't modify the original file. Table 5-1 lists some pr options.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Formatting and Print Commands
The good news is that Apple has included a couple of alternative command-line interfaces to printers, notably atprint for AppleTalk-based printers, and Print, a program that's supposed to inject your print jobs into the regular Aqua print queue.
Regardless of what program you're going to use for printing, before you print a file on a Unix system, you may want to reformat it to adjust the margins, highlight some words, and so on. Most files can also be printed without reformatting, but the raw printout might not look quite as nice. Further, some printers accept only PostScript, which means you'll need to use a text-to-PostScript filter such as enscript for good results. Before we cover printing itself, let's look at both pr and enscript to see how they work.
The pr program does minor formatting of files on the terminal screen or for a printer. For example, if you have a long list of names in a file, you can format it onscreen into two or more columns.
The syntax is:
pr option(s) filename(s)
            
pr changes the format of the file only on the screen or on the printed copy; it doesn't modify the original file. Table 5-1 lists some pr options.
Table 5-1: Some pr options
Option
Description
-k
Produces k columns of output
-d
Double-spaces the output (may not work on all versions of pr
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Configuring Your LPR Printer
While there are a great many areas of Mac OS X that are enhanced by the addition of Unix as the low-level operating system, one area has become more complex: printing. If you only live in the world of Aqua, it's not too bad because Print Center manages all your needs, but if you want to print from the Unix command line and you don't have an AppleTalk printer, you've got a bit of a tinkering job ahead of you.
If you do have a printer accessible through AppleTalk, flip back a few pages and read the section about the atprint command, or use man atprint to learn how to simplify your life considerably.
Otherwise, configuring your printer requires four steps: adding an entry to /etc/printcap for the printer, creating a spool directory and log file skeleton, importing the printcap entry into NetInfo, and adding the printer to Print Center.
To do this, you'll need both your Unix root password and your system administrator password. If you're unsure about your Unix root password, you can go into NetInfo and search the help system.
The first step is to edit the printer capabilities database /etc/printcap. You need to be root to do this, so it's easiest to use the sudo command to simply run the edit command as root:
% sudo vi /etc/printcap
            
This file contains lots of cryptic information that is attempting to define the capabilities and interface for each known printer accessible from Unix. The default entry in the file is for a local printer that's accessible through the /dev/lp device:
lp|local line printer:\
      :lp=/dev/lp:sd=/var/spool/output/lpd:lf=/var/log/lpd-errs:
Odds are that this printer configuration is not going to work for you, however, so comment it out and add a new one for the new printer. In this example, 198.76.82.151 is the IP address of an HP LaserJet 2100TN Ethernet printer, which we'll call lj for the Unix system. If your printer has a unique hostname, that's better to use than the IP address, but either way, carefully duplicate the following:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Redirecting I/O
Many Unix programs read input (such as a file) and write output. In this chapter, we discuss Unix programs that handle their input and output in a standard way. This lets them work with each other.
This chapter generally doesn't apply to full-screen programs, such as the Pico editor, that take control of your whole Terminal window. (The pager programs, less, and more do work together in this way.) It also doesn't apply to graphical programs, such as the Finder or Internet Explorer, that open their own windows on your screen.
What happens if you don't give a filename argument on a command line? Most programs will take their input from your keyboard instead (after you press Return to start the program running, that is). Your Terminal keyboard is the program's standard input.
As a program runs, the results are usually displayed on your Terminal screen. The Terminal screen is the program's standard output . So, by default, each of these programs takes its information from the standard input and sends the results to the standard output. These two default cases of input/output (I/O) can be varied. This is called I/O redirection .
If a program doesn't normally read from files, but reads from its standard input, you can give a filename by using the < (less-than symbol) operator. For example, the mail program (see Section 8.2.3 in Chapter 8) normally reads the message to send from your keyboard. Here's how to use the input redirection operator to count the number of lines in the file to_do :
% wc -l < to_do
%
If a program writes to its standard output, which is normally the screen, you can make it write to a file instead by using the greater-than symbol (>) operator. The pipe operator (|) sends the standard output of one program to the standard input of another program. Input/output redirection is one of the most powerful and flexible Unix features.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Standard Input and Standard Output
What happens if you don't give a filename argument on a command line? Most programs will take their input from your keyboard instead (after you press Return to start the program running, that is). Your Terminal keyboard is the program's standard input.
As a program runs, the results are usually displayed on your Terminal screen. The Terminal screen is the program's standard output . So, by default, each of these programs takes its information from the standard input and sends the results to the standard output. These two default cases of input/output (I/O) can be varied. This is called I/O redirection .
If a program doesn't normally read from files, but reads from its standard input, you can give a filename by using the < (less-than symbol) operator. For example, the mail program (see Section 8.2.3 in Chapter 8) normally reads the message to send from your keyboard. Here's how to use the input redirection operator to count the number of lines in the file to_do :
% wc -l < to_do
%
If a program writes to its standard output, which is normally the screen, you can make it write to a file instead by using the greater-than symbol (>) operator. The pipe operator (|) sends the standard output of one program to the standard input of another program. Input/output redirection is one of the most powerful and flexible Unix features.
Instead of always letting a program's output come to the screen, you can redirect output to a file. This is useful when you'd like to save program output, or when you put files together to make a bigger file.

Section 6.1.1.1: cat

cat , which is short for "concatenate," reads files and outputs their contents one after another, without stopping.
To display files on the standard output (your screen), use:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Pipes and Filters
We've seen how to redirect input from a file and output to a file. You can also connect two programs together so that the output from one program becomes the input of the next program. Two or more programs connected in this way form a pipe. To make a pipe , put a vertical bar (|) on the command line between two commands. When a pipe is set up between two commands, the standard output of the command to the left of the pipe symbol becomes the standard input of the command to the right of the pipe symbol. Any two commands can form a pipe as long as the first program writes to standard output and the second program reads from standard input.
When a program takes its input from another program, performs some operation on that input, and writes the result to the standard output (which may be piped to yet another program), it is referred to as a filter. A common use of filters is to modify output. Just as a common filter culls unwanted items, Unix filters can restructure output.
Most Unix programs can be used to form pipes. Some programs that are commonly used as filters are described in the next sections. Note that these programs aren't used only as filters or parts of pipes. They're also useful on their own.
The grep program searches a file or files for lines that have a certain pattern. The syntax is:
grep "pattern" file(s)
            
The name "grep" is derived from the ed (a Unix line editor) command g/re/p, which means "globally search for a regular expression and print all matching lines containing it." A regular expression is either some plain text (a word, for example) and/or special characters used for pattern matching. When you learn more about regular expressions, you can use them to specify complex patterns of text.
The simplest use of grep is to look for a pattern consisting of a single word. It can be used in a pipe so only those lines of the input files containing a given string are sent to the standard output. But let's start with an example reading from files: searching all files in the working directory for a word—say,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Accessing the Internet
A network lets computers communicate with each other, sharing files, email, and much more. Unix systems have been networked for more than 25 years, and Macintosh systems have always had networking as an integral part of the system design from the very first system released in 1984.
This chapter introduces Unix networking: running programs on other computers, copying files between computers, browsing the World Wide Web