BUY THIS BOOK
Add to Cart

Print Book $19.95


Add to Cart

Print+PDF $25.93

Add to Cart

PDF $15.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £13.95

What is this?

Looking to Reprint or License this content?


Learning Unix for Mac OS X Tiger
Learning Unix for Mac OS X Tiger By Dave Taylor
June 2005
Pages: 280

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Why Use Unix?
Why would any sane person want to type in a bunch of funny looking Unix commands when you can just use the mouse? After all, Mac OS X has one—if not the— best looking user interface out there, so what would compel you, a Mac user through and through, to use the Unix command line? That's a tough sell, but you can boil it down to just one word: Power.
Lying underneath Mac OS X Tiger's purring Aqua interface is a powerful Unix system, ready to leap into action at a moment's notice. All you have to do is command Unix to take action. One of the greatest pleasures of using Unix within Mac OS X is that you get the benefit of a truly wonderful graphical environment and the underlying power of the Unix command line. There's no denying it's a match made in heaven. Even Apple promotes Mac OS X with the tagline:
"The simplicity and elegance of the Mac, and the Power of Unix."
This chapter sets the stage for the rest of the book, answering the question: "Why use Unix when you have a perfectly good Mac graphical interface?" It's an important question, and I think that within just a few minutes, you'll agree that joining the Unix world is really like learning you have a completely separate, and even more powerful, operating system lurking in your machine.
Why you should have to remember commands and type them in is an obvious thing to question. If you're a long-time Macintosh person who is familiar and happy with the capabilities and logic of the Aqua interface, you might need some convincing that Unix is your friend. Here's why: dipping into the primarily text-based Unix tools on your Mac OS X system gives you more power and control over both your computer and your computing environment. There are other reasons, including:
  • There are thousands of open source and otherwise freely downloadable Unix-based applications. Can't afford Adobe Photoshop but still want a powerful graphics editor? The GNU Image Manipulation Program (GIMP) offers a viable solution (see Chapter 10).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Power of Unix
Why you should have to remember commands and type them in is an obvious thing to question. If you're a long-time Macintosh person who is familiar and happy with the capabilities and logic of the Aqua interface, you might need some convincing that Unix is your friend. Here's why: dipping into the primarily text-based Unix tools on your Mac OS X system gives you more power and control over both your computer and your computing environment. There are other reasons, including:
  • There are thousands of open source and otherwise freely downloadable Unix-based applications. Can't afford Adobe Photoshop but still want a powerful graphics editor? The GNU Image Manipulation Program (GIMP) offers a viable solution (see Chapter 10).
  • Want to search for files by when or who created them? Difficult in the Finder or Spotlight, but it's a breeze with Unix (see Chapter 5).
  • And how about managing your files and file archives in an automated fashion? Tricky to set up with the GUI tools, but in Unix, you can set up a cron job to handle this at night while you sleep (see Chapter 5 as well).
Fundamentally, Unix is all about power and control. As an example, consider the difference between using Force Quit from the Apple menu and the Unix programs ps and kill. While Force Quit is more attractive, as shown in Figure 1-1, notice that it lists only graphical applications.
Figure 1-1: Force Quit doesn't show all running applications
By contrast, the ps (processor status) command used from within the Terminal application (/Applications/Utilities/Terminal) shows a complete and full list of every application, utility, and system process running on your Mac, as shown here:
$ ps -ax
  PID  TT  STAT      TIME COMMAND
    1  ??  S<s    0:00.31 /sbin/launchd
31  ??  Ss     0:00.56 /usr/sbin/syslogd -m 0 -c 5
   37  ??  Ss     0:02.30 kextd
   41  ??  Ss     0:03.48 /usr/sbin/configd
   42  ??  Ss     0:00.47 /usr/sbin/coreaudiod
   43  ??  Ss     0:00.76 /usr/sbin/diskarbitrationd
...
  375  p2  Ss     0:00.03 login -p -f taylor
  376  p2  S+     0:00.04 -bash
  437  p3  Ss     0:00.05 -bash
  455  p3  R+     0:00.01 ps -ax
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Thousands of Free Applications
This should appeal to anyone who is a part of the Macintosh community: by warming up to Unix and its command line, you are joining the much-lauded open source movement, since Mac OS X is based on an open source Unix operating system, called Darwin. What's excellent is that there are thousands of different applications available for open source operating systems, including design, development, scientific, and business applications that compare quite favorably to expensive commercial alternatives. Also, don't make the mistake of assuming that all open source applications are command-line applications! Some of the very best applications, like The GIMP graphics editor (www.gimp.org) and the NeoOffice/J suite (www.neooffice.org) are designed to work within either X11 or directly in Mac OS X's Aqua GUI environment.
While this book covers only about 50 of the most basic Unix commands, there are over a thousand Unix commands included with Mac OS X—and you can't see some of these commands without accessing the command line. From sophisticated software development environments to web browsers, file transfer utilities to encryption and compression utilities, almost everything you can do in the Aqua interface—and more—can be done with a few carefully chosen Unix commands.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Power Internet Connections
If you're someone who uses the Internet daily, you already know that there are a bunch of useful Mac OS X applications available to help you be efficient. But lots of them seem to have a price tag attached, even a simple FTP program like Fetch (www.fetchworks.com). But why spend $25 on an application when you can use Mac OS X Tiger's built-in ftp command-line utility for free!
For example, if you wanted to download the cover image for this book from O'Reilly's web site, you could use the following commands (as noted in bold type):
MacDave:~ taylor$ ftp ftp.oreilly.com
Connected to tornado.east.ora.com.
220 ProFTPD 1.2.10 Server (ftp.oreilly.com) [172.31.173.9]
Name (ftp.oreilly.com:taylor): anonymous
331 Anonymous login ok, send your complete email address as your password.
Password: [Type in your email address here]
ftp> cd /pub/graphics/book-covers/low-res
ftp> get 0596009151.gif
local: 0596009151.gif remote: 0596009151.gif
229 Entering Extended Passive Mode (|||38666|)
150 Opening BINARY mode data connection for 0596009151.gif (217245 bytes)
100% |*************************************|   212 KB  45.72 KB/s  00:00 ETA
226 Transfer complete.
217245 bytes received in 00:04 (44.22 KB/s)
ftp> bye
221 Goodbye.
That downloads the image file for the cover of this book to your Mac, which is nice, but what if you want to look at it? Sure, you could go to the Finder, find the file, and then double-click on the file's icon to open it in Preview, but that's a lot of work. However, with a little help from Unix, you can just type in the following command:
MacDave:~ taylor$ open 0596009151.gif
MacDave:~ taylor$
The open command, which is special to Mac OS X, examines the file it's supposed to open (0596009151.gif), detects which application should open it by default (something you can see in a file's Get Info window), and then opens the file in Preview—all in a fraction of a second! See how much time Unix just saved you (not to mention the $25!)?
From logging in to your Mac from remote locations to transferring files from your system to a server using an encrypted connection, Mac OS X's Unix command line is quite powerful. But don't take my word for it. Chapter 8 takes you on a detailed tour of command-line Internet utilities.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Simple Guided (Unix) Tour
Enough talking about what Unix can do, it's time to flex your fingers, open up your Mac, and try a few commands so you can get a sense of how it all works!
The first step is to launch the Terminal application, through which you'll interact with the command shell, the program within which you type in your commands and the responses are shown. Terminal is tucked into the Utilities folder in your Applications folder, which you can quickly get at from the Finder with the Shift-⌘-U keyboard shortcut.
Since you'll be using the Terminal application a lot throughout this book (and hopefully in the future, as you grow more comfortable with Unix), you should drag the Terminal's icon to the Dock so it's always at the ready. Or, if the Terminal's already running, you can Control-click on its application in the Dock and select "Keep in Dock" from its contextual menu, as shown in Figure 1-3.
Figure 1-3: Control-click the Terminal's Dock icon, and select "Keep In Dock" from its contextual menu so it will always be there when you need it
Throughout the following example, type in the commands you see in bold, pressing the Return key after each one (again, this is known as "entering a command" in Unix-speak). Preceding each command, I've included some comments to let you know what you're about to do:
Without any arguments, the cd command moves you to your Home directory:
$ cd
The pwd (or present working directory) command shows you the path for the directory you're currently in:
$ pwd
/Users/taylor
Use the ls command to list the files in your Home directory; compare this listing with the picture of the Finder window shown in Figure 1-2. If you omit the -a option, then all the hidden dot files stay hidden in this directory:
$ ls
Desktop         Mail            Pictures        myopen
Documents       Movies          Public
Library         Music           Sites
Now let's change directories to your Library folder:
$ cd Library
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The 10 Most Common Unix Commands
If you want to just jump in and try things out, here are the 10 most common commands with a very short summary of what each does:
ls
List files or directories.
cp original_file copied_file
Copies the original_file (or files) from one location to another.
mv original_file new_file
Move a file or files; the original is deleted once complete.
rm filename
Remove a file, set of files or folders full of files.
Use the rm command with caution; there's no "Trash" where things are moved to. Once you've used rm to delete something, it's gone forever.
pwd
Display your present working directory; this is where you currently are in the filesystem.
cd directory_name
Change to the specified directory in the filesystem. Without any arguments, it's a shortcut for changing back to your Home directory.
man command_name
Access Mac OS X's built-in documentation for the Unix commands. To read the man page for the ls command, for example, type in man ls.
more filename
Display a long text file, one screen at a time. Pressing the spacebar gets the next page when you're ready, and pressing Q at any time quits the program and returns you to the command prompt.
grep pattern
Search for the specified pattern across as many files as you desire. A fast way to find that email message you sent to Uncle Linder, for example.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Using the Terminal
With a typical Unix system, a staff person has to set up an account for you before you can use it. With Mac OS X, however, the operating system installation process automatically creates a default user account. The account is identified by your username, which is usually a single word or an abbreviation. Think of this account as your office—it's your personal place in the Uix environment.
When you log into your Mac OS X system, you're automatically logged into your Unix account as well. In fact, your Desktop and other customized features of your Mac OS X environment have corresponding features in the Unix environment. Your files and programs can be accessed either through the Finder or through a variety of Unix command-line utilities that you can use in Mac OS X's Terminal application.
In this chapter, you'll not only learn about the Terminal and how to customize it for your own needs, but you'll also gain an understanding of the command-line nature of Mac OS X when accessed through the Terminal. If you're used to moving your mouse around and clicking on buttons, this might seem wonderfully—or awkwardly—retro, but like any other powerful environment, the difference between the Finder and the Terminal are part of what makes the Terminal, and Unix, so remarkably powerful.
The way you use Unix on Mac OS X is through an application, known as the Terminal. The Terminal application is located in the Utilities folder (/Applications/Utilities). To launch the Terminal, open a Finder window, use the Shift-⌘-U keyboard shortcut (which takes you right to the Utilities folder), and then locate and double-clicking on the Terminal application, as shown in Figure 2-1. It starts up presenting you with a dull, uninspiring white window with black text that says "Welcome to Darwin!" and a shell prompt.
Figure 2-1: Finding Terminal in the Utilities folder
By default, Terminal uses bash as its shell. If you'd like to configure it to use a different shell, you can do so by selecting Terminal → Preferences and specifying the shell to use. I talk about that in the sidebar "What is a Shell?" later in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Launching the Terminal
The way you use Unix on Mac OS X is through an application, known as the Terminal. The Terminal application is located in the Utilities folder (/Applications/Utilities). To launch the Terminal, open a Finder window, use the Shift-⌘-U keyboard shortcut (which takes you right to the Utilities folder), and then locate and double-clicking on the Terminal application, as shown in Figure 2-1. It starts up presenting you with a dull, uninspiring white window with black text that says "Welcome to Darwin!" and a shell prompt.
Figure 2-1: Finding Terminal in the Utilities folder
By default, Terminal uses bash as its shell. If you'd like to configure it to use a different shell, you can do so by selecting Terminal → Preferences and specifying the shell to use. I talk about that in the sidebar "What is a Shell?" later in this chapter.
Most Mac OS X applications you've run to this point probably have a pretty graphical interface and allow you to move the cursor around with your mouse or trackpad. Move it over something you want and you can simply click for the action to take place. The Terminal is different, though, and your mouse gets a rest for a while as you type in the commands on your keyboard, ending each line with a Return.
Unix command lines can be simple, one-word entries such as the date command. They can also be more complex; you may need to type more than the command or program name.
A Unix command can have arguments. An argument can be an option or a filename. The general format for a Unix command line is:
command option(s) filename(s)
There isn't a single set of rules for writing Unix commands and arguments, but these general rules work in most cases:
  • Enter commands in lowercase.
  • Options modify the way in which a command works. Options are often single letters prefixed with a dash (-, also called "hyphen" or "minus") and set off by any number of spaces or tabs. Multiple options in one command line can be set off individually (such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customizing Your Terminal Session
There are a number of different ways that you can customize your Terminal session beyond what's shown so far in this chapter. These are more advanced techniques, and you can safely flip past them if they seem too complex (though I'd still encourage you to read through the material, just so you can see what capabilities are included within the Terminal application).
You can change the current Terminal title using the following cryptic sequence of characters:
echo '^[]2;My-Window-Title^G'
To type the ^[ characters in bash, use the key sequence Control-V Escape (press Control-V and release, then press the Escape key). To type ^G, use Control-V Control-G. The vi editor supports the same key sequence.
Such cryptic sequences of characters are called ANSI escape sequences . An ANSI escape sequence is a special command that manipulates some characteristic of the Terminal, such as its title. ^[ is the ASCII ESC character (which begins the sequence), and ^G is the ASCII BEL character. (The BEL character is used to ring the Terminal bell, but in this context, it terminates the escape sequence.)
AppleScript is a powerful programming language used to automate Mac OS X applications. The Mac OS X Terminal is one such application. You can run AppleScript commands at the shell prompt using the osascript utility. The \ character tells the shell that you want to enter a single command on several lines (when you use this, the shell will prompt you with a ? character):
osascript -e \
'tell app "Terminal" to set option of first window to value'
For example, to minimize your current Terminal window:
$ osascript -e \
> 'tell app "Terminal" to set miniaturized of first window to true'
$
For a complete list of properties you can manipulate with AppleScript, open the Script Editor (/Applications/AppleScript) and select File → Open Dictionary. Open the Terminal dictionary and examine the properties available under window, as shown in Figure 2-11. If a property is marked
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with the Terminal
To get into the Unix environment, launch the Terminal application (go to Finder → Applications → Utilities → Terminal).
If you expect to use the Terminal a lot, drag the Terminal icon from the Finder window onto the Dock or choose "Keep in Dock" by clicking on the app icon in the Dock while Terminal is running. You can then launch Terminal with a single click.
Once Terminal is running, you'll see a window like the one in Figure 2-13.
Figure 2-13: The Terminal window
You can have a number of different Terminal windows open, if that helps your workflow. Simply use ⌘-N to open each one, and ⌘-~ to cycle between them without removing your hands from the keyboard.
Once you have a window open and you're typing commands, it's helpful to know that regular Mac OS X copy and paste commands work, so it's simple to send an email message to a colleague showing your latest Unix interaction, or to paste some text from a web page into a file you're editing with a Unix text editor such as vi.
If you have material in your scroll buffer you want to find, use ⌘-F (or select Find → Find from the Edit menu) and enter the specific text. ⌘-G (Find → Find Next) lets you search down the scroll buffer for the next occurrence, and Shift-⌘-G (Find → Find Previous) lets you search up the scroll buffer for the previous occurrence. You can also search for material by highlighting a passage, entering ⌘-E (Find → Use Selection for Find), or jumping to the selected material with ⌘-J (Find → Jump to Selection). You can also save an entire Terminal session as a text file with File → Save Text As, and you can print the entire session with File → Print. It's also a good idea to study the key sequences shown in the Scrollback menu , as illustrated in Figure 2-14.
Figure 2-14: Command sequences accessible from the Scrollback menu
There are some symbols in the Scrollback menu you might not have seen before in your Mac OS X exploration: the upward facing diagonal arrow for Scroll to Top is the Top or Home key on your keyboard, and the downward facing diagonal arrow for Scroll to Bottom is the End key. You can move up a page with the Page Up key, and down a page with the Page Down key. To move up or down lines, use z-up arrow or z-down arrow, as needed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customizing the Shell Environment
The Unix shell reads a number of configuration files when it starts up. These configuration files are really shell programs, so they are extraordinarily powerful. Shell programming is beyond the scope of this book.
But let's look at what you can customize without having to become a full-fledged Unix geek, shall we?
The default login shell for Tiger is the ever-popular bash shell, but many Unix fans prefer to use the Korn shell (ksh) instead. As mentioned earlier, Mac OS X offers a host of different shells, including /bin/bash, /bin/csh, /bin/ksh, /bin/tcsh, /bin/zsh, and /bin/sh.
To change your login shell, you can either use the Unix chsh command (enter chsh on the command line and you'll be asked which shell you'd like starting the next time you log in), or just change it within the Terminal Inspector's Shell pop-up screen, as shown earlier, in Figure 2-3.
The easiest customization you can make to the shell is to change your command prompt. By default, bash on Mac OS X has a shell prompt made up of your computer hostname, your current working directory, your account name, and a dollar sign. For example:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Advanced Shell Customization
There's not much more you can do with the Terminal application than what's shown in this chapter, but there's an infinite amount of customization possible with the bash shell (or any other shell you might have picked). Here are a few directions to get you started.
Because Unix is a multiuser system, there are two possible locations for the configuration files: one applies to all users of the system and another to each individual user.
The system-wide setup files that are read by bash, the default shell for Mac OS X, are found in /etc (profile and bashrc). You only have permission to change these system-wide files if you use sudo (see "Superuser Privileges with sudo in Chapter 3). However, you can create another file called .profile in your home directory that will add additional commands to be executed whenever you start a new Terminal window. (If you configure Terminal to use another shell, such as the Bourne shell, the C shell, or the Z shell, you'll need to set up different configuration files. See the manpage for your selected shell to learn necessary details. To learn more about csh, for example, type man csh.)
The system-wide setup files are read first, then the user-specific ones, so commands in your .profile file can override those in the system-wide files. The system-wide profile and bashrc files are succinct:
$ cat /etc/profile
# System-wide .profile for sh(1)

PATH="/bin:/sbin:/usr/bin:/usr/sbin"
export PATH

if [ "${BASH-no}" != "no" ]; then
  [ -r /etc/bashrc ] && . /etc/bashrc
fi

$ cat /etc/bashrc
# System-wide .bashrc file for interactive bash(1) shells.
if [ -n "$PS1" ]; then PS1='\h:\w \u\$ '; fi
# Make bash check it's window size after a process completes
shopt -s checkwinsize
$
If you want to change the PATH for all users, perhaps to add /usr/local/bin (see Chapter 4 for details on what you can find in that directory), modify the /etc/profile contents as follows:
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
The .profile file can contain any shell command that you want to run automatically whenever you create a new Terminal. Some typical examples include changing the shell prompt, setting environment variables (values that control the operation of other Unix utilities), setting aliases, or adding to the search path (where the shell searches for programs to be run). A
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Unresponsive Terminal
During your Unix session, your terminal may not respond when you type a command, or the display on your screen may stop at an unusual place. That's called a "hung" or "frozen" terminal or session. Note that most of the techniques in this section apply to a Terminal window, but not to non-Terminal windows, such as a web browser.
A session can hang for several reasons. For instance, your computer can get too busy; the Terminal application has to wait its turn. In that case, your session resumes after a few moments. You should not try to "un-hang" the session by entering extra commands, because those commands will all take effect after Terminal comes back to life.
If your display becomes garbled, press Control-L. In the shell, this will clear the screen and display the prompt. In a full-screen program, such as a text editor, this keyboard shortcut redraws the screen.
If the system doesn't respond for quite a while (how long that is depends on your individual situation; ask other users about their experiences), the following solutions usually work. Try the following steps in the order shown until the system responds:
Press the Return key once
You may have typed text at a prompt (for example, a command line at a shell prompt) but haven't yet pressed Return to say that you're done typing and your text should be interpreted.
Try job control (see Chapter 7); type Control-Z
This control key sequence suspends a program that may be running and gives you a shell prompt. Now you can enter the jobs command to find the program's name, then restart the program with fg or terminate it with kill.
Press Control-C or ⌘-.
This interrupts a program that may be running. (Unless the program is run in the background; as described in Chapter 7, the shell waits for a background program to finish before giving a new prompt. A long-running background program may thus appear to hang the Terminal.) If this doesn't work the first time, try it once more; doing it more than twice usually won't help.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Exploring the Filesystem
Once you launch the Terminal, you can use the many facilities that Mac OS X provides at the command line, an environment that's quite a bit more powerful than the graphical interface you may be used to viewing. As a user, you have an account that gives you:
  • A place in the filesystem where you can store your files
  • A username that identifies you and lets you control access to files
  • An environment you can customize
In this chapter, you'll see how all the thousands of files on your Mac are organized, how to learn more details about any given file, and how to move around through Mac OS X's filesystem. You'll see that the Finder has been hiding quite a lot of information from you, entire directories with thousands of files that are invisible from the Finder but easily found and explored within the Terminal.
A file is the unit of storage in Mac OS X. A file can hold anything: text (a report you're writing, a to-do list), a program, digitally encoded pictures or sound, and so on. All of those are just sequences of raw data until they're interpreted by the right program.
Files are organized into directories (more commonly referred to as folders on the Aqua side of the Mac). A directory is actually a special kind of file where the system stores information about other files. You can think of a directory as a place, so that files are said to be contained in directories, and you work inside a directory. It's important that you realize that everything is a file in Unix. Whether you're working with a directory (perhaps moving files around) or editing a document, Unix fundamentally looks at everything as the same sort of container of information.
A filesystem includes all the files and directories on a mounted volume, such as your system's hard disk or your .Mac account's iDisk (which you mount on your system with a little help from WebDAV). This section introduces Mac OS X's filesystem, showing you how all the files on your Mac are organized and how to use Unix commands to explore your Mac's filesystem. Later sections show how you can look in files and protect them. Chapter 4 has more information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Mac OS X Filesystem
A file is the unit of storage in Mac OS X. A file can hold anything: text (a report you're writing, a to-do list), a program, digitally encoded pictures or sound, and so on. All of those are just sequences of raw data until they're interpreted by the right program.
Files are organized into directories (more commonly referred to as folders on the Aqua side of the Mac). A directory is actually a special kind of file where the system stores information about other files. You can think of a directory as a place, so that files are said to be contained in directories, and you work inside a directory. It's important that you realize that everything is a file in Unix. Whether you're working with a directory (perhaps moving files around) or editing a document, Unix fundamentally looks at everything as the same sort of container of information.
A filesystem includes all the files and directories on a mounted volume, such as your system's hard disk or your .Mac account's iDisk (which you mount on your system with a little help from WebDAV). This section introduces Mac OS X's filesystem, showing you how all the files on your Mac are organized and how to use Unix commands to explore your Mac's filesystem. Later sections show how you can look in files and protect them. Chapter 4 has more information.
When you launch the Terminal, you're placed in a directory called your home directory . This directory, which can also be viewed in the Finder by clicking the Home icon, contains personal files, application preferences, and application data such as Safari's bookmarks. In your home directory, you can create your own files, create other subdirectories, and so on. Like folders in a file cabinet, directories offer a way for you to organize your files.
You can find out where your home directory is at any time by typing the following command:
$ echo $HOME
/Users/taylor
$
As you can see, this tells me that my home directory (taylor) is found within the Users directory (/Users). In Unix, a forward slash ( / ) is used to separate directory names, with just a single slash signifying the very bottom, or
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Listing Files and Directories
To use the cd command, you must know which entries in a directory are subdirectories and which are files. The ls command lists entries in the directory tree and can also show you which is which.
When you enter the ls command, you get a list of the files and subdirectories contained in your working directory. The syntax is:
ls options directory-and-filenames
If you've just moved into an empty directory, entering ls without any arguments may seem to do nothing. This isn't surprising, because you haven't made any files in your working directory. If you have no files, nothing is displayed; you'll simply get a new shell prompt:
$ ls
$
But if you're in your home directory, ls displays the names of the files and directories in that directory. The output depends on what's in your directory. The screen should look something like this:
$ ls
Desktop         Library         Movies         Pictures          Sites
Documents       Mail            Music          Public            mac-rocks
$
Sometimes ls might display filenames in a single column. If yours does, you can make a multicolumn display with the -C option (multicolumn, sorted down) or the -x option (multicolumn, sorted across). ls has a lot of options that change the information and display format.
The -a option (for all) is guaranteed to show you some more files, as in the following example:
$ ls -a
.                      .bash_history      Desktop              Pictures
..                     .dvdcss            Documents            Public
.CFUserTextEncoding    .profile           Library              Sites
.DS_Store               .ssh                Mail                 mac-rocks
.Trash                 .sversionrc        Movies
.Xauthority            .viminfo           Music
$
When you use ls -a, you'll always see at least two entries named . (dot) and .. (dot, dot). As mentioned earlier, .. is always the relative pathname to the parent directory. A single . always stands for itself; believe it or not, this is useful with commands such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Protecting and Sharing Files
Mac OS X makes it easy for users on the same system to share files and directories. For instance, all users in a group can read documents stored in one of their manager's directories without needing to make their own copies (if the manager has allowed such access). The advantage of this is that you wouldn't need to send around files via email as attachments. Instead, if everyone can access those files, they can do so with some help from the Unix filesystem.
Here's a brief introduction to file security and sharing. If you have critical security needs, or you just want more information, talk to your system staff, or see an up-to-date book on Unix security such as Practical Unix and Internet Security , by Simson Garfinkel, Gene Spafford, and Alan Schwartz (O'Reilly).
Any user with admin privileges can use the sudo command (see "Superuser Privileges with sudo" later in this chapter) to do anything to any file at any time—regardless of what its permissions are. Access permissions won't keep your private information safe from everyone, although let's hope that you can trust the other folks who share your Macintosh! This is one reason that you want to be thoughtful about those to Directory Access Permissions
A directory's access permissions help to control access to the files and subdirectories in that directory:
  • If a directory has read permission (r), a user can run ls to see what's in the directory and use wildcards to match files in it.
  • A directory that has write permission (w) allows users to add, rename, and delete files in the directory.
  • To access a directory (that is, to read or write the files in the directory or to run the files if they're programs), a user needs execute permission (x) on that directory. To access a directory, a user must also have execute permission to all its parent directories—all the way up to the root.
Mac OS X includes a shared directory for all users: /Users/Shared
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Changing Your Password
The ownership and permissions system described in this chapter depends on the security of your username and password. If others get your username and password, they can log into your account and do anything you can, and if you have admin privileges, that could be anything—including deleting all your files. They can read private information, corrupt or delete important files, send email messages as if they came from you, and more. If your computer is connected to a network—whether to the Internet or a local network inside your organization—intruders may also be able to log in without sitting at your keyboard! See "Remote Logins" in Chapter 8 for one way this can be done.
Anyone may be able to get your username—it's usually part of your email address, for instance, or shows up as a file's owner in a long directory listing. Your password is what keeps others from logging in as you. Don't leave your password anywhere around your computer. Don't give your password to anyone who asks you for it unless you're sure he'll preserve your account security. Also, don't send your password by email; it can be stored, unprotected, on other systems and on backup tapes, where other people may find it and then break into your account.
If you think that someone knows your password, you should probably change it right away—although if you suspect that a computer "cracker" (or "hacker") is using your account to break into your system, you should ask your system administrator for advice first, if possible. You should also change your password periodically. Every few months is recommended.
A password should be easy for you to remember but hard for other people (or password-guessing programs) to guess. Here are some guidelines. A password should be between six and eight characters long. It should not be a word in any language, a proper name, your phone number, your address, or anything anyone else might know or guess that you'd use as a password. It's best to mix upper- and lowercase letters, punctuation, and numbers. A good way to come up with a unique but memorable password is to think of a phrase that only you might know, and use the first letters of each word (and punctuation) to create the password. For example, consider the password
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Superuser Privileges with sudo
Most Mac OS X user accounts run with restricted privileges; there are parts of the filesystem to which you don't have access, and there are certain activities that are prohibited until you supply a password. For example, when you run the Software Update utility from System Preferences, Mac OS X may ask you for your password before it proceeds. This extra authentication step allows Software Update to run installers with superuser privileges.
You can invoke these same privileges at the command line by prefixing a command with sudo (short for "superuser do"), a utility that prompts you for your password and executes the command as the superuser. You must be an administrative (or admin, for short) user to use sudo. The user you created when you first set up your Mac is an admin user . You can add new admin users or grant admin status to a user in System Preferences → Accounts, as shown in Figure 3-11.
Figure 3-11: When checked, the "Allow user to administer this computer" option in the Accounts preference panel gives a user administrative privileges, which also lets her use the sudo command
You may need to use sudo when you install certain Unix utilities, or if you want to modify a file you don't own. Suppose you accidentally created a file in the /Users directory while you were doing something else as the superuser. You won't be able to modify it with your normal privileges, so you'll need to use sudo:
$ ls -l logfile.out
-rw-r--r--    1 root     wheel     1784064 Nov  6 11:25 logfile.out
$ rm logfile.out
override rw-r--r--  root/wheel for logfile.out? y
rm: logfile.out: Permission denied
$ sudo rm logfile.out
Password:
$ ls -l logfile.out
ls: logfile.out: No such file or directory
If you use sudo again within five minutes, it won't ask for your password. Be careful using sudo, since it gives you the ability to modify protected files, all of which are protected to ensure the system runs properly.
I commonly find myself using sudo when I want to search across the entire filesystem without worry about disk permissions. For example, if
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exploring External Volumes
Earlier I mentioned that additional hard disks on your system and any network-based disks are all mounted onto the filesystem in the /Volumes directory. Let's take a closer look to see how it works:
$ ls /Volumes
110GB           Extra 30        Panther         X
$ ls -l /Volumes
total 8
drwxrwxrwx  29 taylor  staff     986 12 Jun 16:37 110GB
drwxrwxrwx  11 taylor  unknown   374  4 Jun 23:28 Extra 30
lrwxr-xr-x   1 root    admin       1 13 Jun 12:30 Tiger -> /
drwxrwxr-t  61 root    admin    2074 12 Jun 16:51 X
There are four disks available, one of which is actually the root (or boot) disk: Tiger. Notice that the entry for Tiger is different from the others, with the first character shown as l rather than a d. This means it's a link (see "Working with Links" in Chapter 4), which is confirmed by the fact that it's shown as Tiger in the regular ls output, while the value of the alias is shown in the long listing (you can see that Panther actually points to /).
If you insert a CD or DVD into the system, it also shows up in /Volumes:
$ ls -l /Volumes
total 12
drwxrwxrwx  29 taylor   staff     986 22 Sep 16:37 110GB
dr-xr-xr-x   4 unknown  nogroup   136 17 Aug  2001 CITIZEN_KANE
drwxrwxrwx  11 taylor   unknown   374  4 Sep 23:28 Extra 30
lrwxr-xr-x   1 root     admin       1 23 Sep 12:30 Tiger -> /
drwxrwxr-t  61 root     admin    2074 22 Sep 16:51 X
Plugging in an iPod and a digital camera proceeds as follows:
$ ls -l /Volumes
total 44
drwxrwxrwx  29 taylor   staff      986 22 Sep 16:37 110GB
dr-xr-xr-x   4 unknown  nogroup    136 17 Aug  2001 CITIZEN_KANE
drwxrwxrwx  11 taylor   unknown    374  4 Sep 23:28 Extra 30
drwxrwxrwx   1 taylor   admin    16384 19 Aug 20:54 NIKON D100
lrwxr-xr-x   1 root     admin        1 23 Sep 12:30 Tiger -> /
drwxrwxr-t  61 root     admin     2074 22 Sep 16:51 X
drwxr-xr-x  15 taylor   unknown    510 27 Apr 09:37 Zephyr
Zephyr is the name of the iPod, and NIKON D100 is the camera.
Now, for a neat trick, let's use Unix commands to look at the files on the iPod Zephyr:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: File Management
The previous chapter introduced the Unix filesystem, including an extensive discussion of the directory structure, the ls command for seeing what files are on your system, and how to move around using cd and pwd. This chapter focuses on Unix filenaming schemes—which aren't the same as names you'd see in the Finder, as you'll see—and how to view, edit, rename, copy, and move files.
As Chapter 3 explained, both files and directories are identified by their names. A directory is really just a special kind of file, so the rules for naming directories are the same as the rules for naming files.
Filenames may contain any character except /, which is reserved as the separator between files and directories in a pathname. Filenames are usually made of upper- and lowercase letters, numbers, dots (.), and underscores (_). Other characters (including spaces) are legal in a filename, but they can be hard to use because the shell gives them special meanings or otherwise forces you to constantly be changing how you work with these filenames on the command line.
Spaces are a standard part of Macintosh file and folder names, so while I recommend using only letters, numbers, dots, and underscores for filenames, the reality is that you have to work with spaces in file and directory names, because that's what Mac people do. Rather than naming a file myFile.txt as a Unix person would, most Mac folks are used to adding spaces to filenames, such as my file.txt. The Finder, by contrast, dislikes colons (which older versions of Mac OS used as a directory separator, just as Unix uses the forward slash). If you display a file called test:me in the Finder, the name is shown as test/me instead. (The reverse is also true: if you create a file in the Finder whose name contains a slash, it will appear as a colon in the Terminal.)
Though it's tempting to include spaces in filenames as you do in the Finder, if you're planning on doing any substantial amount of work on the Unix side, get used to using dashes or underscores in place of spaces in your filenames. It's 99 percent as legible, but considerably easier to work with.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File and Directory Names
As Chapter 3 explained, both files and directories are identified by their names. A directory is really just a special kind of file, so the rules for naming directories are the same as the rules for naming files.
Filenames may contain any character except /, which is reserved as the separator between files and directories in a pathname. Filenames are usually made of upper- and lowercase letters, numbers, dots (.), and underscores (_). Other characters (including spaces) are legal in a filename, but they can be hard to use because the shell gives them special meanings or otherwise forces you to constantly be changing how you work with these filenames on the command line.
Spaces are a standard part of Macintosh file and folder names, so while I recommend using only letters, numbers, dots, and underscores for filenames, the reality is that you have to work with spaces in file and directory names, because that's what Mac people do. Rather than naming a file myFile.txt as a Unix person would, most Mac folks are used to adding spaces to filenames, such as my file.txt. The Finder, by contrast, dislikes colons (which older versions of Mac OS used as a directory separator, just as Unix uses the forward slash). If you display a file called test:me in the Finder, the name is shown as test/me instead. (The reverse is also true: if you create a file in the Finder whose name contains a slash, it will appear as a colon in the Terminal.)
Though it's tempting to include spaces in filenames as you do in the Finder, if you're planning on doing any substantial amount of work on the Unix side, get used to using dashes or underscores in place of spaces in your filenames. It's 99 percent as legible, but considerably easier to work with.
Further, in the interest of having files correctly identified in both the Finder and Unix, you'd be wise to get into the habit of using the appropriate file extensions, too (i.e., .doc for Microsoft Word documents, .txt for text files, .xls for Excel spreadsheets, and so on). As an added bonus, this makes life easier for your less-fortunate (Windows-using) friends when you send them files.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File and Directory Wildcards
When you have a number of files named in series (for example, chap1.doc to chap12.doc) or filenames with common characters (such as aegis, aeon, and aerie), you can use wildcards to save yourself lots of typing and match multiple files at the same time. These special characters are the asterisk (*), question mark (?), and square brackets ([ ]). When used in a file or directory name given as an argument on a command line, the characteristics detailed in Table 4-1 are true.
Table 4-1: Shell wildcards
Notation
Definition
*
An asterisk stands for any number of characters in a filename. For example, ae* matches any filename that begins with "ae" (such as aegis, aerie, aeon, etc.) if those files are in the same directory. You can use this to save typing for a single filename (for example, al* for alphabet.txt) or to choose many files at once (as in ae*). A * by itself matches all file and subdirectory names in a directory, with the exception of any starting with a period. To match all your dot files, try .??*.
?
A question mark stands for any single character (so h?p matches hop and hip, but not hp or help).
[]
Square brackets can surround a choice of single characters (i.e., one digit or one letter) you'd like to match. For example, [Cc]hapter would match either Chapter or chapter, but chap[12] would match chap1 or chap2. Use a hyphen (-) to separate a range of consecutive characters. For example, chap[1-3] matches