Chapter 16. The Unix Crash Course

As you’re certainly aware by now, Mac OS X’s resemblance to the original Mac operating system is only superficial. The engine underneath the pretty skin is utterly different. In fact, it’s Unix, one of the oldest and most respected operating systems in use today. The first time you see it, you’d swear that Unix has about as much in common with the original Mac OS as a Jeep does with a melon (see Figure 16-1).

What the illustration at the bottom of Figure 16-1 shows, of course, is a command line interface: a place where you can type out instructions to the computer. This is a world without icons, menus, or dialog boxes. The mouse is almost useless here.

Surely you can appreciate the irony: The brilliance of the original 1984 Macintosh was that it eliminated the command line interface that was still the ruling party on the computers of the day (like Apple II and DOS machines). Most nongeeks sighed with relief, delighted that they’d never have to memorize commands again. Yet here’s Mac OS X, Apple’s supposedly ultramodern operating system, complete with a command line! What’s going on?

Actually, the command line never went away. At universities and corporations worldwide, professional computer nerds kept right on pounding away at the little C: or $ prompts, appreciating the efficiency and power such direct computer control afforded them.

You’re forgiven if your reaction to the idea of learning Unix is, “For goodness’ sake—can’t I finish learning one way to control my new operating system before I have to learn yet another one?”

Absolutely. You never have to use Mac OS X’s command line. In fact, Apple has swept it far under the rug, obviously expecting that most people will use the beautiful icons and menus of the regular desktop. There are, however, some tasks you can perform only at the command line, although fewer with each release of Mac OS X.

Top: What most people think of when they think “Macintosh” is a graphic interface (GUI)—one that you control with a mouse, using icons and menus to represent files and commands.Bottom: Terminal offers a second way to control Mac OS X: a command line interface, which you operate by typing out programming commands.

Figure 16-1. Top: What most people think of when they think “Macintosh” is a graphic interface (GUI)—one that you control with a mouse, using icons and menus to represent files and commands. Bottom: Terminal offers a second way to control Mac OS X: a command line interface, which you operate by typing out programming commands.

For intermediate or advanced Mac fans with a little time and curiosity, however, the command line opens up a world of possibilities. It lets you access corners of Mac OS X that you can’t get to from the regular desktop. It lets you perform certain tasks with much greater speed and efficiency than you’d get by clicking buttons and dragging icons. And it gives you a fascinating glimpse into the minds and moods of people who live and breathe computers.

If you’ve ever dabbled in Excel macros, experimented with AppleScript, or set up a Mac on a network, you already know the technical level of the material you’re about to read. The Unix command line may be unfamiliar, but it doesn’t have to be especially technical, particularly if you have some “recipes” to follow like the ones in this chapter.

Note

Unix is an entire operating system unto itself. This chapter is designed to help you find your footing and decide whether or not you like the feel of Unix. If you get bit by the bug, see Appendix D for sources of additional Unix info.

The keyhole into Mac OS X’s Unix innards is a program called Terminal, which sits in your Applications→Utilities folder (see Figure 16-2). Terminal is named after the terminals (computers that consist of only a monitor and keyboard) that still tap into the mainframe computers at some universities and corporations. In the same way, Terminal is just a window that passes along messages to and from the Mac’s brain.

The first time you open Terminal, you’ll notice that there’s not much in its window except the date, time and source of your last login, and the command line prompt (Figure 16-2).

For user-friendliness fans, Terminal doesn’t get off to a very good start; this prompt looks about as technical as computers get. It breaks down like this:

Unless you’ve fiddled with Terminal’s preferences, the insertion point looks like a tall rectangle at the end of the command line. It trots along to the right as you type.

An enormous number of programs have been written for Unix. And thanks to thousands of open-source developers—programmers all over the world who collaborate and make their work available for the next round of modification—much of this software is freely available to all, including Mac OS X users.

Each Unix command generally calls up a single application (or process, as geeks call it) that launches, performs a task, and closes. Many of the best-known such applications come with Mac OS X.

Here’s a fun one: Just type uptime and press Enter or Return. (That’s how you run a Unix program: Type its name and press Return.) On the next line, Terminal shows you how long your Mac has been turned on continuously. It shows you something like: “13:09 up 8 days, 15:04, 1 user, load averages: 1.24, 1.37, 1.45”—meaning your Mac has been running for 8 days, 15 hours nonstop.

You’re finished running the uptime program. The $ prompt returns, suggesting that Terminal is ready for whatever you throw at it next.

Try this one: Type cal at the prompt, and then press Return. Unix promptly spits out a calendar of the current month.

OfficeMac:~ chris$ cal
   September 2009
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

OfficeMac:~ chris$

This time, try typing cal 4 2010, cal -y, or cal -yj. These three commands make Unix generate a calendar of April 2010, a calendar of the current year, and a calendar of Julian days of the current year, respectively.

If you can’t see any icons for your files and folders, how are you supposed to work with them?

You have no choice but to ask Unix to tell you what folder you’re looking at (using the pwd command), what’s in it (using the ls command), and what folder you want to switch to (using the cd command), as described in the following pages.

The ls command, short for list, makes Terminal type out the names of all the files and folders in the folder you’re in (that is, your working directory). You can try it right now: Just type ls and then press Return. Terminal responds by showing you the names of the files and folders inside in a list, like this:

Desktop   Downloads Movies    Pictures  Sites
Documents Library   Music     Public

In other words, you see a list of the icons that, in the Finder, you’d see in your Home folder.

Note

Terminal respects the limits of the various Mac OS X accounts (Chapter 12). In other words, a Standard or Administrator account holder isn’t generally allowed to peek further into someone else’s Home folder. If you try, you’ll be told, “Permission denied.”

You can also make Terminal list what’s in any other directory (one that’s not the working directory) just by adding its pathname as an argument. Arguments are extra pieces of information after the command that refine how the command should run. (Remember the calendar example? When you wanted the April 2010 calendar, you typed cal 4 2010. The “4” and “2010” parts were the arguments—that is, everything you typed after the command itself.)

To see a list of the files in your Documents directory, then, you could just type ls /Users/chris/Documents. Better yet, because the ~ symbol is short for “my home directory,” you could save time by typing ls ~/Documents. The pathname “~/Documents” is an argument that you’ve fed the ls command.

As part of a command’s arguments, you can sometimes insert option flags (also called switches)—modifying characters (or short phrases) that affect how the command works, just like option settings do in GUI applications. In the calendar example, you can type cal -y to see a full-year calendar; the -y part is an option flag.

Option flags are almost always preceded by a hyphen (-), although you can usually run several flags together following just one hyphen. If you type ls -al, both the -a and -l flags are in effect.

Here are some useful options for the ls command:

In other words, you’ve got two subdirectories here, called Old Tahoe Footage 2 and Picnic Movie 2—which itself contains a Media directory.

Now you know how to find out what directory you’re in, and how to see what’s in it, all without double-clicking any icons. That’s great information, but it’s just information. How do you do something in your command line Finder—like switching to a different directory?

To change your working directory, use the cd command, followed by the path of the directory you want to switch to. Want to see what’s in the Movies directory of your home directory? Type cd /Users/chris/Movies and press Return. The $ prompt shows you what it considers to be the directory you’re in now (the new working directory). If you perform an ls command at this point, Terminal shows you the contents of your Movies directory.

That’s a lot of typing, of course. Fortunately, instead of typing out that whole path (the absolute path, as it’s called), you can simply specify which directory you want to see relative to the directory you’re already in.

For example, if your Home folder is the working directory, the relative pathname of the Trailers directory inside the Movies directory would be Movies/Trailers. That’s a lot shorter than typing out the full, absolute pathname (/Users/chris/Movies/Trailers).

If your brain isn’t already leaking from the stress, here’s a summary of the three different ways you could switch from ~/(your home directory) to ~/Movies:

By now, you might be thinking that clicking icons would still be faster than doing all this typing. Here’s where the typing shortcuts of the bash shell come in.

Wildcards are special characters that represent other characters—and they’re huge timesavers.

The most popular wildcard is the asterisk (*), which means “any text can go here.” For example, to see a list of the files in the working directory that end with the letters te, you could type ls *te. Terminal would show you files named Yosemite, BudLite, Brigitte, and so on—and hide all other files in the list. If the wildcard matches any directories, you’ll also see the contents of those directories as well, just as though you’d used ls with each of the full directory names.

Likewise, to see which files and directories begin with “Old,” you could type ls Old* and press Return. You’d be shown only the names of icons in the working directory called Old Yeller, Old Tahoe Footage, Olduvai Software, and so on.

If you add the asterisk before and after the search phrase, you find items with that phrase anywhere in their names. Typing ls *jo* will show you the files named Mojo, johnson, Major Disaster, and so on.

You already know that the tilde (~) character is a shortcut to your home directory. But you can also use it as a shortcut to somebody else’s home directory simply by tacking on that person’s account name. For example, to change to Miho’s home directory, use cd ~miho.

The bash shell offers dozens of special keystroke shortcuts for navigation. You may recognize many of them as useful undocumented shortcuts that work in any Cocoa application, but even more are available (and useful) in Terminal:

Keystroke

Effect

Control-U

Erases the entire command line you’re working on (to the insertion point’s left).

Control-A

Moves the insertion point to the beginning of the line.

Control-E

Moves the insertion point to the end of the line.

Control-T

Transposes the previous two characters.

Esc-F

Moves the insertion point to the beginning of the next word.

Esc-B

Moves the insertion point to the beginning of the current word.

Esc-Delete

Erases the previous word (defined as “anything that ends with a space, slash, or most other punctuation marks; periods and asterisks not included”). You have to hold down Esc as you press Delete; repeat for each word.

Esc-D

Erases the word, or section of a word, following the insertion point.

Esc-C

Capitalizes the letter following the insertion point.

Esc-U

Changes the next word or word section to all uppercase letters.

Esc-L

Changes the next word or word section to all lowercase letters.

The previous pages show you how to navigate your directories using Unix commands. Just perusing your directories isn’t particularly productive, however. This section shows you how to do something with the files you see listed—copy, move, create, and delete directories and files.

Using the Unix command cp, you can copy and rename a file in one move. (Try that in the Finder!)

The basic command goes like this: cp path1 path2, where the path placeholders represent the original file and the copy, respectively.

You can even copy several files or directories at once. Where you’d normally specify the source file, just list their pathnames separated by spaces, as shown in Figure 16-6.

You can also use the * wildcard to copy several files at once. For example, suppose you’ve got these files in your iMovie Projects directory: Tahoe1.mov, Tahoe2.mov, Tahoe3.mov, Tahoe4.mov, Script.doc, and Tahoe Project File. Now suppose you want to copy only the QuickTime movies into a directory called FinishedMovies. All you’d have to do is type cp *mov ../FinishedMovies and press Return; Mac OS X instantly performs the copy.

If you wanted to copy all those files (not just the movies) to another directory, you’d use the * by itself, like this: cp * ../Finished Movies.

Unfortunately, if the iMovie Projects directory contains other directories and not just files, that command produces an error message. The Unix cp command doesn’t copy directories within directories unless you explicitly tell it to, using the -R option flag. Here’s the finished command that copies everything in the current directory—both files and directories—into FinishedMovies: cp -R * ../FinishedMovies.

Here’s one more example: a command that copies everything (files and directories) with Tahoe in its name into someone else’s Drop Box directory: cp -R *Tahoe* ~miho/Public/Drop\Box.

Now that you know how to copy files, you may want to move or rename them. To do so, you use the Unix command mv almost exactly the same way you’d use cp (except that it always moves directories inside of directories you’re moving, so you don’t have to type -R).

The syntax looks like this: mv oldname newname. For example, to change your Movies directory’s name to Films, you’d type mv Movies Films. You can rename both files and directories this way.

Unix provides an extremely efficient way to trash files and directories. With a single command, rm, you can delete any file or directory—or all those that you’re allowed to access with your account type.

The dangers of this setup should be obvious, especially in light of the fact that deletions are immediate in Unix. There is no Undo, no Empty Trash command, no “Are you sure?” dialog box. In Unix, all sales are final.

The command rm stands for “remove,” but it could also stand for “respect me.” Pause for a moment whenever you’re about to invoke it. For the purpose of this introduction to rm, double-check that administration privileges are indeed turned off for your account.

To use this command, just type rm, a space, and the exact name of the file you want to delete from the working directory. To remove the file practice.txt you created with the touch command, for example, you’d just type rm practice.txt.

To remove a directory and everything in it, add the -r flag, like this: rm -r Practice-Folder.

If you’re feeling particularly powerful (and you like taking risks), you can even use wildcards with the rm command. Now, many experienced Unix users make it a rule to never use rm with wildcards while logged in as an administrator, because one false keystroke can wipe out everything in a directory. But here, for study purposes only, is the atomic bomb of command lines, the one that deletes everything in the working directory: rm -rf *.

Just after the letters rm, you can insert options like these:

srm is a command line version of the Finder’s Secure Empty Trash function (Emptying the Trash I: Quick and Easy). It lets you choose just how thoroughly Mac OS X scrubs the hard drive spot where the deleted file once sat.

The srm utility lets you specify three general levels of deletion:

The bottom line: To make sure no one ever, ever reads that poem you typed out for your cat one lonely, bleary-eyed evening, type srm “My Twinkie.doc”. That will be the end of it, and neither the CIA nor Norton Utilities will ever know what it was.

Mac OS X comes with nearly 1,400 Unix programs like the ones described in this chapter. How are you supposed to learn what they all do?

Fortunately, almost every Unix program comes with a help file. It may not appear within an elegant, gradient-gray Snow Leopard window—in fact, it’s pretty darned plain—but it offers much more material than the regular Mac Help Center.

These user-manual pages, or manpages, hold descriptions of virtually every command and program available. Mac OS X, in fact, comes with manpages on almost 7,500 topics—over 40,000 printed pages’ worth.

Alas, manpages rarely have the clarity of writing or the learner-focused approach of the Mac Help Center. They’re generally terse, just-the-facts descriptions. In fact, you’ll probably find yourself needing to reread certain sections again and again. The information they contain, however, is invaluable to new and experienced Unix fans alike, and the effort spent mining them is usually worthwhile.

To access the manpage for a given command, type man followed by the name of the command you’re researching. For example, to view the manpage for the ls command, enter: man ls.

Now the manual appears, one screen at a time, as shown in Figure 16-7.

A typical manpage begins with these sections:

For more information on using man, view its own manpage by entering—what else?—man man.

Tip

The free program ManOpen, available for download at www.missingmanuals.com, is a Cocoa manual-pages reader that provides a nice looking, easier-to-control window for reading manpages.

Or why not just use Dashboard? Download the *NIX Manual widget (from this book’s “Missing CD” page at www.missingmanuals.com, for example). It provides an equally attractive interface to the manpages.

If you spend endless hours staring at the Terminal screen, as most Unix junkies do, you’ll eventually be grateful for the preference settings that let you control how Terminal looks and acts. In fact, Terminal lets you manage your preferences in an ingenious way.

Instead of having a single set of options saved (as with other applications), Terminal manages your options as named settings groups, allowing you to quickly apply different settings to different windows at any time using the Inspector window (Shell→Show Inspector).

You can also save the layout of entire groups of windows, each with their own settings in effect, into a single configuration, allowing you to recreate those layouts in an instant.

Configure your settings using Terminal’s Preferences panel (Figure 16-8), which you get to by choosing Terminal→Preferences (of all places).

This tab is the heart of Terminal’s preferences management. On the left: a list of settings categories. On the right: the options for the currently selected category. Terminal comes with several preconfigured settings, and you can add and remove these and your own using the and buttons below the list. (To restore all the options for the prepackaged settings to their original state, select Restore Defaults from the menu.)

To see your changes reflected instantly in a Terminal window, make sure the window you’re watching is using the same setting you’re modifying.

After you’ve used Terminal awhile, you may feel ready for a few of these power tips:

Permissions is a largely invisible, but hugely important, Mac OS X and Unix feature. The behind-the-scenes permissions setting for a file or folder determines whether or not you’re allowed to open it, change it, or delete it. Permissions are the cornerstone of several important Mac OS X features, including the separation of user accounts and the relative invulnerability of the operating system itself.

As you know from Chapter 13, you can get a good look at the permissions settings for any file, folder, or disk by highlighting it and choosing File→Get Info in the Finder. But even there, you’re not seeing all the permission settings Unix provides, and every now and then, you might want to. Suppose, for example, that you’re a teacher in charge of a computer lab containing 25 Macs. On each computer, you’ve created Standard accounts (see Chapter 12) for five students, for a total of 125 student accounts.

Soon after the students start using the lab, you notice a bit more giggling and frantic typing than you’d expect from students researching Depression-era economics. You nonchalantly stroll to the end of the room and do a quick about-face at one of the desks. Aha—iChat! Horribly depressed by the comments you read there regarding your fashion sense, you vow to keep students from using that application ever again.

You have several options:

In general, when you double-click a file icon in the Finder, it opens either as a program or opens into a program (if it’s a document).

But most Mac OS X application icons in the Finder are really folders posing as single files. Inside the folder, or package, are all the files that application depends on to run, including the actual application file itself, the one that opens when you double-click the package icon. If you turn off the execute permission for that inner nugget, you prevent it from running—and, as in this classroom example, you can turn it off for certain kinds of account holders and not others.

To inspect the permissions for iChat, open the Applications folder. Control-click the iChat icon. From the shortcut menu, choose Show Package Contents. A new Finder window opens, revealing the contents of the iChat application package.

Open the Contents→MacOS folder; inside you find the individual iChat program file. (Nobody would ever bother opening iChat by double-clicking this icon, but it’s possible.) You could inspect its permissions by highlighting the inner iChat icon, choosing File→Get Info, and then expanding the Sharing and Permissions section.

The Unix way is faster. In Terminal, just use the ls command like this:

ls -l /Applications/iChat.app/Contents/MacOS

The -l flag produces a long list—an expanded display showing extra information about each item in the directory, in this case its single iChat file. Terminal’s response is something like this:

total 10616
-total 4424
-rwxr-xr-x  1 root  wheel  5844848 Jul 28 22:28 iChat

Thanks to the -l option, the first line displays the grand total size on disk of all the loose files in the directory: 4424. (It’s measured in 512-byte blocks. If you also included the -k flag, you would see this measurement in kilobytes. Remember that part of the reason Snow Leopard occupies so much less disk space is that many of its system files are compressed on the disk. That’s why the “on disk” size and actual size of a folder’s contents don’t always add up.)

Next you see the name of the one inhabitant of the MacOS directory: iChat. (If there were more, you would see each item on its own line.) But what is -rwxr-xr-x? Is Terminal having a meltdown?

Not at all; you’re just seeing more Unix shorthand, listed in what are supposed to be helpful columns. Figure 16-10 breaks down the meaning of each clump of text.

To understand the coded nine-character file-mode section, you need a good grasp of the topics covered in Chapter 13. There you’ll find out that as you create new files and directories, you can specify who else is allowed to see or make changes to them. In fact, you can specify these permissions for three different categories of people: the owner (usually yourself), your group, and everyone else.

The file-mode column is made of three subcolumns (Figure 16-10), which correspond to those same three categories of people: owner, group, and everybody else.

Within each sequence, three characters describe the read (r), write (w), and execute (x) permissions that this person or group has to this file or directory (more on these concepts in a moment). A hyphen (-) means, “Nope, this person isn’t allowed this kind of access.” In Figure 16-10, you can see that, if you were the owner of this file, you could do anything you want to it—because there are no hyphens.

There’s an x in the other columns, too, meaning that anyone can execute (launch) this file. Since there’s also a w in the owner column, that user (root) could, in theory, even make changes to the file (although there would never be a reason to do so).

The three forms of access—read, write, and execute—have slightly different meanings when applied to files and directories:

Back to the task of keeping iChat from launching. The x in every user category tells you that anyone can run this program. Your mission, should you choose to accept it, is to change these settings so that one class of account holder can run iChat (Admin), but not another (Standard).

As you’ve seen, every file’s set of permissions identifies both an owner and a group. The group that owns the iChat file is wheel, but as you would expect, the Admin class of users is part of the admin group (though not part of wheel). If you want to allow only administrators and anyone else in the admin group to run the program, then you need to also change its group to admin.

You just have to make sure that no other account holders—Standard ones—are also part of the admin group. That’s easy enough to find out.

To find out what Unix groups you belong to, type id in Terminal and press Return. On the next line, Terminal types out a list of items beginning with your account name—that’s your user ID (your uid)—followed by the name of your primary group (your gid). Next are the names of all the groups that include your account. (The Mac refers to accounts and groups by number, which are listed here.) If you have an Administrator account, it’s probably something like uid=506(chris) gid=20(staff) groups=20(staff),401(com.apple.sharepoint.group.1),204(_developer),100(_lpoperator),98(_lpadmin),81(_appserveradm),80(admin),79(_appserverusr),61(localaccoun ts),12(everyone).

But you want to find what groups incorporate Standard account holders. To determine what groups someone else’s account belongs to, type id casey (or whatever the account name is). You’ll probably see that Casey doesn’t belong to the admin group. And, in fact, that’s true for all Standard account holders. (If you prefer a little less output, the groups command used similarly will show you only the group names.)

All right then: The admin group contains only Admin users. As far as permissions are concerned, then, Standard account holders fall into the everyone else category.

You just need to turn off iChat’s execute permissions for everyone else and change iChat’s group to admin to complete your task. Doing so allows only the file’s owner (root) and members of its group (admin) to execute the file (that is, to open the program). All other account holders, meaning Standard account holders, are out of luck. They’ll actually have to pay attention in class.

If you actually try the chmod command described above, however, you get only an error message (“Operation not permitted”).

Only the owner of an item can change its permissions. And you’re not iChat’s owner; root is (that is, Mac OS X itself).

So how do you solve the problem? One solution would be to turn on the root account as described on Putting It Together, and then log on as root. But that’s a hassle, and turning on the root account always entails a security risk.

Instead, you could open the Get Info window for the iChat application file, make yourself the owner, and then type in your name and password to prove you’re an administrator. Then open Terminal, use the chmod command now that you’re the file’s owner, return to the Finder, open Get Info again, and change the file’s permissions back to root.

For a Unix guru, that’s an awful lot of steps for something that should take only a few keystrokes. As it turns out, the final possibility is quick and easy, which explains its popularity in Unix circles. It’s the sudo command.

sudo is a cool command name. Technically, it’s short for superuser do, which means you’re allowed to execute any command as though you’d logged in with the root (superuser) account—but without actually having to turn on the root account, log out, log back in again, and so on.

It’s also a great command name because it looks as though it would be pronounced “pseudo,” as in, “I’m just pretending to be the root user for a moment. I’m here under a pseudonym.” (In fact, you pronounce it “SOO-doo,” because it comes from superuser do. In the privacy of your own brain, though, you can pronounce it however you like.)

If you have the root account—or can simulate one using sudo—you can override any permissions settings, including the ones that prevent you from changing things in the Applications directory (like iChat).

Now you’re ready to change the permissions of that infernal iChat application file. To use sudo, you must preface an entire command line with sudo and a space. Type this:

sudo chmod o-x /Applications/iChat.app/Contents/MacOS/iChat

Taken slowly, this command breaks down as follows:

  • sudo. “Give me the power to do whatever I want.”

  • chmod. “Change the file mode…”

  • o-x. “…in this way: remove execute permission for others…”

  • /Applications/iChat.app/Contents/MacOS/iChat. “…from the file called iChat, which is inside the Applications→iChat.app→Contents→MacOS folder.”

The first time you run sudo, you’re treated to a stern talking-to that means business: “WARNING: Improper use of the sudo command could lead to data loss or the deletion of important system files. Please double-check your typing when using sudo. Type ‘man sudo’ for more information.

“To proceed, enter your password, or type Ctrl-C to abort.”

In other words, sudo is a powerful tool that lets you tromp unfettered across delicate parts of Mac OS X, so you should proceed with caution. At the outset, at least, you should use it only when you’ve been given specific steps to follow, as in this chapter.

Now sudo asks for your usual login password, just to confirm that you’re not some seventh-grader up to no good. If you are indeed an administrator, and your password checks out, sudo gives you a 5-minute window in which, by prefacing each command with sudo, you can move around as though you’re the all-high, master root account holder. (If you don’t use sudo again within a 5-minute span, you have to input your password again.)

The last step, then, is to change the iChat’s group to admin.

The Unix command for changing a file’s group ownership is chgrp (for change group), and it will do the deed:

sudo chgrp admin /Applications/iChat.app/Contents/MacOS/iChat

By this point, you should be able to guess that this command allows you (with sudo) to change the group ownership to admin of the file /Applications/iChat.app/Contents/MacOS/iChat.

Now whenever anyone who isn’t an administrator tries to open iChat, its icon bounces just once in the Dock before dying painlessly.

To restore its original permissions, use the same commands, but in the chmod command, replace the with a , like this:

sudo chmod o+x /Applications/iChat.app/Contents/MacOS/iChat

Then rerun the chgrp command, but replace admin with wheel:

sudo chgrp wheel /Applications/iChat.app/Contents/MacOS/iChat

It could happen to you. You’ve got yourself a folder filled with hundreds of files—downloaded photos from your digital camera, for example. Most are pretty crummy, but the ones you took in Tahoe (which therefore have Tahoe in their file names) are spectacular. You want to protect those files from deletion without having to turn on the Locked checkbox (Locked Files: The Next Generation) of every file individually.

Here again, you could operate in the Finder, just like ordinary mortals. You could use Spotlight to round up all files with Tahoe in their names, highlight them in the search results window, choose File→Get Info, and then turn on Locked for all of them at once. But doing it the Unix way builds character.

When you turn on a file’s Locked checkbox, Mac OS X turns on an invisible switch known to Unix veterans as the user immutable flag. Not even the superuser is allowed to change, move, or delete a file whose user immutable flag is turned on.

The command you need to change such flags is chflags—short for change flags, of course. You can follow the chflags command with three arguments: its own option flags, the file flags, and the pathname of the file whose flags are being changed. In this case, the flag you care about is called uchg (short for user changeable; in other words, this is the immutable flag).

To protect all the Tahoe shots in one fell swoop, then, here’s what you’d type at the prompt:

chflags uchg ~/Pictures/*Tahoe*

The asterisks are wildcards that mean “all files containing the word Tahoe in their names.” So in English, you’ve just said, “Change the immutable flag (the Locked checkbox setting) for all the Tahoe files in my Pictures folder to ‘locked.’”

To view the results of your handiwork right in Terminal, issue this command: ls -lO ~/Pictures (or any other path to a folder containing locked items). That’s the familiar ls (list) command that shows you what’s in a certain directory, followed by an -l flag for a more complete listing, and an -O flag that produces a “flags” column in the resulting table.

In any case, Terminal might spit out something like this:

total 830064
-rw-r-r-1 chris  chris  -    158280000  Jun 16 20:05 Sunset.jpg
-rw-r-r-1 chris  chris  uchg  58560000  Jun 16 20:05 NewMoon.jpg
-rw-r-r-1 chris  chris  uchg 107520000  Jun 16 20:05 Tahoe.jpg
-rw-r-r-1 chris  chris  uchg 107520000  Jun 16 20:05 Tahoe.jpg

The fourth column, the product of the -O flag, lists any file flags that have been set for each file. In this case, three of the files are listed with uchg, which represents the user immutable (locked) flag. (The hyphen for the first listed file means “no flags”—that is, not locked.)

Back at the school computer lab, you’re still grumpy. The students leave piles of file and folder icons splattered across all the Macs’ desktops, and you’ve had enough. Not only is it a sign of laziness and disorganization, but the icons cover the desktop picture of the hallowed school mascot: the southern hairy-nosed wombat.

You’ve warned them enough, and now it’s time for action: No World of Warcraft at lunchtime unless the desktops are clean in 15 minutes!

As you finish writing the new rule on the whiteboard, you turn to face the students’ Mac screens—and you’re stunned. The full, uncluttered image of your beloved marsupial gazes back from the Macs’ displays; the offending icons are gone. How could that be? There hasn’t even been time for the students to select all the icons and drag them to the Trash!

Apparently the students weren’t as lazy as you thought: They’ve been learning the Way of the Terminal. What they actually did was sweep all those icons under the rug, Unix style, with this command:

chflags hidden ~/Desktop/*

They manipulated another file flag, called the hidden flag. The command turns on the hidden flag for all files (indicated by the asterisk) in the Desktop folder—and so their icons disappear. The actual file is still there; but you just can’t see it in the Finder anymore.

Of course, you’re not about to let some punk kids pull one over on you. In your copy of Terminal, you deftly type chflags nohidden ~/Desktop/* to bring the icons back.

The students have 13 minutes left to really clean their desktops.

So far, you’ve read about only a handful of the hundreds of Unix programs that are built into Mac OS X and ready to run. Yes, ls and sudo are very useful tools, but they’re only the beginning. As you peruse beginner-level Unix books and Web sites (see Appendix E), for example, you’ll gradually become familiar with a few more important terms and tools.

Here’s a rundown of some more cool (and very safe) programs that await your experimentation.

Mac OS X offers no shortage of ways to cut the cord on a program that seems to be locked up or runnning amok. You can force quit it, use Activity Monitor, or use kill.

The kill program in Terminal simply force quits a program, as though by remote control. (It even works when you SSH into your Mac from a remote location, as described in Chapter 22.) All you have to do is follow the kill command with the ID number of the program you want to terminate.

And how do you know its ID number? You start by running top—described in a moment—whose first column shows the PID (process ID) of every running program.

When you hear Unix fans talk about kill online, they often indicate a number flag after the command, like this: kill -9. This flag is a “noncatchable, non-ignorable kill.” In other words, it’s an industrial-strength assassin that accepts no pleas for mercy from the program you’re killing.

If you check top and find out that BeeKeeper Pro’s process ID is 753, you’d abort it by typing kill 753 and then pressing Return. If it still appears to be breathing, add the -9 flag like this: kill -9 753, which should deliver the fatal blow. You might even need to rerun the command until you receive output similar to kill: 753: no such pid, telling you that indeed, that process is no more; please hold your fire.

It’s perfectly easy to shut down your Mac from the menu. But using shutdown with its -h flag (for halt) in Terminal has its advantages. For one thing, you can control when the shutdown occurs, using one of these three options:

There are still more useful flags. For example:

One of the most powerful uses of shutdown is turning off Macs by remote control, either from across the network or across the world via Internet. That is, you can use SSH (described in Chapter 22) to issue this command.

You know how Mac OS X can create compressed .zip archive files?

Terminal lets you stuff and combine files in these formats with the greatest of ease. To compress a file, just type gzip, a space, and then the pathname of the file you want to compress (or drag the file directly from the desktop into the Terminal window). When you press Enter or Return, Mac OS X compresses the file.

“Tarring” a folder (combining its contents into a single file—a tarball, as Unix hepcats call it) is only slightly more complicated. You have to specify the resulting file’s name, followed by the actual directory pathname, like this: tar -cf Memos.tar /Users/chris/ Memos. Add the -z flag if you want to tar and compress the folder: tar -czf Memos. tar.gz /Users/chris/Memos.

To combine and compress files using zip, just specify a name for the zip file and the names of the items to zip, like this: zip StaffordLake.zip Stafford* (which would cram all files in the working directory whose name begins with Stafford into a single archive).

To zip a folder, include the -r flag as well: zip -r Memos /Users/chris/Memos.

In any case, if you switch to the Finder, you see that the file or folder you specified is now compressed (with the suffix .gz), combined (with the suffix .tar), or both (with the suffix tar.gz or .zip).

Unfortunately, the command line zip utility doesn’t handle extended attributes properly (see the next page), so stick with tar and gzip if you want to create guaranteed Mac-friendly archives. The best format is a gzipped tarball, which the Finder will properly open with a double-click. (If you only gzip a file without tarring, the Finder won’t preserve any extended attributes when opening it.) You can also use these utilities to open combined and compressed files, but they can easily overwrite existing items of the same name if you’re not careful. Use the Finder or StuffIt Expander to eliminate that worry.

The xattr command lets you see and manage the extended attributes (EAs) of your files—the invisible metadata that describes all kinds of characteristics of every file, from the exposure of a digital camera shot to the tempo of a song in iTunes. (Chapter 3 has much more on metadata and searching for it.)

Running xattr * lists any EAs in your working directory. If you ran it in your ~/ Downloads folder, the command might look like this:

MacChris:Downloads chris$ xattr  *
GoogleEarthMac.dmg: com.apple.diskimages.fsck
GoogleEarthMac.dmg: com.apple.diskimages.recentcksum
GoogleEarthMac.dmg: com.apple.metadata:kMDItemWhereFroms
GoogleEarthMac.dmg: com.apple.quarantine
MacPorts-1.8.0-10.6-SnowLeopard.dmg: com.apple.diskimages.fsck
MacPorts-1.8.0-10.6-SnowLeopard.dmg: com.apple.diskimages.re-
centcksum
MacPorts-1.8.0-10.6-SnowLeopard.dmg: com.apple.
metadata:kMDItemWhereFroms
MacPorts-1.8.0-10.6-SnowLeopard.dmg: com.apple.quarantine
NeoOffice-3.0-Intel.dmg: com.apple.metadata:kMDItemWhereFroms
NeoOffice-3.0-Intel.dmg: com.apple.quarantine

Only three files are listed, but each of their EAs gets its own line. What you’ll find in common to all of these files is that they hold a “com.apple.quarantine” EA.

You know how, the first time you open a program on your Mac, you get the dialog box shown in Figure 12-15 (Five Mac OS X Security Shields)? Now you know how the Mac knows that this is the first time you ran it: That detail was stored as one of its extended attributes.

If you really can’t stand those messages, you could use another Unix command to prevent the nag box from appearing. For example, before installing NeoOffice, you could simply remove the quarantine EA from its downloaded disk image file using the xattr command’s -d flag, like this:

xattr -d com.apple.quarantine NeoOffice-3.0-Intel.dmg

You can also use the ls command to see EAs. When you use just the -l flag with ls, files with EAs show an @ sign at the end of the permission codes:

MacChris: Downloads ls -l NeoOffice-3.0-Intel.dmg
-rw-r--r--@ 1 chris staff 167536744 Mar 28 11:58 NeoOffice-3.0-Intel.dmg

To see what those EAs are, add the @ flag:

MacChris:Downloads chris$ ls -l@ NeoOffice-3.0-Intel.dmg
-rw-r--r--@ 1 chris  staff  167536744 Mar 28 11:58 NeoOffice-3.0-Intel.dmg
com.apple.metadata:kMDItemWhereFroms             196
com.apple.quarantine           74

One way to create and edit text files containing aliases (and to perform other command-related tasks) is to use nano, a popular text editor that’s an improved version of the pico editor (see Figure 16-12). In fact, if you try to run pico, nano opens instead.

As you’ll discover just by typing nano and pressing Return, nano is a full-screen Unix application. You enter text in nano much as you do in TextEdit, yet nano is filled with features that are especially tailored to working with Unix tasks and commands.

Nor is nano the only text editor that’s built into the Unix under Mac OS X. Some Unix fans prefer the more powerful and complex vim or emacs, in the same way that some people prefer Microsoft Word to TextEdit.

Used all by itself, the date command simply displays the current date and time. However, you can use its long list of date “conversion specifications” (enter man date to see all of them) to format the date string in any conceivable way. Begin the string with a and then enter the formatting you like, mixing in any regular text as well, like this:

office-mac:~ chris$ date +"I can't believe it's already week %V
of %Y, here in the %Z time zone. But what do you expect on a %A
at %l:%M %p?"
I can't believe it's already week 23 of 2010, here in the PST
time zone. But what do you expect on a Wednesday at 8:21 PM?

If you have a soft spot in your heart for Spotlight, you’ll be happy to see the mdfind command in Terminal. It performs the same kinds of searches, finding by metadata like music genre or exposure data for photos.

To find all reggae songs, for example, try:

mdfind 'kMDItemMusicalGenre == "Reggae"'

To find all photos you shot with the flash on:

mdfind 'kMDItemFlashOnOff == "1"'

The mdls command reveals all the metadata for a particular file, like the IMG_3033. jpg picture in this example:

ongaku:Photos$ mdls IMG_3033.JPG
kMDItemAcquisitionMake         = "Canon"
kMDItemAcquisitionModel        = "Canon PowerShot S3 IS"
kMDItemAperture                = 4.65625
kMDItemBitsPerSample           = 32
kMDItemColorSpace              = "RGB"
kMDItemContentCreationDate     = 2007-06-30 14:51:07 -0700
kMDItemContentModificationDate = 2007-06-30 14:51:07 -0700
kMDItemContentType             = "public.jpeg"

You can find more about constructing your queries here: http://developer.apple.com/mac/library/documentation/Carbon/Conceptual/SpotlightQuery/Concepts/QueryFormat.html.

launchd is a multitalented Unix program responsible for launching system programs, during startup or anytime thereafter. Part of its job is triggering certain commands according to a specified schedule, even when you’re not logged in. People can use launchd to trigger daily backups or monthly maintenance, for example. You can program your unattended software robot by editing simple property list files.

Mac OS X comes set up to run launchd automatically; it’s the very first process that starts up when the Mac does. It launches all your other startup items, in fact. (If you open the Activity Monitor program in your Applications→Utilities folder, you’ll see it listed among the administrator processes that your Mac is running all the time.)

In fact, launchd comes with three under-the-hood Unix maintenance tasks already scheduled: a daily job, a weekly job, and a monthly job. They come set to run at 3:15 a.m. (the first two), and 5:30 a.m. If your Mac isn’t generally turned on in the middle of the night, these healthy jobs may never run.

You can either leave your Mac on overnight every now and then or, if you’re feeling ambitious, change the time for them to be run. A glance at man launchd.plist shows you how. (Hint: It involves using sudo nano and editing the three com.apple.periodic property list files in /System/Library/LaunchDaemons—but be careful not to mess with anything else in there!)

The Unix syntax and vocabulary presented in this chapter is all well and good, and it’ll give you the rosy glow of having mastered something new. But it still doesn’t entirely explain why Unix gives programmers sweaty palms and dilated pupils.

The real power of Unix comes down the road—when you start stringing these commands together.

Suppose, for example, you want to round up all the TIFF image files related to your Yosemite project, scale them to a common size, convert them to JPEG files, and copy them to an FTP site. How would you go about it?

You could, of course, use Spotlight to search for all TIFF files that have “Yosemite” in their names. But what if your images were named otherwise but kept in folders with Yosemite in their names? You would have to find those folders first, and then the TIFF files within them.

You could perform the next step (scaling and converting the image) either manually or by a preprogrammed script or Automator workflow, using a program like Photoshop or even iPhoto. Once the images were all done, you’d need to collect them and then use your favorite FTP program to upload them to the server.

If you’ve mastered Unix, though, you could shave 12 minutes off of your workday just by changing to an empty working directory (in this example, ~/Stage) and typing this as one long line:

find ~ -type f -ipath '*yosemite*tif' -print0 | xargs -0 sips
-Z 250 -s format jpeg --out ~/Stage && ftp -u ftp://ftp.coast-
photo.com/Incoming *

Even after almost 50 pages of Unix basics, that mass of commands probably looks a tad intimidating. And, indeed, if you’ve never programmed before, even the following breakdown may make your eyes glaze over. Nevertheless, pieces of it should now look familiar:

When you press Return or Enter after this gigantic command, Mac OS X scans all the directories inside your home directory, rounds up all the Yosemite-related images, scales them, converts and renames them, and then uploads each to the FTP directory.

Once you’ve gained some experience with Unix commands and programs like these, you’ll find it fairly easy to adapt them to your own tasks. For example, here’s a more versatile command that searches a directory called Projects for all TIFF files modified after 6:00 that morning, converts them to thumbnail-sized JPEGs, plops them into the images directory of your FTP-accessible Web server, and then moves them all to your Backup directory:

cd ~/Stage && find ~/Projects -type f -iname *tif -newermt 6:00
-print0 | xargs -0 sips -Z 128 -s format jpeg --out ~/Stage &&
ftp -u ftp://carlos:birdie@ftp.coast-photo.com/htdocs/images *
&& mv * ~/Backup/

With just a few more keystrokes, you could modify that command to collect some files, lock them, and place copies of each in every account holder’s home directory, as well as several different servers at the same time. What’s more, it emails you a report when it’s done. Using launchd, you could even configure this routine to trigger itself automatically every day at 11:00 p.m. Considering the hundreds of Unix programs included with Mac OS X and the thousands of others available on the Internet, the possibilities are limitless.

For some guidance in picking up your Unix career from here, see Appendix E.