Chapter 38. Using Basic Unix Commands

In the past several years, an operating system known as Linux has sprung from obscurity to the front page of every IT publication in the world. Unix-based operating systems are powerful and stable, but many average computer users have been intimidated by their complexity. Also, traditionally, people had to access Unix systems from the command line, by typing text commands in a text-only window. As you found out way back in Chapter 1, “Introducing Mac OS X,” Apple has harnessed that power and stability while maintaining the ease of a traditional Macintosh by designing Mac OS X with a Unix subsystem.

By the Way

By creating Mac OS X, Apple has become the largest producer of Unix-based operating systems on the planet!

If you’ve been using Mac OS X for a while now, you might be wondering what all this command-line talk is about—after all, you certainly haven’t needed to type a command on your system, nor have any of your applications required you to access a command prompt. That’s precisely what Apple intended when creating Mac OS X.

Beneath the veneer of Mac OS X’s graphical interface lies the powerful BSD (Berkley Software Distribution) version of the Unix platform. This layer sits behind many of the tasks you perform on your machine and coordinates the actions that make using your Macintosh possible. Although you don’t have to directly interact with this underlying system to complete your day-to-day tasks, you can—if you choose to do so.

Terminal: The Window to the Underworld

The Terminal application (/Applications/Utilities/Terminal) provides your point of access to the BSD subsystem of Mac OS X. Opening Terminal creates a new window with a beckoning command prompt, just waiting for some input, as shown in Figure 38.1.

Terminal opens a window into the Unix layer of Mac OS X.

Figure 38.1. Terminal opens a window into the Unix layer of Mac OS X.

You can customize the appearance of the Terminal application in a number of ways, such as changing the font, resizing the window, and setting a title in the Window Settings, found in the Terminal application menu. One of the most important changes you can make, however, is setting an unlimited scrollback buffer.

As you use the Terminal program and begin to explore Unix, you will be able to “scroll back” to check on the output of commands that you’ve entered using the scrollbars. By default, the Terminal remembers 10,000 lines. This might seem like a lot, but those who use Terminal to do serious operations will quickly see that it isn’t. To change to an unlimited scrollback buffer, follow these steps:

  1. Open the Terminal application Window Settings, found in the application menu.

  2. Click the Buffer option in the pop-up menu at the top of the window.

  3. Select the Unlimited Scrollback radio button, shown in Figure 38.2.

    An unlimited scrollback buffer helps you keep track of the things you’ve done.

    Figure 38.2. An unlimited scrollback buffer helps you keep track of the things you’ve done.

  4. Close the settings by closing the window or click Use Settings as Defaults.

  5. Open a new Terminal window by choosing File, New Shell from the menu (Command-N).

  6. The new window is ready for use with an unlimited scrollback buffer.

Now that you’ve found the command prompt, let’s see what you can do with it. Whenever possible, I’ll try to relate the command-line tools to their graphical Mac OS X alternatives.

Working with Files: Basic Commands

As you work with the Mac OS X Finder, you get to know a sequence of mouse commands for working with the files and folders on your system. These same actions can be carried out from the command line very easily. In some cases, you might find that the command line is actually faster for some tasks than the Finder.

Basic Commands

Let’s start with some of the basic commands for listing, moving, and copying files. Obviously, you can’t do much with your files unless you can see them, so we start with the ls (or list) function.

ls

Typing ls at the command prompt displays all the available files in the current directory (folder). Because the Terminal opens to your home directory and you haven’t learned how to change directories, you probably see a list of the files inside your home that’s similar to the list following list:

[client18:~john] john% ls
Desktop        Library      Music        Public
Documents      Movies       Pictures     Sites

As you know, your Mac OS X files also have permissions on them. To view the listing with permissions showing, use ls -l, and you see a list similar to the following:

[client18:~john] john% ls -l
total 94296

drwx------   9 john  john         306 Jul 25 01:11 Desktop
drwx------  49 john  john        1666 Jul 10 23:55 Documents
drwx------  41 john  john        1394 May 30 18:58 Library
drwx------   6 john  john         204 Mar 30 02:40 Movies
drwx------   3 john  john         102 Mar 30 02:40 Music
drwx------   6 john  john         204 Jul 10 23:55 Pictures
drwxr-xr-x   6 john  john         204 Mar 30 02:40 Public
drwxr-xr-x  16 john  john         544 Jul 10 23:55 Sites

For the most part, the listing is straightforward. The second column is a count of the number of files in a directory. The third and fourth columns are the owner and group, respectively. The fifth column contains the file size, whereas the sixth and seventh columns are the modification date and filename.

The first column, however, is filled with strange letters, such as drwx (repeated several times). The first character of this sequence of letters indicates what kind of file it is. In the listing example, the first characters are all the letter d—for directories. The rest of the nine letters represent read, write, and execute permissions for the user, group, and everyone, respectively.

By the Way

The Mac OS X GUI doesn’t provide a control over the execute permission of a file. This attribute, as its name suggests, controls whether the file can be executed or, in Mac terms, run.

For example, assume that you see a column with drwxr-xr--. Following the pattern we set up, the first letter, d, indicates that this is a directory, and the next three letters, rwx, tell us that the owner has read, write, and execute permissions. The middle three positions, r-x, show read and execute permission for everyone within the file’s group, and the last three, r--, tell us that everyone else has read permission for the file.

Special “abbreviations” are used to represent two special files (you can see these when you use ls -al):

  • .A single period represents the current directory.

  • ..Two periods represent the parent directory of the current directory.

You can use this directory notation with the other commands we look at in this section.

cp

The next command we look at is the cp, or copy, command. Copy, as its name suggests, is used to copy files or directories of files. The syntax for cp is simply

cp <source file path> <destination file path>

For example, to copy the file test.txt to testcopy.txt, you would type

cp test.txt testcopy.txt

This does nothing more than create an exact duplicate of the file test.txt named testcopy.txt in the same directory. To copy a file to another directory, just include the full pathname of the file.

In the case of copying a directory, you must perform a recursive copy, which copies the contents of the folder and the contents of any folders within the source. Do this by supplying the -R option to cp. For example, if I want to copy the directory /Users/jray/testfiles and all of its contents to the folder /Users/robyn/otherfiles, I use the following command:

cp -R /Users/jray/testfiles /Users/robyn/otherfiles

Simple enough, isn’t it? You might recognize this as the equivalent of Option-dragging a file within the Finder, or using the Copy contextual menu command.

Did you Know?

If you play with cp, you might notice that it cannot copy Macintosh-specific files (applications, files with custom icons, and so on). To get around this, you can use the ditto command, which copies one directory to another, complete with all the information that makes a Macintosh file special.

mv

“Moving” right along, the mv command can move a file or directory from one place to another or rename it. It uses the same syntax as cp:

mv <source file path> <destination file path>

This is the same as clicking and dragging an icon from one place to another within the Finder.

For example:

mv myfile.txt myoldfile.txt

This moves the file myfile.txt to myoldfile.txt, effectively renaming the file. Like copy (cp), you could move the file to another directory by using its full pathname.

For example:

mv myfile.txt /Users/robyn/robynsfilenow.txt

Here the file myfile.txt is moved to /Users/robyn and stored with the new name: robynsfilenow.txt.

rm

Now that you can list, move, and copy files, you should probably also learn how to delete them. The rm (remove) command erases a file from your system. It’s extremely important that you pay attention to what you’re doing with rm because no Undo command or Trash exists from which to remove a deleted file.

When using rm, I recommend using the -i option along with it. This forces the system to ask you before removing a file. The basic syntax for rm is

rm -i <filename>

If you want to remove an entire directory, you must also add the -r option to the mix to force rm to go through the directory and remove all the files within it. For example, suppose that you want to remove a directory called myjunkfiles, including all the files inside it. To do that, type the following:

rm -ri myjunkfiles

The rm command steps through each file in the directory and prompts you to confirm that the file should be deleted.

Wildcards

When working with files, you can use a few special symbols in place of characters in the filename. Specifically, the following sequences are available:

  • *Matches any number of characters in a filename

  • ?Matches a single unknown character

  • [0-9]Matches a range of characters

For example, if I want to list only the files in a directory that contain the letters memo anywhere in their names, I would type

ls *memo*

If, on the other hand, I want to be a bit more specific, such as listing all files that start with memo and end with exactly two characters that I don’t know, I could use

ls memo??

Finally, to be even more exact, I could match a range of characters using the format [<start>-<end>]. Assume that I have a group of files, all named memo, followed by two extra characters—some of which are numbers. To list all the memo files followed by the numbers, I could enter

ls memo[0-9][0-9]

Wildcards make it easy to work with groups of files and directories without having to list each name separately.

Editing Files with pico

Creating and editing files is another important part of mastering the Mac OS X command line. This is a definite necessity for performing remote administration of the system, enabling you to make changes to your system’s configuration from almost any terminal connected to the Internet.

A number of text editors are available that you can use from the Mac OS X command line:

  • emacs-- The emacs editor is a powerful editor that can be used for programming and basic editing tasks, and can even be programmed using the Lisp language.

  • vi--vi is the choice editor for die-hard Unix fans. It’s fast and omnipresent—it’s available on just about any Unix machine that exists. (By the way, vi is pronounced V-I, not Vee.)

  • pico—The pico editor is a modern editor for beginners. Like vi, it’s fast, but it’s much simpler to use and is the focus of our attention here.

To use pico, start it from the command line with the name of the file you want to edit or from a new file that you want to create:

pico <filename>

Figure 38.3 shows the pico editor running.

Pico is an easy-to-use command-line editor. (As you can see, it can even be used to make changes to the HTML for a Web page.)

Figure 38.3. Pico is an easy-to-use command-line editor. (As you can see, it can even be used to make changes to the HTML for a Web page.)

To operate pico, use the arrow keys on your keyboard to move the cursor around the screen. Typing enters new text, whereas pressing Delete removes existing characters. You can also use a number of control characters during editing:

  • Control-G—Opens a help screen with basic usage instructions

  • Control-O—Writes (saves) the file

  • Control-R—Reads a new file into the editor

  • Control-Y—Jumps to the previous page

  • Control-V—Jumps to the next page

  • Control-W—Searches the file for a given sequence of characters

  • Control-X—Exits pico

By the Way

You can certainly use pico to read files as well as edit them, but if you just want to quickly scroll through a file, use more <filename> to move through the file a page at a time.

File Permissions

The final file operations that we look at are how to modify permissions. You’ve already discovered how you can tell what the permissions of a file are (using ls)—now let’s see how you can change them.

chown

By default, you own every file that you create. That’s fine, but you might want to change the owner of a file so that you can give it to someone else. The chown command (change ownership) performs this task with ease. Although you can also do this in the Finder, you can use the command-line chown command with filename wildcards to handle multiple files simultaneously.

To use chown, all you need is the name of the file you want to change and the username of the person you want to assign ownership to:

chown <username> <filename>

To change the ownership of a file called test.txt to the user jray, you would type

chown jray test.txt

You might need to prefix the line with the sudo command, which you learn about a bit later in this chapter.

chmod

The chmod command (change mode) modifies file permissions—the read, write, and execute attributes that you saw earlier when learning about the ls function.

The chmod command takes as its parameters a filename and the permissions that you want to assign to it. The permissions are given using a symbolic representation based on the letters u, g, o, and r, w, and x. The u, g, and o are user, group, and other, respectively. The letters r, w, and x represent the read, write, and execute permissions.

Combining these letters with + and -, you can add or subtract any permission from any type of access level:

chmod <permission> <filename>

For example, to remove write permission for the owner of a file named nowrite.txt, you would enter

chmod u-w nowrite.txt

Likewise, to add read permission for other users (the rest of the world), use this syntax:

chmod o+r nowrite.txt

As you can see, the Unix commands give you a much greater level of control than using the equivalent Get Info feature in the Finder.

Managing files in Unix is the same as managing files in Mac OS X’s Finder, but instead of mouse actions, typed commands are used to tell your computer what to do. Before moving on, try editing a few files and using the basic mv and cp commands to move them around. When you feel comfortable with the process, move on to the next section, “Process Management.” There you learn how the Unix side of your computer views running applications.

Process Management

As you use your Mac OS X computer, you create dozens of processes and support processes that you probably never realized existed. In Chapter 36, “Maintaining Your System,” you learn about some of the GUI tools that enable you to manage these processes in a point-and-click manner. In this section, however, you see the commands that can provide the raw data of what is happening on your system.

Viewing Processes

To view the active processes on your computer, you can use one of two commands. The first command, ps, creates a process listing of whatever’s running in the foreground (or, modified, everything that’s running). The second command, top, shows a list of the applications using up the most resources on your computer.

ps

To use the ps command, all you need to do is type ps at the command prompt. This generates a list of the processes that you control on the computer. For example:

[localhost:~] jray% ps
  PID  TT  STAT      TIME COMMAND
  707 std  Ss     0:00.25 -tcsh (tcsh)

Here, the process is my command-line shell (tcsh), which isn’t very interesting. To list everything that’s running on a Mac OS X computer, add the argument -ax to the command, like this:

[localhost:~] jray% ps -ax
  PID  TT  STAT      TIME COMMAND
    1  ??  SLs    0:00.05 /sbin/init
    2  ??  SL     0:02.75 /sbin/mach_init
   41  ??  Ss     0:01.94 kextd
   68  ??  Ss     0:22.85 /System/Library/Frameworks/ApplicationServices.framew
   70  ??  Ss    40:38.78 /System/Library/CoreServices/WindowServer
   72  ??  Ss     0:07.96 update
   75  ??  Ss     0:00.01 dynamic_pager -H 40000000 -L 160000000 -S 80000000 -F
  103  ??  Ss     0:00.61 /sbin/autodiskmount -va
  127  ??  Ss     0:03.28 configd
  185  ??  Ss     0:00.38 syslogd
  218  ??  Ss     0:00.02 /usr/libexec/CrashReporter
  240  ??  Ss     0:01.37 netinfod -s local
  247  ??  Ss     0:04.32 lookupd
  257  ??  S<s    0:05.72 ntpd -f /var/run/ntp.drift -p /var/run/ntpd.pid
  270  ??  Ss     0:01.38 /System/Library/CoreServices/coreservicesd
  277  ??  Ss     0:00.00 inetd
  288  ??  S      0:00.00 nfsiod -n 4
  289  ??  S      0:00.00 nfsiod -n 4
  290  ??  S      0:00.00 nfsiod -n 4
  298  ??  S      0:00.27 DirectoryService
...and so on.

For each process, you’ll notice a PID number in the listing. This is the process ID, and it uniquely identifies the program running on your computer. There’s also a TIME field, which contains how much cumulative processor time the software has used on your machine.

By the Way

You might also notice the TT and STAT columns in the listing. These display the controlling terminal of a given process and its status. Unfortunately, these topics are beyond the scope of this book and are best addressed by an advanced book, such as Mac OS X Unleashed from Sams Publishing.

Keep track of the PID values—you need them in a few minutes.

top

If you want a more interactive means of monitoring what’s running on your system, try using the top command. The utility, shown in Figure 38.4, shows a listing of the most active and processor-intensive applications running on your machine. It can provide a good means of uncovering unusual activity on your computer and answering why your system is sluggish at a given point in time.

Use top to get an interactive view of the processes on your computer.

Figure 38.4. Use top to get an interactive view of the processes on your computer.

When running top, the most active processes are shown at the top of the listing. Usually the Mac OS X components rank very highly in the list (such as the Finder). Watching the CPU (percentage of CPU being used), TIME (total amount of CPU time the application has consumed), and RSIZE (amount of memory the application is using) columns gives you the most useful information about what your computer is doing. If you see an unusual piece of software that you didn’t install (perhaps your coworker’s copy of Seti@Home) in the listing, you can write down its PID and then force it to quit.

By the Way

To quit top, you’ll need to type the key command Control-C. That returns Terminal to a command line where you can continue entering commands.

From the command line, you can use Unix to force any application to quit. Although powerful, this can also pose a danger to the system: Users can easily force important parts of the operating system to quit!

Killing Processes

As violent as it sounds, the action of forcing a running Unix process to quit is called killing it. Appropriately enough, this action uses a command called kill.

The kill command’s actions don’t need to be as drastic as forcing an application to quit. In reality, the kill command simply sends a signal to a process that can be interpreted in a number of ways. Some signals simply cause the software to reload its configuration, whereas others do indeed force it to exit.

The two most common signals you’ll encounter are HUP (to force a reload) and KILL (to truly kill a process). Along with a signal, the kill command also requires a process ID (the numbers supplied in the PID column of the ps or top commands).

Armed with this information, you can kill a process using this syntax:

kill -<signal> <process id>

For example, to force a process with the ID of 1992 to quit, I would type

kill -KILL 1992

Watch Out!

Killing a process with the KILL signal does not save any data that the application is processing. Use this as a last resort for gaining control of a piece of software.

Also be aware that indiscriminately killing processes on your system could make Mac OS X unstable or even crash the operating system.

The kill command can be used remotely to control what’s running on your machine and shut down processes that shouldn’t be active. In the next section, you learn how to gain complete control over the command line.

Server Administration

Although everything that you’ve learned so far in this chapter is valid, it isn’t necessarily completely functional. For example, you can’t change the owner of a file you don’t own. In most cases, that’s fine, but for complete control over the machine, you should be able to do whatever you want.

The command that makes this possible is sudo. When sudo is placed in front of any other command, it enables you to execute the command as the root user. Root has complete control over everything on your system, so be careful when using the command; you could end up removing all the files from your computer.

For example, to kill a process that you didn’t create, you could use the following:

sudo kill <signal> <process ID>

sudo starts, asks you for your user password, and then executes the given command with root’s permissions.

The commands themselves stay the same but gain a whole new level of capability. Using this technique, you can easily remove, copy, or rename files belonging to other users.

By the Way

Don’t let the power go to your head! Other people who use or store files on your system should have a right to privacy, unless you explicitly tell them otherwise. Reading files you don’t own is unethical and, depending on the circumstances, may be illegal.

Getting Help with Manpages

Almost every function and utility that exists on your system includes a built-in help file called a manpage (manual page). The man command returns all the information you need to understand the arguments a given utility takes, how it works, and the results you should expect. Consider the more command, for example. Although this has been mentioned only briefly, you can quickly learn more information about it by typing

man more

For example:

[localhost:/etc] john% man more
man: Formatting manual page...

MORE(1)                                                   MORE(1)

NAME

       more, page--file perusal filter for crt viewing

SYNOPSIS
       more  [  -cdflsu  ] [ -n ] [ +linenumber ] [ +/pattern ] [
       name ...  ]

       page more options

DESCRIPTION
       More is a filter which allows examination of a  continuous
       text  one screenful at a time on a soft-copy terminal.  It
       normally pauses after each screenful, printing the current
       file name at the bottom of the screen or --More-- if input
       is from a pipe.  If the user then types a carriage return,
       one  more  line  is displayed.   If the user hits a space,
       another screenful is displayed.  Other  possibilities  are
       enumerated later.
...and so on...

This is only a tiny portion of the total manpage for the more command. There are more than five pages of information for this function alone!

Did you Know?

If you don’t know exactly what command you’re looking for, use apropos <keyword> to search through the manpage information for a given word or phrase.

Other Useful Commands

Thousands of other commands and utilities on Mac OS X could potentially be covered in a Unix chapter. Instead of trying to do the impossible and document them all in 15 to 20 pages, we finish the chapter by listing a few interesting functions that you can explore (remember to use man!) if you choose to do so.

  • curl--Retrieves information from a given URL. Useful for downloading files from the command line.

  • ncftp--A simple, yet surprisingly user-friendly FTP client.

  • cat--Displays the contents of a file.

  • file--Shows the type of a file (what it contains).

  • locate--Quickly finds a file based on the text in its name.

  • find--Locates files based on their size, modification dates, and so on. This is the Unix equivalent of the Finder’s Find feature.

  • grep--Searches through a text file for a given string.

  • shutdown--Shuts down a Mac OS X computer.

  • reboot--Reboots a Mac OS X computer.

  • date--Displays the current date and time.

  • uptime--Shows the amount of time your computer has been online and what the current system load is.

  • passwd--Changes your Mac OS X password.

  • df--Shows the amount of free and used space on all available partitions.

  • du--Displays disk usage information on a directory-by-directory basis.

  • tar--Archives and dearchives files in the Unix tar format.

  • gzip/gunzip--Compresses and decompresses files.

Again, I want to stress that this should serve as a starting place for exploring the Unix subsystem. You will find commands that aren’t listed in this chapter. However, with the documentation provided here, you’re prepared for how they work and understand how to get more information about them.

By the Way

If this chapter has whetted your appetite for using the command line, I highly recommend Mac OS X Unleashed, which covers many of the topics discussed in this book but with greater technical detail and much more attention to the Unix side of Mac OS X.

Summary

In this chapter, you learned some of the basics of the Unix command line. You should now be capable of performing many of the standard Finder functions from a command prompt. Although many gaps exist in what was covered, Unix is a broad topic and one that takes years to master. Hopefully you’re on your way to becoming a future Unix guru!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset