Terminal Preferences and Configuration

 < Day Day Up > 

Interacting with Unix: Basic Unix Commands

You've already learned how to interact with Unix using Mac OS X's Aqua interface and the GUI tools discussed throughout the earlier chapters of this book. Much of the rest of the book provides the information you need to interact with Unix textually, through the command line. Unix commands, programs, and applications are all run by typing their names at the command line. The remainder of this chapter covers what you need to know to start interacting with the command line and how to get help for what you're trying to do.

Introduction to the Unix Shell

As mentioned previously, a terminal alone isn't sufficient to enable you to interact with your machine. The terminal needs something to talk to, and that thing is usually a program called a shell. Unix shells provide text-based interaction between the user and the rest of the operating system. For those who have experience with the DOS environment, you can think of a Unix shell as similar to a very powerful version of COMMAND.COM. Please don't let that put you off. COMMAND.COM does not approach being a fair comparison for a Unix shell, but both do let you type commands to the computer.

Although it is text-based, you can think of a shell running in a terminal as sharing a few conceptual similarities with a Finder window.

Any running shell can be thought of as "being in a place" in the filesystem, just as a Finder window is open to a certain folder in the system. This place is the current working directory.

Each shell can navigate through the filesystem by moving to parent or higher-level directories, or by moving to child or lower-level directories. Again, this is much like the functionality provided in each Finder window, by command-clicking the folder icon to reveal the enclosing folder structure or clicking a folder displayed in the window to navigate to an enclosed folder.

Unlike a Finder window, a shell in a terminal is not restricted to running a command that is present in the same directory that the terminal is "at" it can run commands located anywhere on the machine.

Also unlike Finder windows, shell commands that you execute in terminal windows (usually) run within the Terminal window, and they (usually) consume the resources of the shell such that the shell becomes "preoccupied" and can't run another command until the current one finishes (although you can always open another Terminal window to launch another shell to work in while other commands complete).

Most flavors of Unix come with a number of different shells from which the user can choose, and the BSD version underlying Mac OS X is no exception. With Mac OS X, you can choose from the following five shells, or possibly more, if Apple or another source makes them available.

  • sh The Bourne shell. The Bourne shell is ubiquitously available on Unix, but does not have syntax or features particularly friendly to the user. It is most frequently used for writing shell scripts (programs written to run using the shell language itself, rather than a more traditional programming language; how to write them is covered in Chapter 15, "Shell Configuration and Programming (Shell Scripting)") that are expected to run on any version of Unix. Sometimes it is used for the login shell of particularly important accounts, such as root.

  • csh The C shell (yes, it's pronounced seashell). The csh shell is a more user-friendly shell that takes its name from the C programming language. csh syntax is similar to the C language, and it provides significant power for both shell programming and for users. csh is almost as omnipresent as sh, and considerably less annoying to use.

  • tcsh Enhanced C shell. Many people considered csh to have been a botched implementation in a number of ways and wanted something with similar syntax, but less broken. tcsh was born to fix the bugs, and extend the functionality, of csh and includes nice features such as automatic command completion and a command history. tcsh is appearing as a standard available on more and more distributions, but although it's a frequent favorite for day-to-day use as a login shell, many traditional Unix users are still shy of using it for writing shell scripts that they might want to distribute widely. Early versions of Mac OS X used tcsh as the default shell, but with Panther, the default switched to bash.

  • bash The Bourne again shell (and yes, Unix programmers frequently have a twisted sense of humor). The Bourne again shell is a modern shell that takes the enhancements that make csh and tcsh more useful for user interaction and implements them in a shell with the sh syntax. bash is popular among Linux users because it's the default login shell for many Linux distributions. bash users and tcsh users tend to engage in heated and sometimes hostile debate over their shells of choice; bash users tend to think of tcsh as an undisciplined and poorly arranged set of hacks that is unsuited for any but the most trivial day-to-day tasks, and tcsh users tend to think of bash as a product of zealots who are unable to see the utter misanthropy of the interface they've designed.

  • zsh zsh is designed to be an interactive user shell that incorporates powerful programming features. The intent in its creation seems to have been to build an amalgam of the most powerful features of the other shells, and to introduce a number of new features as well. The shell has been described as suffering from "feeping creaturism" (see the Jargon File, sometimes called the "Hacker's Dictionary" available at http://www.catb.org/jargon/html/F/feeping-creaturism.html, among a plethora of other locations), and of having a few more features than even the author knows about.

Despite the fact that you'll find references and diatribes on the Internet that make the issue seem to take on almost religious significance, shell preference is just that, personal preference. There are well-considered reasons for picking any of them, and a user's personality as well as the type of work that he is doing ultimately dictates the shell environment in which he'll be most effective and happy. Starting with 10.3, Apple chose to make bash the standard shell for Mac OS X. The previous default was tcsh, and the change will aggravate a great many users because many do not like the syntax of sh. Thankfully, if you have a preference for a different shell, changing yours is a simple matter of resetting a terminal preference or a NetInfo setting. On the other hand, being forced to perform day-to-day work in the same shell language that you would need to use if you wanted to distribute your work to users of other systems is a strong plus for bash because its syntax is based on sh.

Examples in this book are shown using the default bash shell in most places, with tcsh samples where the usage diverges significantly. Regardless of what shell you choose, interaction with each is similar. To issue a command to the computer using a shell, you type the name of the command and press the Return key. In general, the command you requested will be executed by the shell and that shell will be occupied until the command is finished. After the command finishes executing, you'll be returned to the shell prompt. If the command requires additional information, it might be required on the command line in the form of flags or arguments, or interactively in the terminal as the program runs. Flags are usually individual letters or words preceded by a dash (-) that indicate the turning on or off of an option; arguments are words or data provided on the command line for the command to process. Some commands also require that data be provided at internal prompts or data entry areas created by the command when it is run. As mentioned previously, we'll discuss more complex programs and applications in following chapters.

NOTE

When documenting commands throughout the book, we will use the following syntax:

 commandname <required options> [optional options] <arg1> <arg2> 

and

 commandname <required> [optional] <arg1> <arg2> ... 

These mean that you type commandname at the prompt, must choose one or more entries from the <required parameters>, and may choose one or more options from the [optional options]. In the first invocation form, two additional required arguments are expected on the command line; in the second, the command accepts a variable number of arguments. In general, single-letter flags (options or parameters), usually preceded by a - (minus) sign, when enclosed in <> brackets are required, and when enclosed in [] brackets are optional. The brackets shown in the syntax examples are not actually entered on the command line they are shown only to distinguish required parameters and optional options. Arguments are required if shown, and an alternative form of the command is displayed with no parameters or arguments if this is also an allowable syntax. Options or parameters separated by a vertical bar, |, are exclusive; you must, or may, pick one or the other (depending on whether they're required or optional), but you cannot specify both.

For example, the fictitious command documentation shown in Table 9.1 indicates that a command named silly can be invoked as silly, silly -L, and silly -P. Invoked as silly, it does the same thing as silly -L; that is, it makes a silly laugh. Invoked as silly -P, it makes a silly picture. Each form also can be called with an arbitrary number of filenames following the command, in which case silly will place its output in the specified files.

Table 9.1. Command Documentation Table for the Fictitious silly Command

silly

Does something silly, optionally into files.

silly [-L|P] <filename> <filename2> ...

silly [-L|P]

 

-L

Default: Makes a silly laugh.

-P

Makes a silly picture.



Please be aware that the command documentation tables we've provided here are abstracted from the documentation, experimentation on the system, and our experience. Sometimes things don't really work quite like the online manual pages say that they do. Sometimes they include documentation for ridiculous options that you are unlikely to want to know about (for example, the man command, discussed later in this chapter, includes a -d option that means "Don't actually display the man pages, but do print gobs of debugging information"). We're correcting the documentation where necessary, simplifying it where possible, and leaving out many of the options that you probably don't care about in the tables themselves. If you see options listed in the syntax section, but not described in the rest of the table, these are probably items that seemed unlikely to be useful to most readers. If it seems that the command ought to do something that it can't quite do with the available options, check the built-in man pages, because it's always possible that we omitted exactly the option you're looking for. We'll do our best to keep our online PDF appendix complete with updated man pages that document all command options, even the seemingly useless ones, as well.

Shell Rules and Conventions

In dealing with the shell, it helps to remember a few rules. The first rule you need to know is that things that you type in Unix are case sensitive. This includes commands. Unlike with Mac OS and Windows, you cannot mix case and still have a command function. You must type the name exactly as it is stored on the system. Mac OS X has the option (the default, actually) of using HFS+, which isn't case sensitive, but this creates some odd behavior in its interaction with the BSD subsystem. There are classical Unix commands included in the BSD subsystem that have names that differ only by capitalization and that normally do different things. For example, Mail and mail are two different traditional Unix programs, and they traditionally have different functionality (both deal with email, but do different things). On Mac OS X installed over an HFS+ filesystem, it is indeterminate which program runs when you type mail (or Mail) at the command line. Apple has gone a long way to making the capitalization issue transparent to the user, but there are still places where capitalization sensitivity (or lack thereof) comes back to bite people. Because there's no obligation for Mac OS X to be running on HFS+, and it's quite possible that you will be mounting drives from other machines that aren't running Mac OS X at all, you really should treat everything in the BSD subsystem as though it were case sensitive, even if your installation actually isn't. It might seem initially inconvenient to remember the exact capitalization that's been used for various commands (really, they're almost all lowercase, so it's not that difficult), but with time it will become second nature to you. Regularly practicing good form with respect to case specificity will almost certainly save you considerable headaches eventually.

Next, when you type at the command line, characters that you type become part of the command. Most alphanumeric characters, as well as underlines and hyphens, are valid parts of commands. Most symbols aren't valid parts of commands, and some have special meanings to the command line. Table 9.2 shows some of the symbols with special meaning to the command line.

Table 9.2. Command-Line Symbols

Symbol

Meaning

*

When used as part of a filename, the * character substitutes for zero or more characters in a filename. This is called a wildcard. For example, specifying a filename of *.gif as an argument to a command-line program tells the shell to search the current directory for all files that have names ending in .gif and substitute all these filenames on the command line at this point in the command.

?

A single-character wildcard. Functions like *, except that it substitutes for a single character in filenames, instead of any number of characters. If you need some specific number of wildcarded positions, you can use multiple ? characters, one for each wildcard substitution.

Tab

If you press the Tab key at the command line, the shell attempts to complete the command for you. If the portion of the command or filename that you've typed is unique, the shell fills in the rest of the information for you. For example, if you're in your home directory, and you want to specify the Documents directory on the command line, typing Docu and then pressing the Tab key will most likely fill out the command line to include the full Documents name.

space

Unix interprets a space between words on the command line as a separator between parts of the command. This is not always what you want because Macintosh filenames can have spaces. The Unix command line usually interprets the space in a Mac filename such as My File as indicating two different files: one named My and one named File.

\

The shell escape character. If you need to insert a character into a Unix command or filename that is usually interpreted by the shell (such as a space or * character), you can place the \character before the character that would usually be interpreted by the shell. This is called escaping the special character. You frequently see this on the command line to specify Mac filenames such as My File, which in Unix must be specified as My\ File.


NOTE

Note that you can use the shell escape character \to allow inclusion of usually special characters into a single command argument, or, alternatively, you can often place the argument in quotes. Therefore, if you wanted to list the directory My Big Directory, you could either specify it as My\ Big\ Directory, or as "My Big Directory" when used in a command. Although the quoted version is a little easier to read, we recommend familiarizing yourself with the escaped version because this is what the shell will use when automatically expanding arguments when you press the Tab key.


Most useful shells provide a history mechanism whereby previous commands can be recalled and reused. Previous commands may be recalled to the command line by use of the up arrow key. If you need the last command you typed, just press the up arrow key, and it will be recalled to the command line. You can rotate through the command history with the up arrow and down arrow keys to pick the command you need.

The command line also provides editing capabilities. You can use the left arrow and right arrow keys to move around in the command line currently displayed, and edit it by typing new characters or deleting existing characters with the Delete key. This also applies to commands that you've recalled via the command history with the arrow keys.

When you type a command, the system searches for a command with that name in the list of directories known as the PATH. This is done because a complete search of the entire filesystem could take a long time, and restricting the portions of the filesystem examined to only a small subset speeds up things significantly. Unfortunately, the current directory, where the shell "is," isn't necessarily in the PATH. Because of this, you might be in a directory named /Users/wizbot/spin/, and there might be a command named spinnin in the directory, but typing spinnin produces only the error command not found. In this case, you can run the command by specifying either the full name of the path to the command (/Users/wizbot/spin/spinnin), or by specifying the relative path to the command (./spinnin). You can also solve the problem by adding the path to the directory holding spinnin to the PATH list, or by adding the current directory to the PATH. You learn about this and more in Chapter 15. You also learn considerably more about paths in the immediately following sections, covering the filesystem and basic navigation.

CAUTION

Understanding the location of command executables with respect to the current directory is one of the most common problems that new users encounter at the command line. It is quite common to see a user become furious at a shell prompt because it insists on reiterating command not found when the user types the name of a command. They'll demonstrate that the command most certainly does exist by listing the contents of the directory, and pointing out that it's right there, plain as day. The fact that the places that the shell itself looks to find commands might not include that directory, seems insidiously hard to remember, and we've seen some users return a half-dozen times to ask the same question of other commands, before they truly understood the necessity of specifying either the full path, or ./<commandname> for commands in the current directory.

The difficulty isn't limited to novice users, either. We've seen professional programmers who ought to be able to teach classes on this material, befuddled for days by a slight variant of this error, and even after almost 20 years of working daily with the command line, still experience brief moments of annoyance with this issue ourselves.

Some might wonder, given that we're saying this is a common complaint, why we don't simply recommend adding the current directory to the list of places a shell should look for commands. This is a security-related issue, and while on the surface it sounds like an appealing idea, it's actually a rather dangerous practice. Adding the current directory to the PATH, allows a malicious user to install a trojan horse that has the same name as a real command, that will accidentally be executed instead of what you intended, if you happen to be in the same directory as it is when you attempt to execute the command you wanted. This also has the side effect (which kept our professional programmer mentioned above occupied for a whole weekend) that if you're used to a command running from your current directory, and a command by the same name gets added elsewhere in the system, it might start executing instead when you type its name.

All in all, it's safest to leave the current directory out of your path, and remember to use ./ in front of commands that you want to execute in your current directory.


Occasionally, you might do something that leaves your shell in an apparently unusable state. Frequently, this is because you've started a process that is expecting input from you. If you don't have the appropriate information to give it to keep it happy, you can try several key combinations that might help you regain control of your shell:

  • Ctrl-D This key combination sends an End Of File (EOF) signal to the current process, usually terminating input. If the process is designed to continuously accept data until reaching the EOF, sending it this key combination causes it to stop accepting input and go about whatever it was designed to do next.

    CAUTION

    Be careful with Ctrl-D. If you're not currently running a process in the shell, you'll send the EOF to the shell itself, which tells it that you're finished sending input (typing commands to it) and it will summarily stop. If you've set your Terminal preferences to close the window when the last process running in it stops, that Terminal window goes away as well.


  • Ctrl-Z This key combination suspends the current foreground process (more on foreground and background processes in Chapter 12. The process won't continue to run; it simply sits there in suspended animation until you either close the shell (perhaps by logging out), thereby killing it, or until you reenable it using one of the techniques discussed in "Process Management."

  • Ctrl-C This key combination is the Unix break character. This usually (you can configure the behavior) kills the current process and returns you to the shell prompt.

Don't be afraid to test the commands shown in this book. The system can do a pretty good job of protecting itself from anything a normal user can type, and we'll be sure to place conspicuous warnings with any commands capable of causing mischief in any case. With a little experimenting, we think you'll find that you can do a surprising number of things with only a few keystrokes.

Issuing Commands

So, now that we've taken all that time to provide background on using the shell, you might think that this is going to be confusing, intimidating, or difficult. It's not. It might seem confusing for a bit, but it's not difficult, and if you don't let it become intimidating, you'll find that you can quickly pick up techniques that make day-to-day use of your machine more convenient and productive. There's absolutely no need for you to learn everything that you can do with the shell all at once. As a matter of fact, there's no need to learn more than a handful of commands and techniques at any one time. We've written this section of the book as though you were going to start it as a shell novice, and graduate after seven chapters as an experienced shell programmer. Next to nobody is going to follow that path. This, however, isn't a bad thing; almost nobody follows anybody else's path with learning to use the command line, except in a very general sense.

You start off doing a few things that are useful to you, and as you become proficient with those, it's natural to start adding new abilities and knowledge to your repertoire. Exactly what you learn when isn't really at all important. We've presented the material in an order that we think makes learning to use most commands and utilities (including ones that we haven't room to cover in this book) straightforward, but don't feel that you need to learn it all before you can start utilizing what you've learned. Unless you really want to, don't even try to learn it all before you become comfortable with the parts that help you right now, with whatever you're regularly doing.

That being said, what exactly does this Terminal and shell thing do? It gives you a place to type things, and a place for the machine to respond. Before we get started on specifics, let's look at the sorts of things you can do in a shell running in Terminal. First, when you start Terminal, it gives you a friendly message and a prompt indicating that it's time for you to type something:

 Last login: Sat Sep 20 22:50:19 on console Welcome to Darwin! /Volumes/Wills_Data/ray bash-2.05a$  

That's not too interesting. What's the point of telling me what version of bash I'm running. If I cared, I could probably ask it, right? Let's make that prompt into something more useful. How about our machine name, our username, and the directory we're currently in:

 bash-2.05a$ PS1='\h:\u \W \$ ' brezup:ray ray $ 

Well, that's a little better, at least now I know who and where I am when I look at the terminal. PS1 is a shell variable that customizes your prompt. \h calls out your machine name, \u calls out your username, \W (capitalization is important) calls out the name of the current directory, and \$ places the traditional bash $ character at the end of the prompts. If you're following along, believe it or not, you're customizing your shell environment already. It's not quite the same type of tweaks that you can get out of the Appearance control pane, but this is exactly the sort of small utility command that makes your life easier. And you don't need to read all the way up to Chapter 15 where we cover many other variables like PS1 that can be set to make your life easier, for you to start making productive use of what you know now. We use this prompt (and a slight variation on it) throughout the book.

So now you've customized a bit of your environment. What sort of useful things can you do now? How about a calendar?

 brezup:ray ray $  cal 2005                               2005                                     January               February               March          S  M Tu  W Th  F  S   S  M Tu  W Th  F  S   S  M Tu  W Th  F  S                    1         1  2  3  4  5         1  2  3  4  5  2  3  4  5  6  7  8   6  7  8  9 10 11 12   6  7  8  9 10 11 12  9 10 11 12 13 14 15  13 14 15 16 17 18 19  13 14 15 16 17 18 19 16 17 18 19 20 21 22  20 21 22 23 24 25 26  20 21 22 23 24 25 26 23 24 25 26 27 28 29  27 28                 27 28 29 30 31 30 31        April                  May                   June          S  M Tu  W Th  F  S   S  M Tu  W Th  F  S   S  M Tu  W Th  F  S                 1  2   1  2  3  4  5  6  7            1  2  3  4  3  4  5  6  7  8  9   8  9 10 11 12 13 14   5  6  7  8  9 10 11 10 11 12 13 14 15 16  15 16 17 18 19 20 21  12 13 14 15 16 17 18 17 18 19 20 21 22 23  22 23 24 25 26 27 28  19 20 21 22 23 24 25 24 25 26 27 28 29 30  29 30 31              26 27 28 29 30         July                 August              September        S  M Tu  W Th  F  S   S  M Tu  W Th  F  S   S  M Tu  W Th  F  S                 1  2      1  2  3  4  5  6               1  2  3  3  4  5  6  7  8  9   7  8  9 10 11 12 13   4  5  6  7  8  9 10 10 11 12 13 14 15 16  14 15 16 17 18 19 20  11 12 13 14 15 16 17 17 18 19 20 21 22 23  21 22 23 24 25 26 27  18 19 20 21 22 23 24 24 25 26 27 28 29 30  28 29 30 31           25 26 27 28 29 30 31       October               November              December        S  M Tu  W Th  F  S   S  M Tu  W Th  F  S   S  M Tu  W Th  F  S                    1         1  2  3  4  5               1  2  3  2  3  4  5  6  7  8   6  7  8  9 10 11 12   4  5  6  7  8  9 10  9 10 11 12 13 14 15  13 14 15 16 17 18 19  11 12 13 14 15 16 17 16 17 18 19 20 21 22  20 21 22 23 24 25 26  18 19 20 21 22 23 24 23 24 25 26 27 28 29  27 28 29 30           25 26 27 28 29 30 31 30 31 

Know another quick way to get a calendar for all of any year with only eight keystrokes?

How about a peek at how long your machine's been running?

 brezup:ray ray $ uptime  0:04  up 11 days,  4:56, 8 users, load averages: 0.10 0.03 0.01 

Not only does it tell me how long it's been booted this time around (only one hour, two minutes right now), but also how many users are using the system, the time, and how hard the processor's working (.16 processes running during the command's averaging period, which is not working too hard at all).

How about what your current IP address is and the state of your network?

brezup:sageray Documents $ ifconfig -a lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 inet6 ::1 prefixlen 128 inet6 fe80::1 prefixlen 64 scopeid 0x1 inet 127.0.0.1 netmask 0xff000000 gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280 stf0: flags=0<> mtu 1280 en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 inet6 fe80::230:65ff:feaa:37ae prefixlen 64 scopeid 0x4 inet 192.168.1.19 netmask 0xffffff00 broadcast 192.168.1.255 ether 00:30:65:aa:37:ae media: autoselect (10baseT/UTP <half-duplex>) status: active supported media: none autoselect 10baseT/UTP <half-duplex> 10baseT/UTP <full-duplex> 10baseT/UTP <full-duplex,hw-loopback> 100baseTX <half-duplex> 100baseTX <full-duplex> 100baseTX <full-duplex,hw-loopback> fw0: flags=8822<BROADCAST,SMART,SIMPLEX,MULTICAST> mtu 2030 tunnel inet --> lladdr 00:30:65:ff:fe:aa:37:ae media: autoselect <full-duplex> status: inactive supported media: autoselect <full-duplex>

Okay, so there's a bunch of information that you're not interested in there, but buried in the middle is a line that says inet 192.168.1.19, which is my current IP address. Actually, a couple of lines look like that, because those are all valid IP addresses by which this machine knows itself (127.0.0.1 exists on every machine, and always points back to itself). There's a 426-kilobyte application that you can find on the net that can retrieve this information and show it to you when you double click it. Is the convenience of double-clicking worth the difference between 11 keystrokes and 426KB? Okay, so maybe the trouble of looking through that output is worth spending some disk space on. What if we add 15 more keystrokes (for a total of 26), and get the output down to only the IP address lines?

 brezup:sageray Documents $ ifconfig -a | grep "inet "         inet 127.0.0.1 netmask 0xff000000          inet 192.168.1.19 netmask 0xffffff00 broadcast 192.168.1.255         tunnel inet  -->  

Still worth nearly half a megabyte of disk space? Well, the 426KB application also can monitor your IP address and email you when it changes, but by the time you're finished with Chapter 15, you'll know how to add that capability to what you've seen here, and how to store it as your own little application that you can run with whatever name you care to call it. This'll cost you a one-time payment of another 100 or so keystrokes, depending on the length of your email address. It's rarely the functionality that takes up the room in these sorts of utility applications. Instead it's all the additional trimmings that must be layered around a simple utility to make it into a nice double-clickable GUI-driven application.

Hardly a day goes by when we don't see one or more utilities that someone's published for Mac OS X that aren't amazingly overcomplex and oversize for the capabilities that they bring to the end user. It's truly wonderful that people are willing to write little applications that perform useful actions and post news about them on macnn.com, and we wish their authors only the best. But it would often be of much more use for the author to just show the handful of lines of shell commands necessary to duplicate the effect. You can help change this landscape and further educate yourself at the same time, by learning how to construct simple utilities yourself (which you will be doing before you know it), and by urging utility authors to tell you how they did it, instead of just asking for impenetrable double-clickable applications.

Other command-line commands that you learn about in this and the following chapters are usually similarly designed. They do some small utility task, but they do it flexibly, and with a minimum of muss, fuss, or effort. By the end of Chapter 15 you will learn how to string them together into arbitrarily complex collections of commands that perform custom operations for you, and that can make use of your computer significantly more enjoyable and productive. Remember as you read through these chapters that it's not imperative for you to learn all the commands as you read about them. We've presented the commands in such an order that the topics build on each other, so paying attention to the general concepts helps a lot, but a multitude of commands are available in the shell, and even the most experienced Unix users rarely use more than a few percent on a regular basis.

Getting Help Through Online Manual Pages

The very first command that you should become familiar with is the man (manual) command. All good Unix systems provide an online collection of manual pages that detail almost every command available in the system. Mac OS X is no exception. Simply type man <commandname> at any shell prompt, and if there is a manual page documenting the command, it will be shown to you. For example, to see the man pages for the date command (which tells you the date and time), you could type

 brezup:sage Documents $ man date DATE(1)                   BSD General Commands Manual                  DATE(1) NAME      date -- display or set date and time SYNOPSIS      date [-nu] [-r seconds] [+format]      date [-u] mmddhhmm[[cc]yy] DESCRIPTION      date displays the current date and time when invoked without arguments.      Providing arguments will format the date and time in a user-defined way      or set the date.  Only the superuser may set the date.      The options are as follows:      -n      The utility timed(8) is used to synchronize the clocks on groups              of machines.  By default, if timed is running, date will set the              time on all of the machines in the local group.  The -n option              stops date from setting the time for other than the current              machine.      -r      Print out the date and time that is seconds from the Epoch.      -u      Display or set the date in UTC (universal) time.      An operand with a leading plus (``+'') sign signals a user-defined format      string which specifies the format in which to display the date and time.      The format string may contain any of the conversion specifications      described in the strftime(3) manual page, as well as any arbitrary text. : 

TIP

If your terminal shows you a line that says more at the bottom of the window, a pathname and a percentage figure, or simply a : character, it means that there is more output to be seen. Press the spacebar and the next page of output scrolls into view. Which of the versions is displayed depends on what pager is being used. The first two are displayed when the pager is more, but : is displayed when the pager is less. If less is used as the pager, you will be able to search the man pages. As of Mac OS X 10.3, the functionality of more has been wrapped into an enhanced version of less, though both behaviors remain available to the user. The most important operating characteristics of both are discussed in the next chapter.


There's a vast quantity of information available in the man pages, books and books worth of it. In 1993, I had a complete printed set of the man pages that were shipped with an early version of Sun Microsystems' flavor of Unix. These manuals completely filled a 4-foot by 6-foot bookcase of 8.5x11 three-ring binders, and the quantity of information provided in the man pages has only been expanding. Once upon a time, this quantity of information was actually a significant burden to store on expensive and scarce disk space, and so it was stored in a mildly compressed format that wasn't easily human-readable, and the man page reading software was written to unpack this data and display it as necessary. Processors weren't so fast back then either, so the "unpack and display" step made the process a little slower than most people liked. To accommodate, the system was also designed to allow a duplicate set of man pages, in an unpacked format as well, which could be transparently (and more quickly) pulled up if they were available on the system, and an additional database of keywords and important terms that could be searched to find related man pages.

For reasons seemingly lost in the depths of time, someone also made the decision that the creation of a searchable database for the man pages would be left to the same process as the act of unpacking (known as "formatting") the man pages. The result of this is that now, even as machines have become fast enough that on-the-fly formatting is an imperceptible delay, and the disk space occupied by uncompressed (formatted) copies is insignificant, we're still saddled with a man system where man pages are typically delivered in a file format in which they can't be easily read or searched, and where creating a searchable version usually requires an additional step beyond what comes native on your machine. Thankfully, modern systems such as Tiger can build the keyword database independently of the formatted man pages, so now updating the database is at least a more convenient process.

By default, Mac OS X is delivered without formatted man pages, and without the database of keywords and terms built. Apple's Xcode (Developer Tools) installer now takes the initiative to run the formatting and database-building commands when it finishes the install process, but this doesn't mean that you no longer need to know about the process because other software that you might install on the system probably won't insert its information into the database or run preformatting commands. Because of this you can end up in a situation where some of your man page system is searchable, and some invisible to the search software. You can only remedy this by running the database building commands manually yourself when you install new software that adds pages to the man page system, or by running Apple installers that update the system as part of their installation process.

If you needed to build the searchable database for your Apple-supplied man page collection, either because you haven't installed the XCode distribution or because you'd like to update the pages with additional information that has been recently installed, you can do it like this:

 brezup:ray Documents $ sudo makewhatis -v Password: man directory /usr/share/man   /usr/share/man/man1         reading /usr/share/man/man1/open.1         reading /usr/share/man/man1/slp_reg.1         ignoring junk description ""         reading /usr/share/man/man1/slpd.1         ignoring junk description ""         reading /usr/share/man/man1/authopen.1         reading /usr/share/man/man1/hdiutil.1         reading /usr/share/man/man1/createhomedir.1 ... <lots of output deleted>         reading /usr/share/man/mann/while.ntcl         reading /usr/share/man/mann/Widget.n         reading /usr/share/man/mann/winfo.ntcl         reading /usr/share/man/mann/wm.ntcl         reading /usr/share/man/mann/yencode.n         reading /usr/share/man/mann/zero.n         reading /usr/share/man/mann/zip.n brezup:ray Documents $ 

That might look like a lot of output, but the only really important thing is that it didn't toss up any serious errors, and that it came back to the command prompt when it finished. Many commands produce a wealth of diagnostic information when they're run, in addition to performing their intended function. Mostly, as with this, unless you're really interested in the intermediate steps and status, you can just ignore it.

Even if Apple's XCode install has already run the makewhatis step for you on the man page set Apple provides, you won't hurt anything if you decide you'd like to run it again yourself. You'll eventually want to run makewhatis on the /usr/local/man directory into which most third-party Unix applications will install their man pages (sudo makewhatis /usr/local/man) so that non-Apple man page information is searchable as well. When you run this command, don't worry too much about the warning messages that you see. So long as the warning messages don't suggest that something went terribly wrong everything is working okay.

NOTE

For the inquisitive, the sudo command used at the beginning of the examples here is used to cause the command that follows it to run with root (administrative) privileges. If you have enabled the root account, you could also do this by using the su command to switch to a shell running as the root user, which is an even more powerful administrative user than the normal Mac OS X Admin user group. We don't recommend that you spend much time in an sued shell because you can do a lot of damage in this mode, but some way to run commands as root is required for doing certain sorts of maintenance like this. We cover the advantages and disadvantages of sudo and su, and the intricacies and requirements for their use, in later chapters.

The makewhatis command that follows the sudo command is the name of a program that does the actual uncompressing, and indexing of the contents of the compressed man page data files. Using sudo before the command allows it to run with the permissions it requires to do the job in directories where your user ID would normally not be allowed to write.


After you have a formatted man page set (the default for Apple's man pages, if you've installed Xcode, but remember you'll need to format your own for other software you install), you can use the -k option to man. (This is equivalent to the apropos command; wherever you see man -k, you can substitute apropos, if that's easier for you to remember. There's also a similar program, whatis, that works just like these, but constrains the results to only whole-word matches of the query.) This option searches the man pages for pages with keywords matching what you've entered. For example, if you want to know which man pages might have information on the subject of time, you could issue a man command like this:

 brezup:ray Documents $ man -k time BIO_f_ssl(3o), BIO_set_ssl(3o), BIO_get_ssl(3o), BIO_set_ssl_mode(3o) ... Benchmark(3)             - benchmark running times of Perl code CPAN::FirstTime(3), s-1CPAN:s0 - Util for s-1CPAN:s0:Config file Initialization ... Time::localtime(3) - by-name interface to Perl's built-in localtime() function Time::tm(3) - internal object used by Time::gmtime and Time::localtime ac(8)                    - display connect time accounting adjtime(2) - correct the time to allow synchronization of the system clock alarm(3)                 - set signal timer alarm ... sleep(1)                 - suspend execution for an interval of time ... strftime(3)              - format date and time time(1)                  - time command execution time(3)                  - get time of day time2posix(3), posix2time(3) - convert seconds since the Epoch times(3)                 - process times timezone(3)              - return the timezone abbreviation touch(1)                 - change file access and modification times tzfile(5)                - time zone information tzset(3)                 - initialize time conversion information ualarm(3)                - schedule signal after specified time uptime(1)                - show how long system has been running utime(3)                 - set file times utimes(2)                - set file access and modification times vtimes(3)                - get information about resource utilization zdump(8)                 - time zone dumper zic(8)                   - time zone compiler ... 

This command lists each of the man pages that the system knows about that match the keyword (in this case, time) that you've requested. We've used ellipses in the output shown here to limit the output to only some of the most interesting time-related functions and commands you might want to know about. The listing you'll see when you run the command is (sometimes unfortunately) as comprehensive as your system can find, with respect to the query.

To be able to limit that listing down to just commands, or to just programming-library functions, or any of several other general categories of time-related information, it's important to know that the man page system has several sections into which the content is divided. Because of this, there might be commands that have multiple man pages, each in a different section. The system is divided into sections roughly segregated into the following topics:

  • Man1 Typical user commands. Documentation of commands that can be executed by the normal user at the command line.

  • Man2 System calls. Documentation of routines internal to the system that programmers can use in programs.

  • Man3 User-level library calls. Documentation of C and other library functions for programmers.

  • Man4 Device drivers, protocols, and network interfaces. Documentation of the internals of hardware support and software APIs for these items.

  • Man5 File formats. Documentation of file format details for both system control files and certain program data files.

  • Man6 Games and demos. Documentation for amusement software.

  • Man7 Miscellaneous. Various tables of useful information, such as ASCII tables.

  • Man8 Maintenance commands. Documentation for maintenance and system administration commands.

  • Man9 System kernel developer's commands. Documentation for system kernel developer commands.

CAUTION

The segregation of the man pages into the directories Man1 Man9 is not absolute. Third-party software providers have a bad habit of breaking convention and placing their man pages in inappropriate sections.

There are also a growing number of specialty sections that are devoted to the segregation of particular programming languages, or operating system features, and these have arbitrary names that aren't easily guessed. The only way that you might know, for example, that there is an ntcl section into which TCL scripting-language documentation is segregated, is because you notice (ntcl) appended to some of the commands that are related to your time query.


If you look at the earlier listing for the man -k time command, you will notice that each topic listed includes a number or letter in parentheses after the name of the topic. This is the man page section in which the item occurs. Unfortunately, although you can display man pages from specific sections by specifying the section before the item to read about (for example, man 1 time), there isn't a good way to tell man -k to search in only a particular section. This often makes the output of man -k less than appealing. By the time you learn how to use a few more features of the command line (the grep program and pipes, specifically), you'll know how to construct your own filters to select exactly the results you really want.

NOTE

Your system might not (and probably won't!) show exactly these same items. The available man pages depend on whether you've installed the developer toolkit and on any other software installed on the system. If the following examples using manual section 3 do not work for you, read through them now, and try them again after you've installed the developer tools (Chapter 14). We're including them here because we expect that many users will have "installed ahead," or are reading this book while trying to learn on a completely configured machine at work or school. If you're following along in a from-the-ground-up installation, bookmark this section on man pages, and try it out again after finishing the developer tools install.


To look at man pages in specific sections of the manual, specify the numeric or textual identifier for the section between the man command and the item you want to look up. For example, the system includes man pages for both the time command and the time() C library function. man time defaults to showing you the man page for the command-line related item, if one exists, so both man time and man 1 time show you the man page for the time command:

 brezup:ray Documents $ man time TIME(1)                   BSD General Commands Manual                  TIME(1) NAME      time -- time command execution SYNOPSIS      time [-lp] utility DESCRIPTION      The time utility executes and times utility.  After the utility finishes,      time writes the total time elapsed, the time consumed by system overhead,      and the time used to execute utility to the standard error stream.  Times      are reported in seconds.      Available options:      -l      The contents of the rusage structure are printed.      -p      The output is formatted as specified by IEEE Std 1003.2-1992              (``POSIX.2'').      The csh(1) has its own and syntactically different builtin version of      time.  The utility described here is available as /usr/bin/time to csh : 

The following man command produces identical results:

 brezup:ray Documents $ man 1 time 

If you want to know about the C library function named time(), however, you will need to look in the program-functions related section of the man pages, using man 3 time as your command:

 brezup:ray Documents $ man 3 time TIME(3)                  BSD Library Functions Manual                  TIME(3) NAME      time -- get time of day LIBRARY      Standard C Library (libc, -lc) SYNOPSIS      #include <time.h>      time_t      time(time_t *tloc); DESCRIPTION      The time() function returns the value of time in seconds since 0 hours, 0      minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without      including leap seconds.      A copy of the time value may be saved to the area indicated by the      pointer tloc.  If tloc is a NULL pointer, no value is stored.      Upon successful completion, time() returns the value of time.  Otherwise      a value of ((time_t) -1) is returned and the global variable errno is set : 

NOTE

If you add any software to the system, it might place man pages into the system man directories (located in /usr/share/man on OS X), or into the local man directories (located in /opt/man, /usr/local/man, or both). If you do this, you will need to rebuild the makewhatis database before the new manual pages will show up when you use the man -k option.


The man system is self-documenting, of course, so if you want to read further about the man command, simply type man man.

A command documentation table (our revised and sometimes corrected version of the man pages, with most esoteric or uninteresting options pared out) for man is shown in Table 9.3, which lists the syntax and selected options for man. The complete documentation table is located in Appendix A.

Table 9.3. Syntax and Selected Options for man

man

Formats and displays online manual pages.

man [-acdfFhkKtwW] [--path] [-m system] [-p string] [-C config_file] [-M pathlist] [-P pager] [-S section_list] [section] name ...

-a

Displays all the manual pages for a specified section and name combination. (The default is to display only the first page found.)

-d

Displays debugging information, rather than manual pages. Not really useful for the end user, but included here because it's important to understand the range of options that these commands typically provide.

-f <keyword>

Displays a list of manual pages that contain complete word matches to the <keyword>. Same as whatis.

-h

Displays the help for man.

-k <keyword>

Displays a list of manual pages that contain the <keyword>. Same as apropos.

-w

Lists the pathnames of manual pages that would be displayed for the specified section and name combination. Don't display the pages themselves.

-S <list>

Searches the specified colon-separated sections in <list>. Overrides MANSECT environment variable.


The optional <section> argument restricts man's results to the specified section. Multiple sections can be listed using the -S <section list> option, and providing a comma-separated list of sections to search.

As you can see, there are copious additional options that we aren't detailing here. These, again, are likely to be of minimal interest to most readers, and we direct your attention to the built-in versions for those cases where you might find it useful to know about such things as how to specify an alternative configuration file or an alternative location to search for man pages.

     < Day Day Up > 


    Mac OS X Tiger Unleashed
    Mac OS X Tiger Unleashed
    ISBN: 0672327465
    EAN: 2147483647
    Year: 2005
    Pages: 251

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net