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, Second Edition

By Dave Taylor, Brian Jepson

Cover | Table of Contents | Colophon


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, the operating system installation 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 Mac OS X system, you're automatically logged into your Unix account as well. In fact, your Desktop and other customized features of your Mac 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 Mac 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 copy 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 (or select Find Find from the Edit menu) and enter the specific text. -G (Find Next) lets you search down the scroll buffer for the next occurrence, and
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 copy 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 (or select Find Find 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 search for material by highlighting a passage, entering -E (Use Selection for Find) or jumping to the selected material with -J (Jump to Selection). You can also save an entire Terminal session as a text file with File Save Text As, and you can print the entire session with File Print. It's a good idea to study the key sequences shown in the Scrollback menu, as illustrated in Figure 1-2.
Figure 1-2: Command sequences accessible from the Scrollback menu
Inside the Terminal window, you're working with a program called a shell . The shell interprets command lines you enter, runs programs you ask for, and generally coordinates what happens between you and the Unix operating system. The default shell on Mac OS X is called
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.
  • Options come before filenames.
  • In a few cases, an option has another argument associated with it; type this special argument just after its option. Most options don't work this way, but you should know about them. The sort command is an example of this feature: you can tell sort to write the sorted text to a filename given after its
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 Mac OS X system. It's good to be aware of them.
Graphical programs
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 -a Chess 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. Although you can't interact with these programs using traditional Unix utilities, Mac OS X includes the osascript utility, which lets you run AppleScript commands from the Unix shell.
Non-interactive Unix programs
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.
Interactive Unix programs
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 your display becomes garbled, press Control-L. In the shell, this will clear the screen and display the prompt. In a full-screen program, such as a text editor, it will redraw the screen.
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:
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.
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.
Press Control-C or -..
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 a background program to finish before giving a new prompt. A long-running background 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 Mac OS X provides. As a user, you have an account that gives you:
  • A place in the filesystem where you can store your files
  • A username that identifies you and lets you control access to your files
  • An environment you can customize
A file is the unit of storage in Mac OS X. 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.
Files are organized into directories (more commonly referred to as a folder on the Mac). A directory is actually a special kind of file where the system stores information about other files. 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.
A filesystem includes all the files and directories on a mounted volume, such as your system's hard disk or your iDisk. This section introduces the Mac OS X 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, which can be opened in the Finder by clicking the Home icon, contains personal files, application preferences, and application data such as bookmarks. In your home directory, you can create your own files. As you'll see, you can also create 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 open a new Terminal window, your home directory is your working directory. When you change to another directory, the directory you move to becomes your working directory.
Unless you specify 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!
The Mac OS X Filesystem
A file is the unit of storage in Mac OS X. 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.
Files are organized into directories (more commonly referred to as a folder on the Mac). A directory is actually a special kind of file where the system stores information about other files. 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.
A filesystem includes all the files and directories on a mounted volume, such as your system's hard disk or your iDisk. This section introduces the Mac OS X 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, which can be opened in the Finder by clicking the Home icon, contains personal files, application preferences, and application data such as bookmarks. In your home directory, you can create your own files. As you'll see, you can also create 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 open a new Terminal window, your home directory is your working directory. When you change to another directory, the directory you move to becomes your working directory.
Unless you specify 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 vi report, the vi editor is started, and a file named report is created in your working directory. But if you type a command such as
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
Mac OS X 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 any Admin user can use the sudo command (see Section 2.3, later in this chapter) to 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 the other folks who share your Macintosh!
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 also have execute permission to all its parent directories, all the way up to the root.
Mac OS X includes a shared directory for all users: /Users/Shared . You can create files in this directory and modify files you have put there. However, you cannot modify a file there that's owned by another user.
The access permissions on a file control what can be done to the file's contents. The access permissions on the directory where the file is kept control whether the file can be renamed or removed. (If this seems confusing, think of it this way: the directory is actually a list of files. Adding, renaming, or removing a file changes the contents of the directory. If the directory isn't writable, you can't change that list.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Superuser Privileges with sudo
Your Mac OS X user account runs with restricted privileges; there are parts of the filesystem you don't have access to, and there are certain activities that are prohibited until you supply a password. For example, when you run the Software Update utility from System Preferences, Mac OS X may ask you for your password before it proceeds. This extra authentication step allows Software Update to run installers with superuser privileges.
You can invoke these same privileges at the command line by prefixing a command with sudo, a utility that prompts you for your password and executes the command as the superuser. You must be an Admin user to use sudo. The user you created when you first set up your Mac will be an Admin user. You can add new Admin users, or grant Admin status to a user in System Preferences Accounts.
What if you don't know your administrative password? If you forgot your password, read the Mac OS Help to direct you. You might need to reboot your computer off your original Mac OS X install CD-ROM, then when you get to the installer, select the Reset Password... option from the Installer menu. The program will then prompt you for a new password and set it for your machine. Reboot again (without the CD-ROM), and you should be set forever.
You may need to use sudo when you install Unix utilities or if you want to modify a file you don't own. Suppose that you accidentally created a file in the /Users directory while you were doing something else as the superuser. You won't be able to modify it with your normal privileges, so you'll need to use sudo:
% ls -l logfile.out 
-rw-r--r--    1 root     wheel     1784064 Nov  6 11:25 logfile.out
% rm logfile.out 
override rw-r--r--  root/wheel for logfile.out? y
rm: logfile.out: Permission denied
% sudo rm logfile.out 
Password:********
% ls -l logfile.out 
ls: logfile.out: No such file or directory
If you use sudo again within five minutes, it won't ask for your password. Be careful using sudo, since it gives you the ability to modify protected files, all of which are protected to ensure the system runs properly.
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 have 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-7 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-7: 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!
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 explained, 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 work with spaces in file and directory names. The Finder, by contrast, dislikes colons (which older versions of Mac OS used 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. (The reverse is also true: if you create a file in the Finder whose name contains a slash, it will appear as a colon in the Terminal.)
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 explained, 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 work with spaces in file and directory names. The Finder, by contrast, dislikes colons (which older versions of Mac OS used 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. (The reverse is also true: if you create a file in the Finder whose name contains a slash, it will appear as a colon in the Terminal.)
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 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
% ls chap?
chap2    chap5    chap7
chap4    chap6
% ls chap[5-7]
chap5    chap6    chap7
% ls chap[5-9]
chap5    chap6    chap7
% ls chap??
chap10   chap1b
% ls *old
chap1a.old   chap3.old    cold
% ls *a*a*
chap1a.old   haha
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").
You should choose an editor 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 a lot easier to learn. For this book, however, we'll focus on the rudiments of vi since it's the most widely available Unix editor, and there's a version of vi included with Mac OS X.
None of these plain text 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 text 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 containing only plain files. Other files having resource forks should be copied with CpMac (available only if you have installed Apple's Mac OS X Developer Tools).

Section 3.4.2.1: cp

The cp program can put a copy of a file into the same directory or into another directory. cp doesn't affect the original file, so it's a good way to keep an identical backup of a file.
To copy a file, use the command:
cp old new
               
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 Window Settings 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.
By default, Terminal uses tcsh as its shell. If you'd like to configure it to use a different shell, you can do so by selecting Terminal Preferences and specifying the shell to use.
To change the display preferences in the Terminal application, go to the Terminal menu and choose Window Settings.... You see a display similar to Figure 4-1.
Figure 4-1: Shell Settings
At the top of the window, notice that a drop-down list lets you select which options to configure: Shell, Processes, Emulation, Buffer, Display, Color, and Window. The names 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 only the current window unless you click "Use Settings as Defaults," after which they will apply to all future Terminal windows that you open.

Section 4.1.1.1: Shell

When you first open Terminal Preferences, the Shell settings are displayed, as shown in Figure 4-1. On this panel you can specify that when a login shell exits, the Terminal application can close the window, close the window only if the shell exited cleanly (that is, returned a nonzero status code, which means that all the applications gracefully shut down), or never close the window. If you like to study what you've done and want to be forced to explicitly close the Terminal window, "Don't close the window" is for you. Otherwise, either of the other two will work fine.
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.
By default, Terminal uses tcsh as its shell. If you'd like to configure it to use a different shell, you can do so by selecting Terminal Preferences and specifying the shell to use.
To change the display preferences in the Terminal application, go to the Terminal menu and choose Window Settings.... You see a display similar to Figure 4-1.
Figure 4-1: Shell Settings
At the top of the window, notice that a drop-down list lets you select which options to configure: Shell, Processes, Emulation, Buffer, Display, Color, and Window. The names 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 only the current window unless you click "Use Settings as Defaults," after which they will apply to all future Terminal windows that you open.

Section 4.1.1.1: Shell

When you first open Terminal Preferences, the Shell settings are displayed, as shown in Figure 4-1. On this panel you can specify that when a login shell exits, the Terminal application can close the window, close the window only if the shell exited cleanly (that is, returned a nonzero status code, which means that all the applications gracefully shut down), or never close the window. If you like to study what you've done and want to be forced to explicitly close the Terminal window, "Don't close the window" is for you. Otherwise, either of the other two will work fine.

Section 4.1.1.2: Processes

One of the more subtle capabilities of the Terminal application is that it can keep track of what applications you're running so it can be smart about confirming window close requests: if there's something still running in the window, it'll pop up a dialog box asking if you're sure you want to quit. This feature is very helpful if you are prone to accidentally clicking the wrong window element or pushing the wrong key sequence.
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 /etc (csh.login, csh.cshrc, and csh.logout). You only have permission to change these system-wide files if you use sudo (see Section 2.3). 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 ~/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 LESS tells the less program which options you want to set every time you use it. Not all commands recognize environment variables, but for those that do, this saves you the trouble of typing the options on every
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 4,700 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, 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 Mac OS X, where Print Center makes it a breeze to add new printers and configure your existing printers. Until the advent of the Common Unix Printing System (CUPS), the Unix environment has never had a printing interface that even comes close in usability. As of Mac OS X 10.2, Print Center and CUPS are combined in a way that brings joy to command-line and GUI lovers alike.
When you add a printer with Print Center, you'll only see some of the printer models that Mac OS X and CUPS support. To get access to advanced options, including extra print drivers, hold down the Option key when you click the Add button. To get even more printer drivers, download and install the Mac OS X release of gimp-print (http://gimp-print.sourceforge.net/). The gimp-print release is available as a disk image that includes a graphical installer.
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.
PostScript is a page description language supported by some printer models. PostScript printers were once the norm among Macintosh users, and still are popular. If you're using an inexpensive inkjet printer or a low- to mid-range laser printer, chances are good that your printer doesn't support PostScript. Some of the utilities described in this section require PostScript, others don't.
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
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.
PostScript is a page description language supported by some printer models. PostScript printers were once the norm among Macintosh users, and still are popular. If you're using an inexpensive inkjet printer or a low- to mid-range laser printer, chances are good that your printer doesn't support PostScript. Some of the utilities described in this section require PostScript, others don't.
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
-h header
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Non-PostScript Printers
The lpr command can handle a variety of file types, including PDF, plain text, and a variety of image types (JPEG, TIFF, and others). If your printer does not support PostScript, you will not be able to use lpr to print PostScript files directly. This also means that you won't be able to use enscript for printing.
However, if you've installed Fink (see Section 8.1), you can install the ghostscript package and run ps2pdf to turn your PostScript file into a PDF. To run enscript on the food file, convert it to PDF, and print it, use pipes between enscript, ps2pdf, and lpr:
% enscript -o - food | ps2pdf - - | lpr
         
The -o - switches and the pipe symbol (|) tell enscript to send its PostScript output to the ps2pdf program. The - - options and the pipe tell ps2pdf to read its input from the pipe and send its output to lpr, which sends the PDF to the printer. For more information on pipes, see Chapter 6.
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 vi 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. tr (character translator) is such a program. Here's how to use the input redirection operator to convert commas to linefeeds in the to_do file:
% cat to_do
Install Mac OS X,Learn Unix,???,Profit!
% tr ',' '\n' < to_do
Install Mac OS X
Learn Unix
???
Profit!
%
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.
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. tr (character translator) is such a program. Here's how to use the input redirection operator to convert commas to linefeeds in the to_do file:
% cat to_do
Install Mac OS X,Learn Unix,???,Profit!
% tr ',' '\n' < to_do
Install Mac OS X
Learn Unix
???
Profit!
%
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:
cat file(s)
               
For example, let's display the contents of the file /etc/csh.login. This system file is the global login file for tcsh and csh.
% cat /etc/csh.login
# System-wide .login file for csh(1).

setenv PATH "/bin:/sbin:/usr/bin:/usr/sbin"
%
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: remotely accessing your Mac from other computers and copying files between computers.
There may be times when you need to access your Mac, but you can't get to the desk it's sitting on. If you're working on a different computer, you may not have the time or inclination to stop what you're doing, walk over to your Mac, and log in (laziness may not be the only reason for this: perhaps someone else is using your Mac when you need to get on it or perhaps your Mac is miles away). Mac OS X's file sharing (System Preferences Sharing) can let you access your files, but there may be times you want to use the computer interactively, perhaps to move files around, search for a particular file, or perform a system maintenance task.
If you enable Remote Login under System Preferences Sharing, you can access your Mac's Unix shell from any networked computer that can run SSH (http://www.ssh.com), OpenSSH (http://www.openssh.org), or a compatible application such as PuTTY (a Windows implementation of SSH available at http://www.chiark.greenend.org.uk/~sgtatham/putty/). SSH and OpenSSH can be installed on many Unix systems, and OpenSSH is included with many Linux distributions as well as Mac OS X.
Figure 7-1 shows how remote login programs such as ssh work. In a local login, you interact directly with the shell program running on your local system. In a remote login, you run a remote-access program on your local system