Mac OS X

Mac OS X's graphical user interface (GUI) is elegant, graceful, and powerful enough to let most of us ignore what's happening behind the scenes. But if you're bent on finding new ways to streamline your work, it may be time to roll up your sleeves and dig into Mac OS's guts -- the Unix command line. This article will help the adventurous get started.

You'll do all your command-line work in Terminal, which is in the Utilities folder in your Applications folder. Once you launch it, you're ready to begin.

The Anatomy of a Command

Command-line commands can be broken down into four parts. The first is the command-line program, which is like any other Mac application, but it uses text instead of graphics to communicate with the user.

Next come options. The command-line equivalent of preferences, they allow you to modify how a program functions. A general rule is that options are identified by either a single or a double dash, which is followed by a single character or a whole word. An additional parameter may follow the option.

After that are arguments, or the input the program acts upon. A program's arguments are usually file names, but they can be almost anything, including the output of other command-line programs.

Finally, there's output, the result of the program. Just like a regular program's output, a command-line program's output can be a file or a printed page, but most often it's text that appears on screen.

Learning ls Hundreds of command-line programs are available in the standard installation of OS X, ranging from the incredibly simple (echo will output whatever you type as its arguments) to the ridiculously obscure (yes will repeatedly press the Y key for you).

One of the most common is the ls (list) command, so we'll start with this. Type it into Terminal and press return. Congratulations, you've just run your first command-line program!

This command displays the contents of the current folder (or directory, in Unix lingo). You should see the names of all the folders and files in your Home folder, including Desktop, Documents, Sites, and so on. That's easy enough, but there's more.

To modify the default behavior of a command, you can join it with options.

Options For instance, you can combine ls with several options that change the way it works. ls -l will display a longer list that has details such as file sizes and modification times. ls -a will show all files, including those whose names begin with a dot, which are normally hidden. (Names of Unix configuration files are often preceded by a dot so they won't clutter up normal listings.) You can combine options, too: ls -l -a will give you a long list of folder contents with all the files displayed.

How do you find out what options a command has? Type man (manual) followed by the name of any command-line program to see all the details about its options and functionality, as well as examples.

Arguments Like many other commands, ls also takes arguments -- in the simplest case, the names of folders you want to see the contents of.

For instance, ls /Users will show you the Home folders of all the users on your machine, along with the universal Shared folder. The command ls /Users/jdoe /Users/rroe will show you the contents of the jdoe and rroe user folders.

You can even use wild cards to specify a range of names more easily: an asterisk will act as a stand-in for any group of characters, and a ques-tion mark will substitute for a single character.

For example, ls /usr/bin/s* will show you all the files that start with the letter s in your computer's /usr/bin directory. This is handy when you want to narrow the program's arguments to a manageable range -- *.doc for all your word processor documents, for instance.

Controlled Experiments

Now that you've gotten acquainted with the ls command, here are a few other command-line essentials.

Changing Directories with cd Unlike the Finder, which allows you to have any number of folders open at once, the command line limits you to a single place at any one time -- this is your working directory. The cd (change directory) command will allow you to choose a new working directory.

Type cd Sites to move into your Sites folder and make it the working directory. Type cd .. to move one step back toward the root of your hard drive, and cd / to move all the way there. The command cd ~ will return you to your Home folder (the tilde [~] is shorthand for Home). If you get confused about which directory you've ended up in, the command pwd (print working directory) will show you where you are in the folder hierarchy.

Having Fun with Files You can do more than list files. Give the ditto command a try: it makes copies.

To use ditto, follow it with two file names (the first is the source and the second is the destination) or more (the last is the folder into which you're copying all the previous files), and it will make duplicates. Be sure to include the -rsrcFork option to preserve the HFS+ resource fork on the copied files, and feel free to use wild cards when you're specify-ing the source files and folders. For example, ditto -rsrcFork ~/*.doc /private/tmp will copy all of the word processing documents in your Home folder to the temporary directory. To view the copies, select Go: Go To Folder in the Finder and enter /private/tmp. You can also use cd /private/tmp and ls from the command line, of course.

With commands such as ditto and wild cards, you can start to see the power the command line gives you -- a single command can copy hundreds of files.

The Impossible Made Possible

That's just the beginning. By stringing command-line commands together with redirection -- using the output of one program as the input for another -- you can accomplish things that are otherwise impossible.

There are three ways to redirect a command's output so that another command can use it as input. The vertical bar, or pipe (|), sends output directly to the following command-line program for use as input. For example, ls -l | more uses the more command to pause after each screenful of data.

If you surround a command with backward apostrophes, or backticks (`), the command will include its output in the argument list of another command.

One example is cd `cat gohere.txt`. The cat (concatenate) command displays files on screen. Combined with backticks and cd, it can change the folder listed in a file into your working directory.

Finally, the greater-than sign (>) will dump the output to a file instead of the screen. For example,

ls -l ~ > ~/myfiles.txt

creates a file called myfiles.txt in your Home folder; this file contains the long list of Home's contents.

Bring It All Together

The true power of the command line becomes apparent when you combine commands, options, arguments, and redirection. Here's a single line of commands that saves compressed backup copies of all the Word documents in your Home directory, complete with a dated file name: find ~ -name '*.doc' | cpio -o | gzip > `date +~/%Y%m%d.cpio.gz`.

As complicated as it looks, this breaks down very simply. The find command lists files based on several criteria: name, date, owner, and many more. find ~ -name '*.doc' lists every file name in your Home folder and its subfolders that ends with .doc.

The contents of that list are passed to the cpio (copy I/O) command, which is basically a simplified Unix version of StuffIt. The -o (output) option tells the program that you're creating an archive.

That data is sent to gzip, a Unix compression program that shrinks the archive and writes the result to a file made up of the output of the date command: your Home folder (~), the exact date (%Y%m%d), and finally the typical Unix file extension attached to a file that has passed through cpio and gzip (.cpio.gz).

Although files are stored in a single archive, you retrieve them individually. To recover a file, reverse the process: gzip -d -c YYYYMMDD.cpio.gz | cpio -i -d -r '*filename*'.

Replace YYYYMMDD with the date you made your archive and filename with at least part of the name you'd like to restore. This command will prompt you with the name of each archived file that matches, allowing you to skip it, restore it to its old location, or put it someplace new. If you'd like a chance to restore any file in the archive, just remove the filename portion of the command ('*filename*'), and you'll be asked about each. To restore the whole archive without question, just remove the -r option.

Taking Command This article just scratches the surface of what you can do with OS X's command line. For longtime GUI users, the command line can be a bit intimidating. But once you get used to a few simple rules, the full power of OS X is at your command.

Other Commands to Explore

You don't need a Unix tome to get started with the command line. You can learn an enormous amount simply by reading and experimenting on your own. Many commands come with detailed documentation; you just have to know where to look. In Terminal, type man (manual) followed by one of these commands to see details and examples.

File viewing: tail, head, more, less, cat
File manipulation: cut, sort, uniq, grep, wc
File creation: touch, mkdir
Ownership and permissions: id, chmod, chown, chgrp
Process manipulation: ps, top
System information: df, hostname, domainname, machine, who

Subscribe to the Best of Macworld Newsletter

Comments