Chapter 1. Inside the Terminal

The first order of business when exploring a new flavor of Unix is to find the command prompt. In Mac OS X, you won’t find the command prompt in the Dock or on a Finder menu. Instead, you’ll need to use the Terminal application, located in /Applications/Utilities. Inside the Terminal, Unix users will find a familiar command-line environment. In this chapter we’ll describe the Terminal’s capabilities, comparing them to the corresponding functionality of X11 terminal emulators such as xterm when appropriate. We’ll also highlight key features of some alternatives to the Terminal. The chapter concludes with a synopsis of the open command, which you can use to launch native Mac OS X applications from the Terminal, and a quick look at a freeware application that allows you to open a Terminal window from a Finder window.

Mac OS X Shells

Mac OS X comes with the Bourne Again SHell (bash) as the default user shell and also includes the TENEX C shell (tcsh), the Korn shell (ksh), and the Z shell (zsh). bash, ksh, and zsh are compatible with sh, the original Bourne shell. When tcsh is invoked through the csh link, it behaves much like csh. Similarly, /bin/sh is a hard link to bash, which also reverts to traditional behavior when invoked through this link (see the bash manpage for more information).

The version of bash that ships with Mac OS X is, according to its manpage, a conformant implementation of the Shell and Utilities portion of the IEEE POSIX Standard 1003.1 specification. Invoking bash with the --posix command-line option changes the default behavior of bash to comply with the POSIX 1003.1 standard in cases where the default behavior differs from this standard.

Note

Apple promotes Mac OS X 10.5.x Leopard as an Open Brand UNIX 03 registered product, conforming to the SUSv3 and POSIX 1003.1 specifications for the C API, Shell Utilities, and Threads.

If you install additional shells, you should add them to the /etc/shells file. To change the Terminal’s default shell, see Customizing the Terminal” later in this chapter. To change a user’s default shell (used for both the Terminal and remote console logins), see Modifying a user” in Chapter 5.

The Terminal and xterm Compared

There are several differences between Mac OS X’s Terminal application and the xterm and xterm-like applications common to Unix systems running the X Window System:

  • You cannot customize the characteristics of the Terminal with command-line switches such as -fn, -fg, and -bg. Instead, you must use the Terminal Inspector or the Terminal Preferences.

  • Unlike xterm, in which each window corresponds to a separate process, a single master process controls the Terminal. However, each shell session is run as a separate child process of the Terminal. You can force a separate instance of some applications, including Terminal, by using the open command with the -n and -a switches, as described later in this chapter.

  • A selection made in the Terminal is not automatically put into the clipboard. You use ⌘-C to copy and ⌘-V to paste. Even before you press ⌘-C, the selected text is contained in a location called the pasteboard. One similarity between the Terminal and xterm is that selected text can be pasted in the same window with the middle button of a three-button mouse (or with Shift-⌘-V). If you want to paste selected text into another window, you must drag and drop it with the mouse or use copy and paste. The operations described in The Services Menu,” later in this chapter, also use the pasteboard.

  • The value of $TERM is xterm-color when running under Terminal (it’s set to xterm under xterm by default).

  • Pressing Page Up or Page Down scrolls the Terminal window, rather than letting the running program handle it. Use Shift-Page Up or Shift-Page Down if you want a character-mode program to receive those keystrokes.

  • Terminal makes full use of Input Manager and CoreText, Mac OS X’s native text and graphics rendering engines, to fully support non-English languages and to make everything faster and smoother.

If you need an xterm, you can have it: simply type xterm in the Terminal and press Enter, and the X11 environment will start up along with an xterm window. See Chapter 7 for more information about the X Window System.

Note

Beginning with Leopard, the X11 package is installed by default. In earlier releases of Mac OS X, however, the X11 package was available as an optional installation. So, if you’re installing an earlier release of Mac OS X, you can either install X11 by selecting to “customize” your installation of Mac OS X, or you can install X11 from the installation DVD at a later time.

There are also Mac OS X-native applications that offer alternatives to Apple’s Terminal, such as Terminator and iTerm (both freeware applications). We’ll have more to say about these programs later in this chapter.

Using the Terminal

If you haven’t launched the Terminal, don’t open it just yet. First, drag Terminal’s application icon from the Utilities subdirectory of the Applications folder, and park it in the Dock so you’ll have quick access to it when you need to access the command line. (If you have launched it, drag its Dock icon to a different location along the Dock, or Control/right-click it and choose “Keep in Dock”). Now you’ve got the Terminal right where you can find it quickly. To launch the Terminal, click its icon in the Dock once.

Note

The full path to the Terminal is /Applications/Utilities/Terminal.app, although the Finder by default hides the .app extension. Terminal.app is not a binary file. Like all .app applications, it’s a Mac OS X bundle: a folder that contains a collection of files, including the binary and support files for the Terminal’s user interface.

You can Control-click (or right-click) on the Terminal in the Finder and select Show Package Contents to see what’s inside. You can also use the Unix commands ls and cd to explore the directory /Applications/Utilities/Terminal.app/.

After the Terminal starts, a Terminal window appears. It shows the last login, the tty name (the name of the Unix device for standard input), and a bash prompt. By default, the prompt consists of your computer name, a colon, and the current directory followed by a space, your username, and the $ character, as shown in Figure 1-1.

The Terminal window
Figure 1-1. The Terminal window

If you’d like to be greeted by a banner message each time you open a new Terminal window, you’ll have to create or edit the /etc/motd file (this file already existed in Mac OS X releases prior to Leopard). Regardless of whether you want to create an motd file or just change the message contained in an existing motd file, you’ll need administrative privileges to edit the file. The sudo vi /etc/motd command can be used to open the file in the vi editor as the superuser. You’ll need to be an administrative user to use sudo. When you execute a command preceded by sudo, you’ll be prompted for your password.

Note

The first user you create while installing Mac OS X is an administrative user, but you can also check the box marked “Allow user to administer this computer” when you create new users in System Preferences→Accounts.

Launching Terminal Windows

One difference xterm users will notice is that there is no obvious way to launch a new Terminal window with user-specified settings from the command line. For example, the Mac OS X Terminal has no simple equivalent to the following commands:

xterm &
xterm -e -fg green -bg black -e pine -name pine -title pine &

Instead, you create a new Terminal window by pressing ⌘-N or selecting Shell→New Window→Basic (or one of the other settings) from the menu bar. It is also possible to open a new Terminal window (or tab) with the help of osascript, which is a command-line program for executing AppleScript code. For example, the shell script (nw) shown in Example 1-1 opens a new Terminal window.

Example 1-1. A script to open a new Terminal window
#!/bin/sh
# Script nw opens a new Terminal window
osascript  <<EOF
tell app "System Events"
  keystroke "n" using command down
end tell
EOF

This shell script uses osascript to invoke AppleScript, which in turn interacts with System Events to achieve the effect of pressing ⌘-N. (In principle, this script should work when executed from other terminal emulators, provided that they make use of the ⌘-N keystroke to open new windows. For example, it works just as well with iTerm.)

You could also command the Terminal application directly. It supports the AppleScript verb “do script”. If you give it a blank script, it will just open a new window, as shown in Example 1-2.

Example 1-2. Another script to open a new Terminal window
#!/bin/sh
# Script: nw2
# Opens a new Terminal window
osascript  <<EOF
tell app "Terminal"
  do script ""
end tell
EOF

The menu bar selection Shell→New Window offers a mix of choices, which include: several predefined settings as well any custom settings you have defined. Of these, one menu option will have “⌘-N” next to it. That option will open a new window with your default settings for Terminal. The predefined settings include Basic, Grass, Homebrew, Novel, Ocean, Pro, and Red Sands, and they differ in their text, background color, and other attributes. Later, we’ll discuss how you can create your own settings.

Note

To cycle between open Terminal windows, you can use the same keystroke that most other Mac OS X applications use: ⌘-`. You can also switch between windows by pressing ⌘-Right Arrow or ⌘-Left Arrow, by using the Window menu, or by using the Terminal’s Dock menu (Control-click or right-click on the Terminal Dock icon). You can also jump to a particular Terminal window with ⌘-number (see the Window menu for a list of numbers). To cycle through tabs, use ⌘-{ or ⌘-}, or ⌘-Shift-Right Arrow or Left Arrow.

As an alternative to creating a new Terminal window, you can create a new Terminal tab within the current Terminal window by pressing ⌘-T or selecting Shell→New Tab→Basic (or some other setting from the list) from the menu bar. Terminal tabs may be opened with different predefined settings, just like Terminal windows. For example, you may have a Basic tab and a Homebrew tab in the same Terminal window. You can rearrange the order of tabs within a Terminal window by dragging a tab with your mouse, just as you can with Safari or Firefox tabs. You can also move an active tab to a new window by selecting Window→Move Tab to New Window from the menu bar. Alternatively, you can move a tab to a new window by dragging it with your mouse onto the desktop, provided that the tab is not the active one in the window. And, should you decide that you have too many open Terminal windows, you can merge all of them into one Terminal window as tabs by selecting Window→Merge All Windows from the menu bar. In that case, each open Terminal window will become a tab in a single window. Figure 1-2 shows several tabs within the same Terminal window, with the rightmost tab active.

A Terminal window with several tabs
Figure 1-2. A Terminal window with several tabs

You can customize startup options for new Terminal windows by creating a new setting, and if you’d like, you can export the new settings to .terminal files. Those files can subsequently be imported into your other Macs that are running Leopard or sent to other users. See Exporting and Importing Terminal Settings” later in this chapter for more details.

Double-clickable shell scripts

Executable shell scripts are double-clickable in Mac OS X. That is, when you double-click any executable script in the Finder, a new Terminal window will open to run the script. The new window will open with Terminal’s default settings. However, you can stuff the shell script full of osascript commands to set the Terminal window’s characteristics after it launches. The osascript command lets you run AppleScript from the command line. Example 1-3 shows a shell script that sets the size and title of the Terminal window and then launches the vim editor.

Example 1-3. Launching the vim editor
#!/bin/sh
# Script RunVim
osascript  <<EOF
tell app "Terminal"
  set number of rows of first window to 34
  set number of columns of first window to 96
  set custom title of first window to "Vim Editor"
end tell
EOF
vim $@

As with any shell script, you’ll need to make it executable before you can run it. For example, to make RunVim executable, you would issue the following chmod command:

chmod +x RunVim

You can assign a custom-made icon to your shell scripts. To change a script’s icon, use the following procedure:

  1. Copy the desired icon to the clipboard.

  2. Select your script in the Finder and open the Get Info window (⌘-I). The file’s icon appears in the upper-left corner.

  3. Click the current icon so that it is highlighted, and use the Paste option (Edit→Paste or ⌘-V) to paste the new icon over it.

  4. Close the Get Info window by typing ⌘-W. The pasted icon is now associated with the script.

To add the shell script application to the Dock, locate the application in the Finder and drag its icon to the Dock. Now you can click on the script’s Dock icon to invoke the script. You can also drag the executable’s icon to the Places section of the Finder’s Sidebar, although this section of the Finder is intended primarily for quick access to frequently visited folders.

The Contextual Menu

Users familiar with the X Window System know that right-clicking an xterm window opens a terminal-related contextual menu. Mac OS X’s Terminal also has a contextual menu that can be accessed by Control-clicking (or right-clicking, if you have a two- or three-button mouse). In Tiger, the Terminal contextual menu includes the choices Copy, Paste, Paste Selection, Paste Escaped Text, Select All, Clear Scrollback, Send Break (equivalent to Control-C), Send Hard Reset, Send Reset, and Window Setting. Each of these items also has a keyboard shortcut. In Leopard, the contextual menu choices are limited to Search in Spotlight, Search in Google, Look Up in Dictionary, Copy, Paste, and Show Inspector. The contextual menu items from Tiger’s Terminal are available as various menu bar items in Leopard.

Customizing the Terminal

As noted earlier, you can customize many attributes of Terminal windows (and tabs) through the Terminal application’s Preferences. In this section, we’ll discuss tweaking the Terminal’s Preferences and some on-the-fly customizations you can make.

Preferences

Terminal’s Preferences are organized into four panes: Startup, Settings, Window Groups, and Encodings. In the Encodings preference pane, you can select various encodings required for a wide variety of languages. The other three groups of preferences require further discussion.

Startup

Under the Startup preference pane, you can configure Terminal so that when it starts, either a new window with a particular setting is opened, or a window group (see the upcoming section Window groups”) is opened. The other item you can configure in the Startup preference pane is listed under “Shells open with”. One choice is the system login utility (/usr/bin/login), and the other selection is the complete path of some specific command, such as an alternative shell. This is similar to the “Run command” option that’s available on the Shell tab for a particular Terminal setting, but the choice you make in “Shells open with” affects all Terminal settings unless you’ve specified a “Run command” and also deselected the “Run inside shell” option in the setting. (Otherwise, the “Run command” is fed into your shell of choice.)

Note

You can change the default shell in the Terminal Preferences, but this change applies only to Terminal (i.e., it will not affect the login shell used for remote or console logins). Changing a user’s default shell is covered in Modifying a user” in Chapter 5.

Settings

Though we briefly discussed some of the options available in the Settings preference pane earlier, let’s now take a closer look. The predefined settings are listed in the left subwindow of the Settings pane, and the options associated with each setting are accessible via a set of tabs in the right subwindow. The options are organized into five categories: Text, Window, Shell, Keyboard, and Advanced. Table 1-1 summarizes the options available on each tab.

Table 1-1. Options for Terminal settings

Tab

Options

Text

Font: Choose your font.

Text: Enable and disable attributes such as antialiasing, bold fonts, blinking text, American National Standards Institute (ANSI) colors, and bright colors for bold text.

Cursor: Select a cursor style and color, and turn blinking on or off.

Window

Title: Specify your own window title and indicate whether to include in that title the active process name, shell command name, setting name, tty name, dimensions, and command key.

Background: Set the color and opacity (no background image).

Window size: Set the number of rows and columns.

Scrollback: Set the size of the scrollback buffer (the number of rows of previous input and output you can scroll upwards to review).

Shell

Startup: Choose a command to run on startup (for example, an alternate shell).

When the shell exits: Specify an action to take when the shell exits (e.g., when you type logout or exit). Choices include “Close the window,” “Close if the shell exited cleanly,” and “Don’t close the window.”

Prompt before closing: Indicate when to prompt when closing a Terminal window. Choices include “Always,” “Never” (the default), or “Only if there are processes running other than [those in the specified list].”

Keyboard

This tab controls key mappings for function, arrow, page up/down, and other keys.

Advanced

Declare your terminal (i.e., set the terminal type variable, $TERM) as ansi, dtterm, rxvt, vt52, vt100, vt102, xterm, or xterm-color (the default); have the Delete key send a Control-H; escape non-ASCII input; paste newlines as carriage returns (on by default); enforce strict VT-100 keypad behavior; scroll to the bottom on input; toggle the audible and visual bells; and set the international character encoding.

In pre-Leopard releases, one configurable option was “Option-click to position cursor.” If you enabled this feature, you were able to Option-click with the mouse to position the cursor in Terminal applications such as vim or Emacs (saving you many keystrokes when you needed to move the insertion point). This option also worked over a remote login session, if the behavior was supported by the remote host’s terminal capabilities. Beginning in Leopard, the Option-click behavior is the default behavior.

Window groups

There are situations in which you will want to routinely have several Terminal windows and tabs open, each having its own process and attributes. For example, you might be editing a file with vim in one window and running octave in another, with both windows having black backgrounds and white text. At the same time, you might be monitoring some output file using tail in another Terminal window, this one having a fixed size of 80 rows ×80 columns and displaying black text on a white background. If this setup is one that you use frequently, you’re in luck: you can save the time that it normally takes you to get things going by saving that set of Terminal windows as a window group.

Before you can establish a window group, you’ll need to define a setting (under the Settings preference pane) corresponding to each window that will be in the window group. When defining a setting, be sure to specify the commands, if any, that must run when a window (or tab) opens with that particular setting. Next, open the Terminal windows (and tabs) that will go into the window group to make sure that the settings work properly. Once you’re satisfied that the settings are correct for the window group’s Terminal windows, make sure that only those windows that are to be members of the group are open. Then, select Window→Save Windows as Group. This selection will give you the opportunity to enter a name for the new window group and decide if the window group should open by default whenever the Terminal application starts. If you don’t elect to start the window group by default, you can always make that choice later in Terminal’s Startup preference pane. In the Window Group preference pane, you can delete window groups, export window groups as .terminal files, or import window groups.

Once you’ve established a window group, you can open it by selecting Window→Open Window Group→Window_group_name.

Customizing the Terminal on the Fly

You can customize the Terminal in shell scripts using escape sequences or AppleScript commands. xterm users may be familiar with the following command to set the xterm window’s title:

echo '^[]0;My-Window-Title^G'

Mac OS X’s Terminal accepts this sequence as well.

^[ is the ASCII ESC character, and ^G is the ASCII BEL character. (The BEL character rings the Terminal bell, but in this context, it terminates an escape sequence.) The escape sequences described here are ANSI escape sequences. ANSI escape sequences are used to manipulate a Terminal window (such as by moving the cursor or setting the title).

To type the ^[ characters on the command line in bash or tcsh, use the key sequence Control-V, Control-[ (press Control-V and release, then press Control-[). To type ^G, use Control-V, Control-G. The vim editor supports the same key sequence, whereas Emacs uses Control-Q instead of Control-V.

You can capture the bash escape sequence in a function that you can include in your .bash_profile script:

function set_title ( )
{
    case $TERM in
        *term | xterm-color | rxvt | vt100 | gnome* )
            echo -n -e "\033]0;$*\007" ;;
        *)  ;;
    esac
}

Then you can change the title by issuing the following command:

$ set_title your fancy title here

You may want to package this as a shell script and make it available to everyone who uses your system, as shown in Example 1-4.

Example 1-4. Setting the Terminal title in a shell script
#!/bin/bash
#
# Script settitle
# Usage:  settitle title
#
if [ $# == 0 ]; then
  echo "Usage:  settitle title"
else
   echo -n -e "\033]0;$*\007"
fi

You can also use osascript to execute AppleScript commands that accomplish the same thing:

osascript -e \
  'tell app "Terminal" to set custom title of first window to 
  "Hello, World"'

Exporting and Importing Terminal Settings

If you want to save your customizations, the procedure to follow depends on whether you are running Mac OS X 10.4 Tiger or 10.5 Leopard.

Saving Terminal settings in Mac OS X 10.4 Tiger

In pre-Leopard Mac OS X releases, you can launch a customized Terminal window from the command line by saving some prototypical Terminal settings to a .term file and then using the open command to launch the .term file. (For more information on open, see The open Command,” later in this chapter.) You can also launch a .term file by double-clicking it in the Finder. To create a .term file in Tiger, open a new Terminal window, then open the Terminal Inspector (File→Show Info or ⌘-I) and set the desired attributes, such as the window size, font, and text and background colors. Then save the Terminal session (File→Save or ⌘-S) to a .term file, such as proto.term. If you save this file to ~/Library/Application Support/Terminal, you’ll be able to launch a new Terminal window with the proto.term file’s special attributes from the File→Library menu.

Alternatively, you can launch such a Terminal window from the command line by issuing a command like one of the following (depending on where you saved proto.term):

$ open ~/Library/Application\ Support/Terminal/proto.term
$ open ~/Documents/proto.term

The .term file is an XML property list (plist) that you can edit with a text editor such as vim (it can be invoked with vi, which is a symbolic link to vim) or with the Property List Editor application (/Developer/Applications/Utilities).[1] By default, opening the .term file creates a new Terminal window with the specified settings. You can configure the window so that it executes a command upon opening by adding an execution string to the .term file. When you launch the Terminal window, this string is echoed to standard output before it is executed. Example 1-5 shows an execution string that connects to a remote host via ssh and exits when you log out.

Example 1-5. An execution string to connect to a remote host
<key>ExecutionString</key>
<string>ssh xyzzy.oreilly.com; exit</string>

Saving Terminal settings in Mac OS X 10.5 Leopard

In Leopard, the closest thing to .term files are settings you create in the Terminal Preferences. Settings can be exported as (or imported from) .terminal files. Older .term files can also be imported as settings, so don’t panic if you switched to Leopard from an earlier release of Mac OS X and don’t want to lose all your .term files. We’ll discuss how to import .term files later.

Terminal 2.0, which ships with Leopard, comes with several predefined settings. You can quickly see which predefined settings are available in the Terminal Inspector by opening a new Terminal window and then selecting Shell→Show Inspector from the menu bar or by pressing ⌘-I. You can also use the Inspector to change the setting of an open Terminal window or tab to another available predefined setting, as shown in Figure 1-3.

Changing a Terminal window setting with the Inspector
Figure 1-3. Changing a Terminal window setting with the Inspector

To create a new custom setting, select Terminal→Preferences from the menu bar (or press ⌘-,) and then select the Settings preference pane. On the left side of the Settings window, you’ll see a listing of the predefined settings. The right portion of the Settings window shows the options associated with the currently selected setting.

You can define a new setting by clicking on the plus sign (+) at the bottom left of the Settings window and giving the new setting whatever name you want. In the example that follows, we’ve used “Proto.” Once that’s done, you can click the new setting (e.g., Proto) in the left side of the Settings window and set its attributes on the right.

Warning

Each time you add a new setting, that new setting becomes your default.

Settings are saved in the ~/Library/Preferences/com.apple.Terminal.plist file. You’ll be able to launch a new Terminal window with your new setting’s special attributes from either the Shell→New Window menu or the Shell→New Tab menu.

You can also export your new setting as a .terminal file, which can be imported in another Leopard installation later. This is done as follows. In the Settings window, select the setting to be exported (e.g., Proto), then click on the gear icon (see Figure 1-4) at the bottom of the left part of the window and select Export to save the setting to a .terminal file, such as Proto.terminal. You can save the .terminal file to a convenient location, such as ~/Documents. Like .term files in older Mac OS X versions, a .terminal file is an XML property list (plist), which you can edit.

Exporting a setting as a .terminal file
Figure 1-4. Exporting a setting as a .terminal file

Warning

Although double-clicking a .term file in older Mac OS X versions opens a new Terminal window with the attributes defined in that file, double-clicking a .terminal (or .term) file in Leopard imports the settings it contains into Terminal’s configuration. Every time you launch a given .terminal file, a new setting with the attributes defined in that .terminal file is created in Terminal’s Preferences. The primary purpose of a .terminal file in Leopard is to save a setting that you can import to another Leopard installation. This means that .terminal files cannot be used to open new Terminal windows.

You can import a .terminal (or .term) file into the Terminal’s list of settings without launching it by clicking on the gear icon at the bottom of the left part of the Settings window, selecting Import, and navigating to the desired .terminal file in the file browser that appears.

Working with File and Directory Names

Although Unix supports complex file and directory names containing spaces, Unix users have traditionally avoided using spaces in file and directory names. Instead, they may use capitalization or hyphens or underscores to imply spaces, as follows:

textFile.txt
text-file.txt
text_file.txt

However, most Mac users tend to insert spaces into file and directory names, and these names are often long and descriptive. Although this practice is okay if you’re going to work in the graphical user interface (GUI) all the time, it creates a small hurdle to jump over when you’re working on the command line. Unix shells will interpret a string containing embedded spaces as separate command-line arguments. A command such as the following, for example, would fail because the shell would interpret the string as separate arguments:

$ cd ~/Documents/My Shell Scripts

To get around this, you have two choices: escape the spaces, or quote the entire file or directory name.

Note

By default, files whose names begin with a dot are invisible in the Finder. You can make files named with a leading dot visible in the Finder by entering the command defaults write com.apple.finder AppleShowAllFiles true and then restarting the Finder with the command killall Finder.

To escape a space on the command line, simply insert a backslash (\) before the space. This also works with other special characters, such as parentheses. The following special characters have meaning to the shell and so must be escaped: * # ` " ' \ $ | & ? ; ~ ( ) < > ! ^. Here is an example of how to use a backslash to escape a space character in a file or directory name:

$ cd ~/Documents/My\ Shell\ Scripts

Alternatively, you can use quotation marks around the file or directory name that contains the space, as follows:

$ cd ~/Documents/"My Shell Scripts"

There is one other way to get around this problem, but it involves using the Finder in combination with the Terminal application. Let’s look at an example. To launch Microsoft Word 2008 from the Terminal, you could enter the path as follows, using escape characters:

$ open -a /Applications/Microsoft\ Office\ 2008/Microsoft\ Word

Or you could enter the path using quotes:

$ open -a "/Applications/Microsoft Office 2008/Microsoft Word"

As you can see, neither method is very pretty, and both require you to know a lot of detail about the path. Now for the easy way:

  1. Type the name of the command and any initial arguments it requires on the command line (in this case, open -a), followed by a space. Don’t press Return yet!

  2. Locate Microsoft Word in the Finder, and drag its icon to the Terminal window to insert the path after the space. When you do this, the spaces and any other special characters in the path will automatically be escaped with backslashes:

    $ open -a /Applications/Microsoft\ Office\ 2008/Microsoft\ Word
  3. Press Return to invoke the command and launch Word 2008.

You can also drag and drop URLs from a web browser. For example, to use curl to download files from the command line:

  1. Open a new Terminal window and type curl -O, with a space after the -O switch.

  2. Bring up your web browser and navigate to http://www.oreilly.com.

  3. Drag the image at the top of the page to the Terminal window. You should now see the following in the Terminal window:

    $ curl -O http://www.oreilly.com/graphics_new/header_main.gif
  4. Press Return in the Terminal window to download header_main.gif to your computer.

Tab Completion

If you want to type a long pathname, you can cut down on the number of keystrokes required by using tab completion. For example, to enter the path /Library/StartupItems, you can type /Li<Tab>, which gives you /Library/. (This works because /Library/ is the only folder at the root of the filesystem whose name begins with the letter “L.”) Next, type S<Tab>. This time, because there is more than one folder under /Library/ that begins with the letter “S,” instead of the path being completed automatically, you’re given a choice of completions: Screen Savers, Scripts, Security, Spotlight, and StartupItems. Type as many letters as are necessary to narrow down your choice, followed by a Tab (in this case, t<Tab>). The full key sequence for /Library/StartupItems would be /Li<Tab>St<Tab>.

If you have multiple completions where a space is involved, you can type a literal space with \<Space>. For example, suppose you have two directories, PROJECT FOLDER and PROJECT. To get a completion for PROJECT FOLDER, you could use PRO<Tab>\ <Space><Tab>. The first <Tab> completes the word PROJECT, begun with the string “PRO”. Adding the string “\ ” at this point and pressing Tab again completes the folder name PROJECT FOLDER.

Changing Your Shell

Although other shells are available in Mac OS X, as we noted earlier, the default shell in Mac OS X releases beginning with Tiger is bash. (Early versions of Mac OS X shipped with tcsh as the default shell.) You can change the default shell for Terminal in its Preferences menu, but this does not affect the login shell used for remote or console logins. To change your default shell in a more pervasive manner, see Modifying a user” in Chapter 5.

Note

If you install additional shells on the system, you’ll need to add them to the /etc/shells file to make Mac OS X aware that they are legitimate shells.

The Services Menu

The Mac OS X Services menu (Terminal→Services) exposes a collection of services that can work with the currently running application. In the case of the Terminal, the services operate on text that you have selected (the pasteboard). To use a service, select a region of text in the Terminal window and choose one of the following items from the Services menu:

ChineseTextConverter

This service can be used to convert selected text to either simplified Chinese or traditional Chinese.

Disk Utility

This service invokes Disk Utility to calculate either a CRC-32 or an MD5 image checksum of a disk whose path has been selected in the Terminal window.

Finder

Once you have selected a filename in the Terminal window, the Finder Services menu allows you to open that file (Finder→Open), show its enclosing directory (Finder→Reveal), or show its information (Finder→Show Info).

Font Book

Not supported by the Terminal.

Grab

Not supported by the Terminal.

Import Image

Not supported by the Terminal.

Mail

The Mail→Send To service allows you to compose a new message to an email address, once you have selected that address in the Terminal window. You can also select a region of text and choose Mail→Send Selection to send a message containing the selected text.

Make New Sticky Note (Shift-⌘-Y)

This service creates a new Sticky (/Applications/Stickies) containing the selected text.

Open URL

This service opens the URL specified by the selected text in your default web browser.

Script Editor

This service gets the result of an AppleScript (after running the highlighted text as an AppleScript), makes a new AppleScript (in the Script Editor), or runs the selected text as an AppleScript without returning the result.

Search With Google (Shift-⌘-L)

This service searches for the selected text using http://google.com in your default web browser.

Send File To Bluetooth Device (Shift-⌘-B)

This service displays a dialog that lets you choose a file to send to a Bluetooth device.

Speech

This service begins speaking the selected text. (Use Speech→Stop Speaking to interrupt.)

Spotlight (Shift-⌘-F)

This service invokes Mac OS X’s system-wide search technology, Spotlight, to search for the selected text. (Mac OS X provides command-line utilities for working with Spotlight. See Chapter 2.)

Summarize

This service condenses the selected text into a summary document. The summary service analyzes English text and makes it as concise as possible while retaining the original meaning.

TextEdit

The TextEdit service can open a filename, or open a new file containing the selected text.

When you use a service that requires a filename, you should select a fully qualified pathname, not just the filename, because the service does not know the shell’s current working directory. (As far as the service is concerned, you are invoking it on a string of text.)

Third-party applications may install additional services of their own.

Bonjour

Bonjour (http://developer.apple.com/networking/bonjour/index.html), originally announced in 2002 as Rendezvous, is a networking technology that allows Bonjour-enabled devices on a local network to automatically discover each other. It is based on a standard called ZeroConf (http://www.zeroconf.org) and allows computers on a network to assign useful IP addresses among themselves, without the need for a DHCP server (or, as the ZeroConf working group puts it, “a man in a white lab coat”). Bonjour works with multicast DNS (mDNS) and DNS Service Discovery (DNS-SD) to allow your Mac to discover computers and services (such as SSH and web servers) on the local network.

Like many Mac OS X applications (e.g., iTunes), Terminal is Bonjour-enabled. For example, you can select Shell→New Remote Connection (or press Shift-⌘-K) to make an SSH connection to any other Mac OS X system on the local area network (LAN), provided it allows such connections. The other Macs on the LAN are identified by their computer names, as specified in their Sharing System Preferences panes.

If you have computers with other operating systems on your network, they may be able to take advantage of Bonjour, too. Apple makes a Bonjour for Windows available at http://www.apple.com/support/downloads/bonjourforwindows.html, and most current Linux distributions include the avahi package, which provides what you need to work with Bonjour services from Linux.

Note

You can learn more about Bonjour by reading Apple’s Bonjour Overview Document, available here: http://developer.apple.com/documentation/Cocoa/Conceptual/NetServices/NetServices.pdf.

Alternative Terminal Applications

As noted earlier, other Aqua-native terminal applications are available; the freeware iTerm (http://iterm.sourceforge.net), developed by Fabian and Ujwal S. Sathyam, is a particularly attractive one. Although Mac OS X’s Terminal is rich with useful features, iTerm offers some interesting features that make it worthy of consideration. We won’t cover iTerm in great detail, but we will touch on a few of its more attractive aspects.

Before getting into what makes iTerm distinct, here are some similarities between iTerm and Terminal:

  • iTerm and Terminal use the same Services menu.

  • Both iTerm and Terminal support transparency, language encodings, and AppleScript, and both have contextual menus that can be accessed by Control-clicking (or right-clicking, if you have a two- or three-button mouse) in a window. iTerm has a slightly more extensive contextual menu than Terminal, though.

  • Both iTerm and Terminal (beginning with Leopard) support tabs.

  • Both iTerm and Terminal support Bonjour.

iTerm supports several language encodings, xterm-color/vt100/xterm-new/xterm-256color/ansi/rxvt/linux emulations, and many GUI features. Particularly interesting features of iTerm include support for multiple tabbed terminal sessions within each window, support for background images, profiles that allow you to open new iTerm sessions with preset terminal settings, and bookmarks for launching iTerm windows or tabs that automatically execute commands. The default value for $TERM is xterm-color, but this can be changed either on the fly, with a bash shell command such as TERM=vt100, or by selecting Bookmarks→Manage Profiles→Terminal Profiles and adjusting the Terminal Settings Type field.

iTerm’s tabbed view is similar to Terminal’s tabbed view, as shown in Figure 1-5.

Using tabs with iTerm
Figure 1-5. Using tabs with iTerm

Tabs in iTerm can be dragged to new windows, and one iTerm window can be dragged onto another to form a new tab. The effect of dragging and dropping windows and tabs in iTerm is no different from the same set of actions in Terminal. Additionally, the same bash (or tcsh) shell commands that can be used to customize the Terminal’s title bar and tabs work just as well in iTerm, as shown in Figure 1-6.

Customized tab labels in iTerm
Figure 1-6. Customized tab labels in iTerm

iTerm’s support for profiles and bookmarks is similar to Terminal’s support for settings. Bookmarks are used to define iTerm sessions with preset terminal settings. For example, you can define the color or typeface to use for text as well as a command to execute upon opening a new tab or window with a given bookmark. Aside from the command that a bookmark will execute, other attributes must be selected from predefined profiles. There are three types of profiles in iTerm: Keyboard, Terminal, and Display profiles. To define new profiles, select Bookmarks→Manage Profiles (or press Option-⌘-B) to access the Profiles window, shown in Figure 1-7. Click the Add button at the bottom left of the Profiles window to add a new profile in any of the three categories. After you’ve added a new profile, select it in the left subwindow of the Profiles window to reveal its options in the right subwindow, as shown in Figure 1-7.

Adding a Terminal profile in iTerm
Figure 1-7. Adding a Terminal profile in iTerm

While a profile determines certain attributes of an iTerm window (or tab), bookmarks are used to open windows and tabs with those attributes. A bookmark may also be defined to execute commands within a window or tab.

The default bookmarks are Default, which specifies the default login shell, and Bonjour, which includes ssh and sftp connections to SSH- and Bonjour-enabled computers on the LAN. To define a new bookmark, select Bookmarks→Manage Bookmarks (or press Shift-⌘-B). Then, click the plus sign in the bottom-left corner of the Bookmarks window to add a new bookmark. You’ll need to specify the bookmark’s name, and a command (which can be a login shell). You may also select predefined Terminal, Keyboard, and Display profiles as well as a shortcut key, as shown in Figure 1-8.

Adding a new iTerm bookmark
Figure 1-8. Adding a new iTerm bookmark

The bookmark’s name is used when you open a session from the New icon in iTerm’s toolbar. You can also create a bookmark group (similar to Terminal’s window groups), by clicking on the icon with the red plus sign to add a folder in the bookmark listing and then, in the Bookmarks window, dragging and dropping bookmarks onto the new bookmark folder. Figure 1-9 shows a Bookmark folder with two bookmarks, in the Bookmark window.

A bookmark group in iTerm
Figure 1-9. A bookmark group in iTerm

Once you’ve defined a bookmark group, you can open any individual bookmark in the bookmark group by selecting Bookmarks→BookmarkGroupName→Individual Bookmark. If no iTerm window is open, the bookmark will open in a new iTerm window; otherwise, the bookmark will open in the frontmost iTerm window. If you’d like to open every member of the bookmark group at the same time, you can select Bookmarks→BookmarkGroupName→Open All. In this case, the set of bookmarks associated with the group will open as tabs within the same iTerm window. If at least one iTerm window is already open, the group will open as tabs in the frontmost window, adding to whatever tabs are already present in that window. The effect of an iTerm bookmark group is similar to that of a window group in Terminal, but Terminal window groups are not restricted to opening as tabs in the same window.

Note

Though we’ve borrowed Terminal’s “window group” terminology to describe iTerm’s bookmark folders as “bookmark groups,” iTerm actually had the bookmark group capability (along with tabs) several years before Terminal received a major overhaul for Leopard.

iTerm’s contextual menu (the menu that appears when you right-click or Control-click in a window) consists of the following items: New Tab (allows you to choose a session from the bookmarks), Select (selects a tab from the current window), Browser (opens the selected URL in your default web browser), Mail (opens a compose mail window with the selected email address as the recipient), Copy, Paste, Save, Select All, Clear Buffer, Info, and Close.

Although iTerm had some clear advantages over Terminal in pre-Leopard releases of Mac OS X (most notably bookmarks and tabs), that is no longer the case at the time of this writing, considering the impressive array of features in Leopard’s Terminal application. The one feature that could tip the scale in favor of iTerm is its support of background images in iTerm windows, assuming that this feature is of paramount importance to you. Oddly enough, Tiger’s version of the Terminal application supported background images, but it lacked tabs and window groups. Overall, with the addition of useful features such as tabs and window groups, Leopard’s Terminal application makes the search for an alternative much less appealing than it was in Tiger.

Note

Terminator (http://software.jessies.org/terminator/) is a cross-platform, Java-based, freeware alternative to Terminal. Though it supports tabs, its feature set seems to come up short when compared to Terminal and iTerm. On the other hand, if having a cross-platform terminal emulator program is important to you, this one is worth a try.

The open Command

The open shell command lets you open Finder windows and launch Aqua applications. To open a directory in the Finder, use open followed by the name of the directory. For example, to open a Finder window containing the current directory, enter the following command:

$ open .

To open your Public folder (~/Public) in a Finder window, use the following:

$ open ~/Public

To open the /Applications folder in a Finder window, use the following:

$ open /Applications

To open an application, you need only its name and the -a switch. For example, to open Xcode (/Developer/Applications), you would use the following:

$ open -a Xcode

To open multiple instances of a program, give the -n switch a whirl (but note that some applications, such as Firefox, may refuse to open a second instance):

$ open -n -a Terminal

Note

You are not required to enter the path for the application, only its name. The only time you are required to enter the path is if you have two different versions of an application with similar names on your system.

You can also use the -a option to open a file with something other than the application with which it’s associated. For example, to open an XML file in Xcode instead of the default XML editor, the Property List Editor, enter this command:

$ open -a Xcode data.xml

To open multiple files, you can use wildcards:

$ open *.c

To force a file to be opened with TextEdit, use -e:

$ open -e *.c

The -e option directs the file to be opened in TextEdit; it cannot be used to open a file in another text editor, such as BBEdit, Smultron, or TextMate However, if you want to open a file using BBEdit, you can use the following:

$ open -a BBEdit filename

Note

Many popular text editors include their own command-line applications for editing documents from the command line: BBEdit uses bbedit, TextWrangler has edit, Smultron gives you smultron (after you choose Help→Install Command-Line Utility from within Smultron), and TextMate uses mate.

If you want to use TextEdit on a file that is owned by an administrator (or root), sudo open -e won’t work. You’ll need to specify the full path to the TextEdit executable, as in:

$ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit filename

If you find yourself doing this often, you might want to create an alias for the path to TextEdit’s executable file. For example, you could enter the following into your .bash_profile file:

alias sudotext="sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit "

Then, the next time you want to open a text file that would otherwise require use of the sudo command, you could just enter the following:

$ sudotext filename

When you enter that command, you’ll be prompted for the admin password; once authenticated, the file you’ve specified will be opened in TextEdit, just as you hoped it would.

Note

In pre-Leopard Mac OS X releases, the open-x11 command is used to open X11-based applications in Apple’s X11 environment. In Leopard, you can simply launch the X11 application as you would any other Unix application, as in:

$ xeyes

You can learn more about X11 in Chapter 7.

While the open command can be used to open a specific directory in a Finder window from Terminal (for example, with open /Applications), you might conversely want to open a Terminal window with its working directory set to the directory in the current Finder window. A nifty little freeware application that makes this process easy is Thomas Wiesehöfer’s OpenTerminal (http://homepage.mac.com/thomasw/OpenTerminal/). To install OpenTerminal, download it from the OpenTerminal website, unzip the downloaded file, then drag and drop the enclosed OpenTerminal application icon to a convenient location (e.g., /Applications/Utilities). Then, open another Finder window and select View→Customize Toolbar. Finally, drag the OpenTerminal icon to the Finder toolbar, as shown in Figure 1-10.

Installation of OpenTerminal in the Finder toolbar
Figure 1-10. Installation of OpenTerminal in the Finder toolbar

Once OpenTerminal has been installed, you can click on its icon in the Finder toolbar to open a Terminal window with its working directory set to the directory in the current Finder window, as shown in Figure 1-11.

The first time you execute OpenTerminal you’ll be presented with its Preferences window, in which you can configure OpenTerminal’s various settings. If you want to change a setting in the Preferences later, you’ll need to launch OpenTerminal by Option-clicking on its icon in the Finder toolbar.

Using OpenTerminal
Figure 1-11. Using OpenTerminal

Finally, if you’d like to be able to open a Terminal window by Control/right-clicking on a folder in the Finder and selecting More→Open Terminal, you can add this optional contextual menu item by installing OpenTerminalContextMenu.plugin. To install the contextual menu item, drag and drop it into either /Library/Contextual Menu Items (if you want to give this capability to all users) or ~/Library/Contextual Menu Items (if you’d like to keep this capability to yourself).



[1] For more information on XML, see Learning XML by Erik T. Ray or XML in a Nutshell by Elliotte Rusty Harold and W. Scott Means (both from O’Reilly).

Get Mac OS X For Unix Geeks, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.