The sample Utility


The sample Utility

The following description of the sample utility shows the format that is used to describe the utilities in this part of the book. These descriptions are similar to the man page descriptions (pages 28 and 788); however, most users find the descriptions in this book easier to read and understand. These descriptions emphasize the most useful features of the utilities and often leave out the more obscure features. For information about the less commonly used features, refer to the man and info pages or call the utility with the help option, which works with some utilities.

sample: Very brief description of what the utility does

sample [options] arguments

Following the syntax line is a description of the utility. The syntax line shows how to run the utility from the command line. Options and arguments enclosed in brackets ([]) are not required. Words that appear in this italic typeface must be typed as is. Words that you must substitute when you type appear in this bold italic typeface. Words listed as arguments to a command identify single arguments (for example, source-file) or groups of similar arguments (for example, directory-list).

Arguments

This section describes the arguments that you can use when you run the utility. The argument itself, as shown in the preceding syntax line, is printed in this bold italic typeface.

Options

This section lists some of the options you can use with the command. Unless otherwise specified, you must precede options with one or two hyphens. Most commands accept a single hyphen before multiple options (page 115). Options in this section are ordered alphabetically by short (single-hyphen) options. If an option has only a long version (two hyphens), it is ordered by its long option. Following are some sample options:

make-dirs

d

This option has a long and a short version. You can use either option; they are equivalent.

delimiter=dchar

 
 

d

dchar

 
  

This option includes an argument. The argument is set in a bold italic typeface in both the heading and the description. You substitute another word (filename, string of characters, or other value) for any arguments you see in this typeface. Type characters that are in bold type (such as the delimiter and d) as is, letter for letter.

 

t

(table of contents) This example shows a simple option preceded by a single hyphen and not followed with any arguments. It has no long version. The table of contents appearing in parentheses at the beginning of the description is a cue, suggestive of what the option letter stands for.


Discussion

This optional section contains a discussion about how to use the utility and any quirks it may have.

Notes

This section contains miscellaneous notessome important and others merely interesting.

Examples

This section contains examples of how to use the utility. This section is tutorial and is more casual than the preceding sections of the description.

at: Executes commands at a specified time

at [options] time [date | +increment]

atq

atrm job-list

batch [options] [time]

The at and batch utilities execute commands at a specified time. They accept commands from standard input or, with the f option, from a file. Commands are executed in the same environment as the at or batch command. Unless redirected, standard output and standard error from commands are emailed to the user who ran at or batch. A job is the group of commands that is executed by one call to at. The batch utility differs from at in that it schedules jobs so that they run when the CPU load on the system is low.

The atq utility displays a list of at jobs you have queued; atrm cancels pending at jobs.

Arguments

The time is the time of day when at runs the job. You can specify the time as a one-, two-, or four-digit number. One- and two-digit numbers specify an hour, and four-digit numbers specify an hour and minute. You can also give the time in the form hh:mm. The at utility assumes a 24-hour clock unless you place am or pm immediately after the number, in which case it uses a 12-hour clock. You can also specify time as now, midnight, noon, or teatime (4:00 PM).

The date is the day of the week or day of the month on which at is to execute the job. When you do not specify a day, at executes the job today if the hour you specify in time is greater than the current hour. If the hour is less than the current hour, at executes the job tomorrow.

You specify a day of the week by spelling it out or abbreviating it to three letters. You can also use the words today and tomorrow. Use the name of a month followed by the number of the day in the month to specify a date. You can follow the month and day number with a year.

The increment is a number followed by one of the following (plural and singular are both allowed): minutes, hours, days, or weeks. The at utility adds the increment to time. You cannot specify an increment for a date.

When using atrm, job-list is a list of one or more at job numbers. You use atq to list job numbers.

Options

f

file

 

Specifies that commands come from file instead of standard input. This option is useful for long lists of commands or commands that are executed repeatedly.

m

(mail) Sends you email after a job is run, even when nothing is sent to standard output or standard error. When a job generates output, at always emails it to you, regardless of this option.


Notes

The shell saves the environment variables and the working directory at the time you submit an at job so that they are available when at executes commands.

Jobs you submit using at are run by the at daemon (atrun). This daemon stores jobs in /var/at/jobs and output in /var/at/spool.

Under OS X 10.4 and later, the atrun daemon is disabled by default for power conservation. Working as a privileged user, you can enable and disable atrun with the following commands:

# launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist # launchctl unload -w /System/Library/LaunchDaemons/com.apple.atrun.plist


See launchctl (page 765) for more information.

Examples

You can use any of the following techniques to paginate and print long_file tomorrow at 2:00 AM. The first example executes the command directly from the command line; the last two examples use the pr_tonight file, which contains the necessary command, and execute it using at.

$ at 2am pr long_file  |  lpr CONTROL-D job 8 at Wed  Jun 22 02:00:00 2005 $ cat pr_tonight #!/bin/bash pr long_file  |  lpr $ at -f pr_tonight 2am job 9 at Wed Jun 22 02:00:00 2005 $ at 2am < pr_tonight job 10 at Wed Jun 22 02:00:00 2005


If you execute commands directly from the command line, you must signal the end of the commands by pressing CONTROL-D at the beginning of a line. After you press CONTROL-D, at displays a line that begins with job followed by the job number and the time when at will execute the job.

If you run atq after the preceding commands, it displays a list of jobs in its queue:

$ atq 8       Wed Jun 22 02:00:00 2005 9       Wed Jun 22 02:00:00 2005 10      Wed Jun 22 02:00:00 2005


The following command removes job number 9 from the queue:

$ atrm 9 $ atq 8       Wed Jun 22 02:00:00 2005 10      Wed Jun 22 02:00:00 2005


The next example executes cmdfile at 3:30 PM (1530 hours) one week from today:

$ at -f cmdfile 1530 +1 week job 12 at Wed Jun 29 15:30:00 2005


Next at executes a job at 7:00 PM on Thursday. This job uses find to create an intermediate file, redirects the output sent to standard error, and prints the file.

$ at 7pm Thursday find / -name "*.c" >report.out 2>report.err lpr report.out CONTROL-D job 13 at Thu Jun 23 19:00:00 2005


bzip2: Compresses or decompresses files

bzip2 [options] [file-list]

bunzip2 [options] [file-list]

bzcat [options] [file-list]

bzip2recover [file]

The bzip2 utility compresses files; bunzip2 restores files compressed with bzip2; bzcat displays files compressed with bzip2.

Arguments

The file-list specifies the pathnames of one or more files (no directories) that are to be compressed or decompressed. If file-list is empty or if the special option is present, bzip2 reads from standard input. The stdout option causes bzip2 to write to standard output.

Options

Accepts the common options described on page 663.

stdout

c

Writes the results of compression or decompression to standard output.

decompress

d

Decompresses a file compressed with bzip2. The combination of this option with bzip2 is equivalent to the bunzip2 command.

fast or best

n

Sets the block size when compressing a file. The n is a digit from 1 to 9, where 1 (fast) generates a block size of 100 kilobytes and 9 (best) generates a block size of 900 kilobytes. The default level is 9. The options fast and best are provided for compatibility with gzip and do not necessarily yield the fastest or best compression.

force

f

Forces compression even if a file already exists, has multiple links, or comes directly from a terminal. The option has a similar effect with bunzip2.

keep

k

Does not delete input files while compressing or decompressing them.

quiet

q

Suppresses warning messages; does display critical messages.

test

t

Verifies the integrity of a compressed file. Displays nothing if the file is OK.

verbose

v

For each file being compressed displays the name of the file, the compression ratio, the percentage of space saved, and the sizes of the decompressed and compressed files.


Discussion

The bzip2 and bunzip2 utilities work similarly to gzip and gunzip; see the discussion of gzip (page 757) for more information. Normally bzip2 does not overwrite a file; you must use force to overwrite a file during compression or decompression.

Notes

The bzip2 home page is sources.redhat.com/bzip2.

The bzip2 utility does a better job of compressing files than gzip does.

Use the bzip modifier with tar (page 864) to compress archive files with bzip2.

bzcat file-list

Works like cat except that it uses bunzip2 to decompress file-list as it copies files to standard output.

bzip2recover

Attempts to recover a damaged file that was compressed with bzip2.

Examples

In the following example, bzip2 compresses a file and gives the resulting file the same name with a .bz2 filename extension. The v option displays statistics about the compression.

$ ls -l total 728 -rw-r--r--  1 sam sam 737414 Feb 20 19:05 bigfile $ bzip2 -v bigfile   bigfile: 3.926:1, 2.037 bits/byte, 74.53% saved, 737414 in, 187806 out $ ls -l total 188 -rw-r--r--  1 sam sam 187806 Feb 20 19:05 bigfile.bz2


Next touch creates a file with the same name as the original file; bunzip2 refuses to overwrite the file in the process of decompressing bigfile.bz2. The force option enables bunzip2 to overwrite the file.

$ touch bigfile $ bunzip2 bigfile.bz2 bunzip2: Output file bigfile already exists. $ bunzip2 --force bigfile.bz2 $ ls -l total 728 -rw-r--r--  1 sam sam 737414 Feb 20 19:05 bigfile


cal: Displays a calendar

cal [options] [[month] year]

The cal utility displays a calendar for a month or a year.

Arguments

The arguments specify the month and year for which cal displays a calendar. The month is a decimal integer from 1 to 12 and the year is a decimal integer. Without any arguments, cal displays a calendar for the current month. When you specify a single argument, it is assumed to be the year.

Options

j

(Julian) Displays a Julian calendara calendar that numbers the days consecutively from January 1 (1) through December 31 (365 or 366).

y

(year) Displays a calendar for the current year.


Notes

Do not abbreviate the year. The year 05 is not the same as 2005.

The cal utility switches to the Gregorian calendar in September 1752.

Examples

The following command displays a calendar for August 2007:

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


Next is a Julian calendar for 1949:

$ cal -j 1949                             1949            January                       February   S   M   Tu   W   Th   F   S    S   M   Tu   W   Th   F   S                             1            32   33  34  35  36   2   3    4   5    6   7   8   37  38   39  40   41  42  43   9  10   11  12   13  14  15   44  45   46  47   48  49  50  16  17   18  19   20  21  22   51  52   53  54   55  56  57  23  24   25  26   27  28  29   58  59  30  31 ...


cat: Joins and displays files

cat [options] [file-list]

The cat utility copies files to standard output. You can use cat to display the contents of one or more text files on the screen.

Arguments

The file-list specifies the pathnames of one or more files that cat processes. If you do not specify an argument or if you specify a hyphen (-) in place of a filename, cat reads from standard input.

Options

b

(blank) Numbers all lines that are not blank as they are written to standard output.

e

(end) Marks the ends of lines with dollar signs. Implies v.

n

(number) Numbers all lines as they are written to standard output.

s

(squeeze blanks) Removes extra blank lines so there are never two or more blank lines in a row.

t

(tab) Displays TABs as ^I. Implies v.

v

(verbose) Displays CONTROL characters with the caret notation (^M) and displays characters that have the high bit set (META characters) with the M- notation. This option does not convert TABs and LINEFEEDs. Use t if you want to display TABs as ^I. LINEFEEDs cannot be displayed as anything but themselves; otherwise, the line would be too long.


Notes

See page 121 for a discussion of cat, standard input, and standard output.

Use the od utility (page 799) to display the contents of a file that does not contain text (for example, an executable program file).

The name cat is derived from one of the functions of this utility, catenate, which means to join together sequentially, or end to end.

Caution: Set noclobber to avoid overwriting a file

Despite cat's warning message, the shell destroys the input file (letter) before invoking cat in the following example:

$ cat memo letter > letter cat: letter: input file is output file


You can prevent the file from being overwritten in this situation by setting the noclobber variable (pages 125 and 363).


Examples

The following command displays the contents of the memo text file on the terminal:

$ cat memo ...


The next example catenates three text files and redirects the output to the all file:

$ cat page1 letter memo > all


You can use cat to create short text files without using an editor. Enter the following command line, type (or paste) the text you want in the file, and press CONTROL-D on a line by itself:

$ cat > new_file ... (text)  ... CONTROL-D


In this case cat takes input from standard input (the keyboard) and the shell redirects standard output (a copy of the input) to the file you specify. The CONTROL-D signals EOF (end of file) and causes cat to return control to the shell (page 122).

In the next example, a pipe sends the output from who to standard input of cat. The shell redirects cat's output to the file named output. After the commands have finished executing, output contains the contents of the header file, the output of who, and footer. The hyphen on the command line causes cat to read standard input after reading header and before reading footer.

$ who | cat header - footer > output


cd: Changes to another working directory

cd [options] [directory]

The cd builtin makes directory the working directory.

Arguments

The directory is the pathname of the directory that is to be the new working directory. Without an argument, cd makes your home directory the working directory. Using a hyphen in place of directory changes to the previous working directory.

Notes

The cd command is a bash and tcsh builtin.

See page 82 for a discussion of cd.

Without an argument, cd makes your home directory the working directory; it uses the value of the HOME (bash, page 284) or home (tcsh, page 359) variable for this purpose.

With an argument of a hyphen, cd makes the previous working directory the working directory. It uses the value of the OLDPWD (bash) or owd (tcsh) variable for this purpose.

The CDPATH (bash, page 290) or cdpath (tcsh, page 359) variable contains a colon-separated list of directories that cd searches. Within the list a null directory name (::) or a period (:.:) represents the working directory. If CDPATH or cdpath is not set, cd searches only the working directory for directory. If this variable is set and directory is not an absolute pathname (does not begin with a slash), cd searches the directories in the list; if the search fails, cd searches the working directory. See page 290 for a discussion of CDPATH.

Examples

The following cd command makes Alex's home directory his working directory. The pwd builtin verifies the change:

$ pwd /Users/alex/literature $ cd $ pwd /Users/alex


The next command makes the /Users/alex/literature directory the working directory:

$ cd /Users/alex/literature $ pwd /Users/alex/literature


Next the cd utility makes a subdirectory of the working directory the new working directory:

$ cd memos $ pwd /Users/alex/literature/memos


Finally cd uses the .. reference to the parent of the working directory to make the parent the new working directory:

$ cd .. $ pwd /Users/alex/literature


chgrp: Changes the group associated with a file

chgrp [options] group file-list

The chgrp utility changes the group associated with one or more files.

Arguments

The group is the name or numeric group ID of the new group. The file-list specifies the pathnames of one or more files whose group association is to be changed.

Options

f

(force) Prevents the display of warning messages about files whose permissions prevent you from changing their group IDs.

H

(dereference) Follows the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not follow the files that symbolic links found while descending a directory hierarchy point to. Works only with R.

L

(dereference) Follows the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to. Works only with R.

P

(no dereference) Does not follow symbolic links while descending a directory hierarchy (default). Works only with R.

R

(recursive) Recursively descends a directory specified in file-list and changes the group ID on all files in the directory hierarchy.

v

(verbose) Displays for each file a message saying whether its group was retained or changed.


Notes

Only the owner of a file or root can change the group association of a file. Also, unless you are root, you must belong to the specified group to change the group ID of a file to that group.

See page 682 for information on how chown can change the group associated with, as well as the owner of, a file.

Examples

The following command changes the group that the manuals file is associated with; the new group is pubs.

$ chgrp pubs manuals


chmod: Changes the access mode (permissions) of a file

chmod [options] who operator permission file-list (symbolic)

chmod [options] mode file-list (absolute)

The chmod utility changes the ways in which a file can be accessed by the owner of the file, the group the file is associated with, and/or all other users. Only the owner of a file or Superuser can change the access mode, or permissions, of a file. You can specify the new access mode absolutely or symbolically.

Arguments

The who, operator, and permission arguments specify symbolically which modes will be changed in what ways. The mode argument specifies the same information absolutely. The file-list specifies the pathnames of one or more files whose permissions chmod is to change.

Symbolic

You can specify multiple sets of symbolic modes (who operator permission) by separating each set from the next with a comma.

The chmod utility changes the access permission for the class of users specified by who. The class of users is designated by one or more of the letters specified in the who column of Table VI-3

Table VI-3. Symbolic mode user class specification

who

User class

Meaning

u

User

Owner of the file

g

Group

Group to which the owner belongs

o

Other

All other users

a

All

Can be used in place of ugo


Table VI-4 lists the symbolic mode operators.

Table VI-4. Symbolic mode operators

operator

Meaning

+

Adds permission for the specified user class

-

Removes permission for the specified user class

=

Sets permission for the specified user classresets all other permissions for that user class


The access permission is specified by one or more of the letters listed in Table VI-5.

Table VI-5. Symbolic mode permissions

permission

Meaning

r

Sets read permission

w

Sets write permission

x

Sets execute permission

s

Sets user ID or group ID (depending on the who argument) to that of the owner of the file while the file is being executed (For more information see page 90.)

t

Sets the sticky bit (Only Superuser can set the sticky bit, and it can be used only with u; see page 955.)

X

Makes the file executable only if it is a directory or if another user class has execute permission

u

Sets the specified permissions to those of the owner

g

Sets the specified permissions to those of the group

o

Sets the specified permissions to those of others


Absolute

You can use an octal number to specify the access mode. Construct the number by ORing the appropriate values from Table VI-6. To OR two octal numbers from this table, just add them. (Refer to Table VI-7 for examples.)

Table VI-6. Absolute mode specifications

mode

Meaning

4000

Sets user ID when the program is executed (page 90)

2000

Sets group ID when the program is executed (page 90)

1000

Sticky bit (page 955)

0400

Owner can read the file

0200

Owner can write to the file

0100

Owner can execute the file

0040

Group can read the file

0020

Group can write to the file

0010

Group can execute the file

0004

Others can read the file

0002

Others can write to the file

0001

Others can execute the file


Table VI-7. Examples of absolute mode specifications

Mode

Meaning

0777

Owner, group, and others can read, write, and execute file

0755

Owner can read, write, and execute file; group and others can read and execute file

0711

Owner can read, write, and execute file; group and others can execute file

0644

Owner can read and write file; group and others can read file

0640

Owner can read and write file; group can read file; and others cannot access file


Table VI-7 lists some typical modes.

ACLs

Although ACLs (Access Control Lists, page 97) are most often modified using the OS X GUI, you can also use chmod to work with them. A chmod command to create, modify, or delete an access rule adheres to the following format:

chmod option user|group allow|deny action


where option is +a (add rule), a (remove rule), or =a (change rule); user is a username or UID number; group is a group name or group ID number; and action is one or more of read, write, append, and execute. For example, the following command adds a rule that gives Jenny read and write access to the memo file:

$ chmod +a "jenny allow read,write" memo


If you replace allow with deny in the preceding command, the rule prohibits Jenny from reading from or writing to memo.

The kernel processes multiple rules in an ACL in the order displayed by ls le. The order entries are stored in is not necessarily the order they were added in. In general, deny entries come before allow entries. You can override the default order by adding a rule with +a# n. This rule will be added as rule number n.

There are two ways to remove access rules. First, you can specify a rule using the same format that you used when you added it. The following command removes the rule that was added in the previous example:

$ chmod a "jenny allow read,write" memo


Second, after using ls le to display a file's ACL, you can use chmod a# n to remove rule number n.

Options

f

(force) Prevents the display of warning messages about files whose permissions prevent chmod from changing the permissions of the file.

H

(dereference) Follows the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not follow the files that symbolic links found while descending a directory hierarchy point to. Works only with R.

L

(dereference) Follows the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to. Works only with R.

P

(no dereference) Does not follow symbolic links while descending a directory hierarchy (default). Works only with R.

R

(recursive) Recursively descends a directory specified in file-list and changes the permissions on all files in the directory hierarchy.

v

(verbose) Displays the name of each file as its permissions are changed.


Notes

When you use symbolic arguments, you can omit the permission from the command line only when the operator is =. This omission takes away all permissions. See the second example in the next section.

See page 87 for a discussion of access permissions in general and page 90 for information about how directory permissions work.

Examples

The following examples show how to use chmod to change the permissions of the file named temp. The initial access mode of temp is shown by ls (see page 87 for information about the ls display):

$ ls -l temp -rw-rw-r-- 1 alex   pubs   57 Jul 12 16:47 temp


When you do not follow an equal sign with a permission, chmod removes all permissions for the specified user class. The following command removes all access permissions for the group and all other users so that only the owner has access to the file:

$ chmod go= temp $ ls -l temp -rw-------   1 alex   pubs   57 Jul 12 16:47 temp


The next command changes the access modes for all users (owner, group, and others) to read and write. Now anyone can read from or write to the file.

$ chmod a=rw temp $ ls -l temp -rw-rw-rw-   1 alex  pubs   57 Jul 12 16:47 temp


Using an absolute argument, a=rw becomes 666. The next command performs the same function as the previous one:

$ chmod 666 temp


The next command removes write access permission for other users. As a result Alex and members of the pubs group can still read from and write to the file, but other users can only read from the file:

$ chmod o-w temp $ ls -l temp -rw-rw-r--   1 alex  pubs  57 Jul 12 16:47 temp


The following command yields the same result, using an absolute argument:

$ chmod 664 temp


The next command adds execute access permission for all users:

$ chmod a+x temp $ ls -l temp -rwxrwxr-x   1 alex  pubs  57 Jul 12 16:47 temp


If temp is a shell script or other executable file, all users can now execute it. (You need read and execute access to execute a shell script but only execute access to execute a binary file.) The following absolute command yields the same result:

$ chmod 775 temp


The next command uses symbolic arguments to achieve the same result as the preceding one. It sets permissions to read, write, and execute for the owner and group, and to read and write for other users. A comma separates the sets of symbolic modes.

$ chmod ug=rwx,o=rw temp


ACLs

The next series of examples manipulate ACLs (page 97), using ls le to display the results. First Alex gives Jenny permission to read from and write to the memo file. The plus sign (+) to the right of the permissions in the output of ls indicates that the file has an ACL.

$ ls -le memo -rw-r--r-- + 1 alex  alex  19 Jun 24 15:30 memo $ chmod +a "jenny allow read,write" memo $ ls -le memo -rw-r--r-- + 1 alex  alex  19 Jun 24 15:30 memo  0: user:jenny allow read,write


Alex then decides to remove the write permissions he just gave Jenny. If the access specification given to a a option is only part of an existing rule, the remainder of the rule remains.

$ chmod -a "jenny allow write" memo $ ls -le memo -rw-r--r-- + 1 alex  alex  19 Jun 24 15:30 memo  0: user:jenny allow read


The next example removes the ACL entry entirely, specifying it by number. Although there are no rules, the file is marked with a plus sign to indicate that it still has an ACL.

$ chmod -a# 0 memo $ ls -le memo -rw-r--r-- + 1 alex  alex  19 Jun 24 15:30 memo


When you specify an ACL operation that it cannot complete, chmod returns an error. The following multiline command uses a while loop (page 540) to remove all ACL rules for memo. The : (null) builtin provides the loop body.

$ while chmod -a# 0 memo > do : > done chmod: No ACL present: Invalid argument


The next example shows that chmod inserts rules in an ACL in a default order:

$ chmod +a "jenny allow read" memo $ chmod +a "jenny deny read" memo $ ls -le memo -rw-r--r-- + 1 alex  alex  19 Jul 19 21:59 memo  0: user:jenny deny read  1: user:jenny allow read


Even though the allow rule was added first, the deny rule appears before it. Next Alex gives read permission to Sam, Max, and Zach:

$ chmod +a "sam allow read" memo $ chmod +a "max allow read" memo $ chmod +a "zach allow read" memo $ ls -le memo -rw-r--r-- + 1 alex  alex  19 Jul 19 21:59 memo  0: user:jenny deny read  1: user:jenny allow read  2: user:sam allow read  3: user:max allow read  4: user:zach allow read


After giving these permissions, Alex realizes that he meant to give Sam write access, too. He could create a new rule by using sam allow write, but he would like to replace Sam's rule with the correct one. The following command replaces (=a) rule number 2 (# 2):

$ chmod =a# 2 "sam allow read,write" $ ls -le -rw-r--r-- + 1 alex  alex  19 Jul 19 21:59 memo  0: user:jenny deny read  1: user:jenny allow read  2: user:sam allow read,write  3: user:max allow read  4: user:zach allow read


chown: Changes the owner of a file and/or the group the file is associated with

chown [options] owner file-list

chown [options] owner:group file-list

chown [options] owner: file-list

chown [options] :group file-list

The chown utility changes the owner of a file and/or the group the file is associated with. Only root can change the owner of a file. Only root or the owner of a file who belongs to the new group can change the group a file is associated with.

Arguments

The owner is the username or numeric user ID of the new owner. The file-list specifies the pathnames of one or more files whose ownership and/or group association chown is to change. The group is the group name or numeric group ID of the new group that the file is associated with. Table VI-8 shows the ways you can specify the new owner and/or group.

Table VI-8. Specifying the new owner and/or group

Argument

Meaning

owner

The new owner of file-list; the group is not changed

owner:group

The new owner and new group association of file-list

owner:

The new owner of file-list; the group association is changed to that of the new owner's login group

:group

The new group associated with file-list; the owner is not changed


Options

f

(force) Prevents chown from displaying error messages when it is unable to change the ownership/group of a file.

H

(dereference) Follows the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not follow the files that symbolic links found while descending a directory hierarchy point to. Works only with R.

L

(dereference) Follows the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to. Works only with R.

P

(no dereference) Does not follow symbolic links while descending a directory hierarchy (default). Works only with R.

R

(recursive) When you include directories in the file-list, this option descends the directory hierarchy, setting the specified ownership/group for all files encountered.

v

(verbose) Displays the name of each file as its ownership is changed.


Examples

The following command changes the owner of the chapter1 file in the manuals directory. The new owner is Jenny.

# chown jenny manuals/chapter1


The following command makes Alex the owner of, and Alex's login group the group associated with, all files in the /Users/alex/literature directory and in all its subdirectories:

# chown -R alex: /Users/alex/literature


The next command changes the ownership of the files in literature to alex and the group associated with these files to pubs:

# chown alex:pubs /Users/alex/literature/*


The final example changes the group association of the files in manuals to pubs without altering their ownership. The owner of the files, who is executing this command, must belong to the pubs group.

$ chown :pubs manuals/*


cmp: Compares two files

cmp [options] file1 [file2 [skip1 [skip2]]]

The cmp utility displays the differences between two files on a byte-by-byte basis. If the files are the same, cmp is silent. If the files differ, cmp displays the byte and line number of the first difference.

Arguments

The file1 and file2 are pathnames of the files that cmp compares. If file2 is omitted, cmp uses standard input instead. Using a hyphen () in place of file1 or file2 causes cmp to read standard input instead of that file.

The skip1 and skip2 are decimal numbers indicating the number of bytes to skip in each file before beginning the comparison.

Options

Accepts the common options described on page 663.

printbytes

b

Displays more information, including filenames, byte and line number, and octal and ASCII values of the first differing byte.

ignoreinitial=n

i

n

  

Skips the first n bytes in both files before beginning the comparison.

verbose

l

(lowercase "l") Instead of stopping at the first byte that differs, continues comparing the two files and displays both the location and the value of each byte that differs. Locations are displayed as decimal byte count offsets from the beginning of the files; byte values are displayed in octal. The comparison terminates when an EOF is encountered on either file.

silent or quiet

s

Suppresses output from cmp; only sets the exit status (see "Notes").


Notes

Unlike diff (page 707), cmp works with binary as well as ASCII files. Byte and line numbering start at 1.

The cmp utility does not display a message if the files are identical; it just sets the exit status. This utility returns an exit status of 0 if the files are the same and 1 if they differ. An exit status greater than 1 means that an error occurred.

When you use skip1 (and skip2), the offset values cmp displays are based on the byte where the comparison began. You can use the standard multiplicative suffixes after skip1 and skip2; see Table VI-1 on page 662.

The cmp utility compares data forks (page 93) of a file only. If you want to compare resource forks, you can manually compare the ..namedfork/rsrc files (page 94) for the target files.

Examples

The examples use the files a and b shown below. These files have two differences. The first difference is that the word lazy in file a is replaced by lasy in file b. The second difference is more subtle: A TAB character appears just before the NEWLINE character in file b.

$ cat a The quick brown fox jumped over the lazy dog. $ cat b The quick brown fox jumped over the lasy dog.TAB


The first example uses cmp without any options to compare the two files. The cmp utility reports that the files are different and identifies the offset from the start of the files where the first difference is found:

$ cmp a b a b differ: char 39, line 1


You can display the values of the bytes at that location by adding the printbytes option:

$ cmp --print-bytes a b a b differ: char 39, line 1 is 172 z 163 s


The l option displays all bytes that differ between the two files. Because this option creates a lot of output if the files have many differences, you may want to redirect the output to a file or pager. The following example shows the two differences between files a and b. The b option displays the values for the bytes as well. Where file a has a CONTROLJ (NEWLINE), file b has a CONTROLI (TAB). The message saying that it has reached the end of file on file a indicates that file b is longer than file a.

$ cmp -lb a b 39 172 z    163 s 46  12 ^J    11 ^I cmp: EOF on a


In the next example, the ignoreinitial option is used to skip over the first difference in the files. The cmp utility now reports the second difference. The difference is put at character 7, which is the 46th character in the original file b (7 characters past the ignored 39 characters).

$ cmp --ignore-initial=39 a b a b differ: char 7, line 1


You can use skip1 and skip2 in place of the ignoreinitial option used in the preceding example:

$ cmp a b 39 39 a b differ: char 7, line 1


comm: Compares sorted files

comm [options] file1 file2

The comm utility displays a line-by-line comparison of two sorted files. The first of the three columns it displays lists the lines found only in file1, the second column lists the lines found only in file2, and the third lists the lines common to both files.

Arguments

The file1 and file2 are pathnames of the files that comm compares. Using a hyphen (-) in place of file1 or file2 causes comm to read standard input instead of that file.

Options

You can combine the options.

1

Does not display column 1 (does not display lines found only in file1).

2

Does not display column 2 (does not display lines found only in file2).

3

Does not display column 3 (does not display lines found in both files).


Notes

If the files have not been sorted, comm will not work properly.

Lines in the second column are preceded by one TAB, and those in the third column are preceded by two TABs.

The exit status indicates whether comm completed normally (0) or abnormally (not 0).

Examples

The following examples use two files, c and d, in the working directory. As with all input to comm, the files have already been sorted:

$ cat c bbbbb ccccc ddddd eeeee fffff $ cat d aaaaa ddddd eeeee ggggg hhhhh


Refer to sort on page 837 for information on sorting files.

The following example calls comm without any options, so it displays three columns. The first column lists those lines found only in file c, the second column lists those found only in d, and the third lists the lines found in both c and d:

$ comm c d         aaaaa bbbbb ccccc                 ddddd                 eeeee fffff         ggggg         hhhhh


The next example shows the use of options to prevent comm from displaying columns 1 and 2. The result is column 3, a list of the lines common to files c and d:

$ comm -12 c d ddddd eeeee


configure: Configures source code automatically

./configure options

The configure script is part of the GNU Configure and Build System. Software developers who supply source code for their products face the problem of making it easy for relatively naive users to build and install their software package on a wide variety of machine architectures, operating systems, and system software. To solve this problem many software developers supply a shell script named configure with their source code.

When you run configure, it determines the capabilities of the local system. The data collected by configure is used to build the makefiles with which make (page 783) builds the executables and libraries. You can adjust the behavior of configure by specifying command line options and environment variables.

Options

disable-feature

Works in the same manner as enable-feature except that it disables support for feature.

enable-feature

Replace feature with the name of a feature that can be supported by the software being configured. For example, configuring the Z Shell source code with the command configure enable-zsh-mem configures the source code to use the special memory allocation routines provided with zsh instead of using the system memory allocation routines. Check the README file supplied with the software distribution to see the choices available for feature.

help

Displays a detailed list of all options available for use with configure. The contents of this list depend on the software distribution being configured.

prefix=directory

By default configure builds makefiles that install software in the /usr/local directory (when you give the command make install). To install the software into a different directory, replace directory with the pathname of the new target directory.

with-package

Replace package with the name of an optional package that can be included with the software you are configuring. For example, if you configure the source code for the Windows emulator wine with the command configure with-dll, the source code is configured to build a shared library of Windows emulation support. Check the README file supplied with the software distribution to see the choices available for package. Also, configure help usually displays the choices available for package.


Discussion

The GNU Configure and Build System allows software developers to distribute software that can configure itself to be built on a variety of systems. It builds a shell script named configure, which prepares the software distribution to be built and installed on a local system. The configure script searches the local system to find the various dependencies for the software distribution and constructs the appropriate makefiles. Once you have run configure, you can build the software with a make command and install the software with a make install command.

The configure script determines which C compiler to use (usually gcc) and specifies a set of flags to pass to that compiler. You can set the environment variables CC and CFLAGS to override these values with your own choices. (See "Macros" on page 494 and the "Examples" section following for more information.)

Notes

Each package that uses the GNU autoconfiguration utility provides its own custom copy of configure, which the software developer created using the GNU autoconf utility. Read the README and INSTALL files that are provided with the package to obtain detailed information about the available options.

The configure scripts are self-contained and run correctly on a wide variety of systems, including OS X. You do not need any special system resources to use configure.

Examples

The simplest way to call configure is to cd to the base directory for the software distribution you want to configure and then run the following command:

$ ./configure


The ./ is prepended to the command name to ensure that you are running the configure script that was supplied with the software distribution. To cause configure to build makefiles that pass the flags Wall and O2 to gcc, use the following command from bash:

$ CFLAGS="-Wall -02" ./configure


If you are using tcsh, use the following command:

tcsh $ env CFLAGS="-Wall -02" ./configure


cp: Copies files

cp [options] source-file destination-file

cp [options] source-file-list destination-directory

The cp utility copies one or more files. It can make a copy of a single file (first format), or it can copy one or more files to a directory (second format). With the r option, cp can copy directories.

Arguments

The source-file is the pathname of the file that cp makes a copy of. The destination-file is the pathname that cp assigns to the resulting copy of the file.

The source-file-list specifies one or more pathnames of files that cp makes copies of. The destination-directory is the pathname of the directory in which cp places the copied files. With this format, cp gives each of the copied files the same simple filename as its source-file.

The r option enables cp to copy directories recursively from the source-file-list into the destination-directory.

Options

f

(force) When the destination-file exists and cannot be opened for writing, this option causes cp to try to remove destination-file before copying source-file. This option is useful when the user copying a file does not have write permission to an existing destination-file but has write permission to the directory containing the destination-file.

i

(interactive) Prompts you whenever cp would overwrite a file. If you respond with a string that starts with y or Y, cp continues. If you enter anything else, cp does not copy the file.

H

(dereference) Copies the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not copy the files that symbolic links found while descending a directory hierarchy point to. See P.

L

(dereference) Copies the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to. See P.

p

(preserve) Creates a destination-file with the same owner, group, permissions, access date, and modification date as the source-file.

P

(no dereference) Copies symbolic links, not the files that the links point to. Without the R option, the default behavior is to dereference links (copy the files that links point to, not the links). With one of these options, cp does not dereference symbolic links (it copies the links, not the files that the links point to).

R

Recursively copies directory hierarchies including ordinary files. The P option is implied.

v

(verbose) Displays the name of each file as cp copies it.


Notes

If the destination-file exists before you execute cp, cp overwrites the file, destroying the contents but leaving the access privileges, owner, and group associated with the file as they were.

If the destination-file does not exist, cp uses the access privileges of the source-file. The user who copies the file becomes the owner of the destination-file and the user's group becomes the group associated with the destination-file.

With the p option, cp attempts to set the owner, group, permissions, access date, and modification date to match those of the source-file.

Unlike ln (page 772), the destination-file that cp creates is independent of its source-file.

Under Mac OS X version 10.4 and later, the cp utility copies extended attributes (page 93). Under version 10.3 and earlier, cp does not copy extended attributes. The CpMac utility, provided with the Developer Tools package (page 478) and available in the /Developer/Tools directory, copies extended attributes and is available on older versions of OS X.

Examples

The first command makes a copy of the file letter in the working directory. The name of the copy is letter.sav.

$ cp letter letter.sav


The next command copies all files with filenames ending in .c into the archives directory, which is a subdirectory of the working directory. Each copied file retains its simple filename but has a new absolute pathname. Because of the p option, the copied files in archives have the same owner, group, permissions, access date, and modification date as the source files.

$ cp -p* .c archives


The next example copies memo from /Users/jenny to the working directory:

$ cp /Users/jenny/memo .


The following command copies the files named memo and letter into another directory. The copies have the same simple filenames as the source files (memo and letter) but different absolute pathnames. The absolute pathnames of the copied files are /Users/jenny/memo and /Users/jenny/letter.

$ cp memo letter /Users/jenny


The final command demonstrates one use of the f option. Alex owns the working directory and tries unsuccessfully to copy one onto a file (me) that he does not have write permission for. Because he has write permission to the directory that holds me, Alex can remove the file but not write to it. The f option enables him to overwrite one with me.

$ ls -ld drwxrwxr-x   2 alex alex  4096 Oct 21 22:55 . $ ls -l -rw-r--r--   1 root admin 3555 Oct 21 22:54 me -rw-rw-r--   1 alex alex  1222 Oct 21 22:55 one $ cp one me cp: cannot create regular file 'me': Permission denied $ cp -f one me $ ls -l -rw-r--r--   1 alex alex  1222 Oct 21 22:58 me -rw-rw-r--   1 alex alex  1222 Oct 21 22:55 one


Refer to "Directory Access Permissions" on page 90 for more information.

cpio: Creates an archive, restores files from an archive, or copies a directory

cpio i [options] [pattern-list]

cpio o [options]

cpio p [options] destination-directory

The cpio utility has three modes of operation: Create mode places multiple files into a single archive file, Extract mode restores files from an archive, and Copy mode makes a copy of a directory hierarchy. The archive file used by cpio may be saved on disk, removable media, or a remote system.

Create mode (o for copy-out) reads a list of ordinary or directory filenames from standard input and writes the resulting archive file to standard output. Extract mode (i for copy-in) reads an archive from standard input and extracts files from that archive. Copy mode (p for pass-through) reads a list of ordinary or directory filenames from standard input and copies the files to a directory.

Arguments

In Extract mode cpio extracts all files found in the archive that it reads from standard input. You can choose to extract or display the names of files selectively by supplying a pattern-list. If the name of a file in the archive matches a pattern in the pattern-list, that file is extracted; otherwise, it is ignored. The cpio patterns are similar to shell wildcards (page 133) except that they match slashes (/) and a leading period (.) in a filename. See the fnmatch man page for more information on cpio patterns.

In Copy mode the destination-directory is the name of the directory that cpio copies files into.

Options

A single, mandatory major option specifies the mode in which cpio operates: Create, Extract, or Copy. You can omit the other options.

Major Options

You must specify exactly one of these options.

i

(copy in) Puts cpio in Extract mode, in which it reads the archive from standard input and extracts files. Without any patterns on the command line, cpio extracts all the files from the archive. With patterns, cpio exTRacts only files with names that the patterns match. The following example extracts from the root.cpio archive file on an external drive only those files whose names end in .c:

$ cpio -i \*.c < /Volumes/Backups/root.cpio


The backslash prevents the shell from expanding the * before it passes the argument to cpio.

o

(copy out) Puts cpio in Create mode, in which it constructs an archive from the files named on standard input. These files may be ordinary or directory files, and each must appear on a separate line. The archive is written to standard output. The find utility frequently generates the filenames that cpio uses. The following command builds an archive of the startup volume (root filesystem) and writes it to the archive on /Volumes/Backups:

[View full width]

$ find -x -d / -print cpio -o >/Volumes/Backups /root.cpio


The x option causes find to traverse only the startup volume; otherwise, find would eventually reach the root.cpio file and cause cpio to try to back it up. The d option causes find to search for files in a depth-first manner, reducing the likelihood of permissions problems when you restore the files from the archive. See the discussion of this option on page 696.

p

(pass through) Puts cpio in Copy mode, in which it copies files named on standard input from one place on the system to another. Instead of constructing an archive file containing the files named on standard input, cpio copies them into the destination-directory (the last argument on the cpio command line). The effect is the same as if you had created an archive in Create mode and then extracted the files in Extract mode, except that using Copy mode avoids creating an archive. The following example copies the working directory hierarchy into /Users/alex/code. Make sure that ~alex/code is not a subdirectory of the working directory or you will perform a recursive copy.

$ find -d . -print | cpio -pdm ~alex/code



Other Options

The remaining options alter the behavior of cpio. These options work with one or more of the three major options.

a

(access time) Resets the access times of source files after copying them so that they have the same access time after copying as they did before copying.

B

(block) Sets the block size to 5,120 bytes instead of the default 512 bytes.

c

(compatible) Writes header information in ASCII so that older (incompatible) cpio utilities on other systems can read the file. This option is rarely needed.

d

(directories) Creates directories as needed when copying files. For example, you need this option when you are extracting files from an archive with a file list generated by find with the d option. This option works in Extract and Copy modes only.

E

filename

 

Reads pattern-list from filename, one pattern per line. You can specify additional patterns on the command line.

f

(flip) Reverses the sense of the test done on pattern-list when extracting files from an archive. Files are extracted from the archive only if they do not match any patterns in pattern-list.

F

archive

 

(file) Uses archive as the name of the archive file. In Extract mode, reads from archive instead of standard input. In Create mode, writes to archive instead of standard output. You can use this option to access a device on another system on a network.

l

(link) When possible, links files instead of copying them.

L

(dereference) Copies the files that symbolic links point to, not the symbolic links themselves.

m

(modification) Preserves the modification times of files that are extracted from an archive. Without this option, the files show the time they were extracted. With this option, the created files show the time they had when they were copied into the archive.

r

(rename) Allows you to rename files as cpio copies them. When cpio prompts you with the name of a file, you can respond with the new name. The file is then copied with the new name. If you press RETURN without entering a name, cpio does not copy the file.

t

(table of contents) Displays a table of contents of the archive. This option works only with the i option, although no files are extracted from the archive. With the v option, it displays a detailed table of contents in a format similar to that displayed by ls l.

u

(unconditional) Overwrites existing files regardless of their modification times. Without this option, cpio will not overwrite a more recently modified file with an older one; it simply displays a warning message.

v

(verbose) Lists files as they are processed. With the t option, it displays a detailed table of contents in a format similar to that displayed by ls l.


Discussion

Without the u option, cpio will not overwrite a more recently modified file with an older file.

You can use both ordinary and directory filenames as input when you create an archive. If the name of an ordinary file appears in the input list before the name of its parent directory, the ordinary file appears before its parent directory in the archive as well. This order can lead to an avoidable error: When you extract files from the archive, the child has nowhere to go in the file structure if its parent has not yet been extracted.

Making sure that files appear after their parent directories in the archive is not always a solution. Consider the problem that occurs if the m option is used when extracting files. Because the modification time of a parent directory is updated whenever a file is created within it, the original modification time of the parent directory is lost when the first file is written to it.

The solution to this potential problem is to ensure that all files appear before their parent directories when creating an archive and to create directories as needed when extracting files from an archive. When you use this technique, directories are extracted only after all files have been written to them and their modification times are preserved.

With the d option, the find utility generates a list of files in which all children appear in the list before their parent directories. If you use this list to create an archive, the files are in the proper order. (Refer to the first example in "Examples.") When extracting files from an archive, the d option causes cpio to create parent directories as needed and the m option preserves modification times. Using this combination of utilities and options preserves directory modification times through a create/extract sequence.

This strategy also solves another potential problem. Sometimes a parent directory may not have permissions set so that you can extract files into it. When cpio automatically creates the directory with d, you can be assured that you have write permission to the directory. When the directory is extracted from the archive (after all the files are written into the directory), it is extracted with its original permissions.

Notes

Under Mac OS X version 10.4 and later, cpio copies extended attributes (page 93). Under version 10.3 and earlier, cpio does not copy extended attributes. For a similar utility that does copy extended attributes, see ditto (page 715).

Examples

The first example creates an archive of the files in Jenny's home directory, writing the archive file to a backup disk:

$ find -d /Users/jenny -print | cpio -o >/Volumes/Backups/jenny.cpio


The find utility produces the filenames that cpio uses to build the archive. The d option causes all entries in a directory to be listed before the directory name itself, making it possible for cpio to preserve the original modification times of directories (see the preceding "Discussion"). Use the d and the m options when you extract files from this archive (see the following examples).

The next example displays a detailed listing of the files in the archive file:

$ cpio -itv < /Volumes/Backups/jenny.cpio


The following command restores the files that formerly were in the memo subdirectory of Jenny's home directory:

$ cpio -idm /Users/jenny/memo/\* < /Volumes/Backups/jenny.cpio


The d option ensures that any subdirectories that were in the memo directory are re-created as needed. The m option preserves the modification times of files and directories. The asterisk in the regular expression is escaped to keep the shell from expanding it.

The final example uses the f option to restore all files in the archive except those that were formerly in the memo subdirectory:

$ cpio -ivmdf /Users/jenny/memo/\* < /Volumes/Backups/jenny.cpio


The v option lists the extracted files as cpio processes the archive, verifying that the expected files are extracted.

crontab: Maintains crontab files

crontab [u username] filename

crontab [u username] option

A crontab file associates periodic times (such as 14:00 on Wednesdays) with commands. The cron utility executes each command at the specified time. When you are working as yourself, the crontab utility installs, removes, lists, and edits your own crontab file. Superuser can work with any user's crontab file.

Arguments

The first format copies the contents of filename (which contains crontab commands) into the crontab file of the user who runs the command. When the user does not have a crontab file, this process creates a new one; when the user already has a crontab file, it overwrites the file. When you replace filename with a hyphen (-), crontab reads from standard input.

The second format lists, removes, or edits the crontab file, depending on which option you specify.

Options

Choose only one of the e, l, and r options. Superuser can use u with one of these options.

e

(edit) Runs the text editor specified by the VISUAL or EDITOR shell variable on the crontab file, enabling you to add, change, or delete entries. Installs the modified crontab file when you exit from the editor.

l

(list) Displays the contents of the crontab file.

r

(remove) Deletes the crontab file.

u

username

 

(user) Works on the crontab file belonging to username. Only Superuser can use this option, and Superuser should always use this option.


Notes

This section covers the versions of cron, crond, crontab, and crontab files that were written by Paul Vixiehence the term Vixie cron. These versions differ from an earlier version of Vixie cron as well as from the classic SVR3 syntax. This version is POSIX compliant. Mac OS X 10.4 and later use cron for user jobs only; system jobs are handled by launchd (page 456).

User crontab files are kept in the /var/cron/tabs directory. Each of these files is named with the username of the user that it belongs to, owned by root, and associated with the user's primary group.

The system utility named cron reads the crontab files and runs the commands. If a command line in a crontab file does not redirect its output, output sent to standard output and standard error is mailed to the user unless you set the MAILTO variable within the crontab file to a different username.

Following is a typical user crontab file:

$ crontab -l 07 4 * * *      /Users/alex/bin/update_mirrors 13 1 * * *      /Users/alex/weblog/nightly


Each entry in a crontab file begins with five fields that specify when the command is to run (minute, hour, day of the month, month, and day of the week). The cron utility interprets an asterisk appearing in place of a number as a wildcard representing all possible values. In the day-of-the-week field, you can use either 7 or 0 to represent Sunday. The preceding example runs update_mirrors daily at 4:07 AM and nightly daily at 1:13 AM.

It is a good practice to start cron jobs a variable number of minutes before or after the hour, half hour, or quarter hour. When you start them at these times, it becomes less likely that many processes will start at the same time, potentially overloading the system.

The cron daemon is started by launchd. If cron has no jobs to run, it exits. It starts automatically when cron jobs are created. When cron starts, it reads all crontab files into memory. The cron utility mostly sleeps but wakes up once a minute, reviews all crontab entries it has stored in memory, and runs whichever ones are due to be run at that time.

/var/cron/allow/var/cron/deny

Superuser determines which users can run crontab by creating, editing, and removing the /var/cron/allow and /var/cron/deny files. When you create a deny file with no entries and no allow file exists, everyone can use crontab. When the allow file exists, only users listed in that file can use crontab, regardless of the presence and contents of deny. Otherwise, you can list in the allow file those users who are allowed to use crontab and in the deny file those who are not allowed to use it. (Listing a user in deny is not strictly necessary because, if an allow file exists and the user is not listed in it, the user will not be able to use crontab anyway.)

Examples

The following example uses crontab l to list the contents of Jenny's crontab file (/var/cron/tabs/jenny). All the scripts that Jenny runs are in her ~/bin directory. The first line sets the MAILTO variable to alex so that Alex gets the output from commands run from Jenny's crontab file that is not redirected. The sat.job script runs every Saturday (day 6) at 2:05 AM, twice.week runs at 12:02 AM on Sunday and Thursday (days 0 and 4), and twice.day runs twice a day, every day, at 10:05 AM and 4:05 PM.

$ who am i jenny $ crontab -l MAILTO=alex 05 02 * * 6        $HOME/bin/sat.job 00 02 * * 0,4      $HOME/bin/twice.week 05 10,16 * * *     $HOME/bin/twice.day


To add an entry to your crontab file, run the crontab utility with the e (edit) option.

cut: Selects characters or fields from input lines

cut [options] [file-list]

The cut utility selects characters or fields from lines of input and writes them to standard output. Character and field numbering start with 1.

Arguments

The file-list specifies the pathnames of one or more ordinary files that cut will work with. If you do not specify an argument or if you specify a hyphen (-) in place of a filename, cut reads from standard input.

Options

c

clist

 

(characters) Selects the characters given by the column numbers in clist. The value of clist is one or more comma-separated column numbers or column ranges. A range is specified by two column numbers separated by a hyphen. A range of -n means columns 1 through n; n means columns n through the end of the line.

d

dchar

 

(delimiter) Specifies dchar as the input and output field delimiter. The default delimiter is a TAB character. Quote characters as necessary to protect them from shell expansion.

f

flist

 

(fields) Selects the fields specified in flist. The value of flist is one or more comma-separated field numbers or field ranges. A range is specified by two field numbers separated by a hyphen. A range of -n means fields 1 through n; n- means fields n through the last field. The field delimiter is a TAB character unless you use the -d option to change it.


Notes

Although limited in functionality, cut is easy to learn and use and is a good choice when columns and fields can be selected without using pattern matching. Sometimes cut is used with paste (page 807).

Examples

For the next two examples, assume that an ls l command produces the following output:

$ ls -l total 2944 -rwxr-xr-x 1 zach zach     259 Feb  1 00:12 countout -rw-rw-r-- 1 zach zach    9453 Feb  4 23:17 headers -rw-rw-r-- 1 zach zach 1474828 Jan 14 14:15 memo -rw-rw-r-- 1 zach zach 1474828 Jan 14 14:33 memos_save -rw-rw-r-- 1 zach zach    7134 Feb 4  23:18 tmp1 -rw-rw-r-- 1 zach zach    4770 Feb 4  23:26 tmp2 -rw-rw-r-- 1 zach zach   13580 Nov 7  08:01 typescript


The following command outputs the permissions of the files in the working directory. The cut utility with the c option selects characters 2 through 10 from each input line. The characters in this range are written to standard output.

$ ls -l | cut -c2-10 otal 2944 rwxr-xr-x rw-rw-r-- rw-rw-r-- rw-rw-r-- rw-rw-r-- rw-rw-r-- rw-rw-r--


The next command outputs the size and name of each file in the working directory. This time the f option selects the fifth and ninth fields from the input lines. The d option tells cut to use SPACEs, not TABs, as delimiters. The tr utility (page 879) with the s option changes sequences of more than one SPACE character into a single SPACE; otherwise, cut counts the extra SPACE characters as separate fields.

$ ls -l | tr -s '  ' ' ' | cut -f5,9 -d' ' 259 countout 9453 headers 1474828 memo 1474828 memos_save 7134 tmp1 4770 tmp2 13580 typescript


The last example displays a list of full names that are stored in the eighth field of the passwd database. The nidump utility (page 796) sends its output to standard output, and a pipe redirects the output to standard input of cut. The d option specifies that the colon character be used as the field delimiter.

$ nidump passwd / nobody:*:-2:-2::0:0:Unprivileged User:/var/empty:/usr/bin/false root:********:0:0::0:0:System Administrator:/private/var/root:/bin/sh ... alex:********:501:501::0:0:Alex Watson:/Users/alex:/bin/bash jenny:*:502:502::0:0:Jenny Chen:/Users/jenny:/bin/zsh ... $ nidump passwd / | cut -d: -f8 - Unprivileged User System Administrator ... Alex Watson Jenny Chen


date: Displays or sets the system time and date

date [options] [+format]

date [options] [newdate]

The date utility displays the time and date known to the system. Superuser can use date to change the system clock.

Arguments

The +format argument specifies the format for the output of date. The format string consisting of field descriptors and text follows a plus sign (+). The field descriptors are preceded by percent signs, and each one is replaced by its value in the output. Table VI-9 lists some of the field descriptors.

Table VI-9. Field descriptors

Descriptor

Meaning

%a

Abbreviated weekdaySun to Sat

%A

Unabbreviated weekdaySunday to Saturday

%b

Abbreviated monthJan to Dec

%B

Unabbreviated monthJanuary to December

%c

Date and time in default format used by date

%d

Day of the month01 to 31

%D

Date in mm/dd/yy format

%H

Hour00 to 23

%I

Hour00 to 12

%j

Julian date (day of the year001 to 366)

%m

Month of the year01 to 12

%M

Minutes00 to 59

%n

NEWLINE character

%p

AM or PM

%r

Time in AM/PM notation

%s

Number of seconds since the beginning of January 1, 1970

%S

Seconds00 to 60 (the 60 accommodates leap seconds)

%t

TAB character

%T

Time in HH:MM:SS format

%w

Day of the week0 to 6 (0 = Sunday)

%y

Last two digits of the year00 to 99

%Y

Year in four-digit format (for example, 2005)

%Z

Time zone (for example, PDT)


The date utility zero fills numeric fields.

The date utility assumes that, in a format string, characters that are not percent signs or field descriptors are ordinary text; date copies these characters to standard output. You can use ordinary text to add punctuation to the date and to add labels (for example, you can put the word DATE: in front of the date). Surround the format argument with single quotation marks if it contains SPACEs or other characters that have a special meaning to the shell.

Setting the date

When Superuser specifies newdate, the system changes the system clock to reflect the new date. The newdate argument has the format

nnddhhmm[[cc]yy][.ss]


where nn is the number of the month (0112), dd is the day of the month (0131), hh is the hour based on a 24-hour clock (0023), and mm is the minutes (0059). When you change the date, you must specify at least these fields.

The optional cc specifies the first two digits of the year (the value of the century minus 1), and yy specifies the last two digits of the year. You can specify yy or ccyy following mm. When you do not specify a year, date assumes that the year has not changed.

You can specify the number of seconds past the start of the minute with .ss.

Options

r

seconds

 

Displays the date and time that is seconds seconds after the epoch (midnight, January 1, 1970 UTC).

u

(UTC) Displays or sets the time and date using Universal Coordinated Time (UTC, page 960; also called Greenwich Mean Time [GMT]).


Notes

If you set up a locale database, date uses that database to substitute terms appropriate to your locale (page 941).

Examples

The first example shows how to set the date for 2:07:30 PM on August 19 without changing the year:

# date 08191407.30 Fri Aug 19 14:07:30 PDT 2005


The next example shows the format argument, which causes date to display the date in a commonly used format:

$ date '+Today is %h %d, %Y' Today is Aug 19, 2005


dd: Converts and copies a file

dd [arguments]

The dd (device-to-device copy) utility converts and copies a file. The primary use of dd is to copy files to and from such devices as tape and floppy drives. Often dd can handle the transfer of information to and from other operating systems when other methods fail. A rich set of arguments gives you precise control over the characteristics of the transfer.

Arguments

Accepts the common options described on page 663.

By default dd copies standard input to standard output.

bs=n

(block size) Reads and writes n bytes at a time. This argument overrides the ibs and obs arguments.

cbs=n

(conversion block size) When performing data conversion during the copy, converts n bytes at a time.

conv=type[,type...]

 

By applying conversion types in the order given on the command line, converts the data that is being copied. The types must be separated by commas with no SPACEs. Table VI-10 lists the conversion types.


Table VI-10. Conversion types

type

Meaning

ascii

Converts EBCDIC-encoded characters to ASCII, allowing you to read tapes written on IBM mainframe and similar computers.

block

Each time a line of input (that is, a sequence of characters terminated with a NEWLINE character) is read, outputs a block of text without the NEWLINE. Each output block has the size given by the obs or bs argument and is created by adding trailing SPACE characters to the text until it reaches the proper size.

ebcdic

Converts ASCII-encoded characters to EBCDIC, allowing you to write tapes for use on IBM mainframe and similar computers.

unblock

Performs the opposite of a block conversion.

lcase

Converts uppercase letters to lowercase while copying data.

noerror

If a read error occurs, dd normally terminates. This conversion allows dd to continue processing data. This conversion is useful when you are trying to recover data from bad media.

notrunc

Does not truncate the output file before writing to it.

ucase

Converts lowercase letters to uppercase while copying data.


count=numblocks

Restricts to numblocks the number of blocks of input that dd copies. The size of each block is specified by the ibs argument.

ibs=n

(input block size) Reads n bytes at a time.

if=filename

(input file) Reads from filename instead of from standard input. You can specify a device name for filename to read from that device.

obs=n

(output block size) Writes n bytes at a time.

of=filename

(output file) Writes to filename instead of to standard output. You can specify a device name for filename to write to that device.

seek=numblocks

Skips numblocks blocks of output before writing any output. The size of each block is specified by the obs argument.

skip=numblocks

Skips numblocks blocks of input before starting to copy. The size of each block is specified by the ibs argument.


Notes

You can use some of the standard multiplicative suffixes to make it easier to specify large block sizes, but dd uses lowercase letters instead of the uppercase letters shown in Table VI-1 on page 662. In addition to the k, m, and g suffixes, dd supports b (block, multiply by 512) and w (word, multiply by the number of bytes in an integer).

Examples

The dd utility can create simple disk images. The following example makes a raw disk image of the partition disk0s1:

# dd if=/dev/disk0s1 of=backup


You can also use dd to create a file filled with pseudorandom bytes:

$ dd if=/dev/random of=randfile2 bs=1 count=100


The preceding command reads from the /dev/random file (an interface to the kernel's random number generator) and writes to the file named randfile. The block size is 1 and the count is 100, so randfile is 100 bytes long. See the random man page in section 4 of the system manual for more information.

Wiping a file

You can use a similar technique to wipe data from a file before deleting it, making it almost impossible to recover data from the deleted file. You might want to wipe a file for security reasons. Wipe a file several times for added security.

In the following example, ls shows the size of the file named secret; dd, with a block size of 1 and a count corresponding to the number of bytes in secret, then wipes the file. The conv=notrunc argument ensures that dd writes over the data in the file and not another place on the disk.

$ ls -l secret -rw-rw-r--  1 max max 2494 Feb  6 00:56 secret $ dd if=/dev/random of=secret bs=1 count=2494 conv=notrunc 2494+0 records in 2494+0 records out $ rm secret


df: Displays disk space usage

df [options] [filesystem-list]

The df (disk free) utility reports on the total space and the free space on each mounted device.

Arguments

When you call df without an argument, it reports on the free space on each mounted device.

The filesystem-list is an optional list of one or more pathnames that specify the filesystems that the report is to cover. You can refer to a mounted filesystem by its device pathname or by the pathname of the directory it is mounted on.

Options

h

(human readable) Displays sizes in K (kilobyte), M (megabyte), and G (gigabyte) blocks, as appropriate.

i

(inode) Reports the number of inodes (page 937) that are used and free in addition to reporting on blocks.

k

(kilobyte) Displays usage in 1,024-byte blocks.

l

(local) Displays local filesystems only.

T

fstype

 

(type) Reports information only about the filesystems of type fstype, such as hfs or nfs. Repeat this option to report on several types of filesystems.


Notes

The df utility supports the BLOCKSIZE environment variable (page 663) and ignores block sizes smaller than 512 bytes or larger than 1 gigabyte.

The count of used and free inodes is meaningless on HFS+ filesystems, where new files can be created as long as free space is available in the filesystem.

Examples

In the following example, df displays information about all mounted filesystems on the local system:

$ df Filesystem        512-blocks     Used     Avail Capacity Mounted on /dev/disk0s3        64465984  34221472  29732512   54%   / devfs                    215       215         0  100%   /dev fdesc                      2         2         0  100%   /dev <volfs>                 1024      1024         0  100%   /.vol /dev/disk1s9       102400000     54600 102345400    0%   /Volumes/Spare /dev/disk1s10      385995336 119741320 266254016   31%   /Volumes/House /dev/disk0s5       255182704 180721088 74461616    71%    /Volumes/Users automount -nsl [263]       0        0        0   100%    /Network automount -fstab [271]     0       0        0   100%    /automount/Servers automount -static [271]    0        0        0   100%   /automount/static


Next df is called with the l and h options, generating a human-readable list of local filesystems. The sizes in this listing are given in terms of megabytes and gigabytes.

$ df -lh Filesystem          Size   Used  Avail Capacity  Mounted on /dev/disk0s3         31G    16G    14G    54%    / /dev/disk1s9         49G    27M    49G     0%    /Volumes/Spare /dev/disk1s10       184G    57G   127G    31%    /Volumes/House /dev/disk0s5        122G    86G    36G    71%    /Volumes/Users


The next example uses the BLOCKSIZE environment variable to cause df to display information about the /Volumes/House partition in megabyte units, then in 1,000,000-byte units:

$ export BLOCKSIZE $ BLOCKSIZE=1M $ df /Volumes/House Filesystem    1M-blocks  Used  Avail Capacity  Mounted on /dev/disk1s10    188474 58467 130006    31%    /Volumes/House $ BLOCKSIZE=1000000 $ df /Volumes/House Filesystem    1000000-blocks  Used  Avail Capacity  Mounted on /dev/disk1s10         197743 61342 136400    31%    /Volumes/House


diff: Displays the differences between two files

diff [options] file1 file2

diff [options] file1 directory

diff [options] directory file2

diff [options] directory1 directory2

The diff utility displays line-by-line differences between two files. By default diff displays the differences as instructions you can use to edit one of the files to make it the same as the other.

Arguments

The file1 and file2 are pathnames of ordinary files that diff works on. When the directory argument is used in place of file2, diff looks for a file in directory with the same name as file1. It works similarly when directory replaces file1. When you specify two directory arguments, diff compares the files in directory1 with the files that have the same simple filenames in directory2.

Options

Accepts the common options described on page 663, with one exception: When one of the arguments is a directory and the other is an ordinary file, you cannot compare to standard input.

ignorespace-change

 

b

Ignores whitespace (SPACEs and TABs) at the ends of lines and considers other strings of whitespace to be equal.

ignoreblanklines

 

B

Ignores differences that involve only blank lines.

context[=lines] C

[lines]

 

Displays the sections of the two files that differ, including lines lines (the default is 3) around each line that differs to show the context. Each line in file1 that is missing from file2 is preceded by ; each extra line in file2 is preceded by +; and lines that are different in the two files are marked with !. When lines that differ are within lines lines of each other, they are grouped together in the output.

ed e

Creates and sends to standard output a script for the ed editor, which will edit file1 to make it the same as file2. You must add w (write) and q (quit) instructions to the end of the script if you plan to redirect input to ed from the script. When you use ed, diff displays the changes in reverse order: Changes to the end of the file are listed before changes to the top, preventing early changes from affecting later changes when the script is used as input to ed. For example, if a line near the top were deleted, subsequent line numbers in the script would be wrong.

ignore-case i

Ignores differences in case when comparing files.

new-file N

When comparing directories, when a file is present in one of the directories only, considers it to be present and empty in the other directory.

show-c-function

 

p

Shows which C function each change affects.

brief q

Does not display the differences between lines in the files. Instead, diff reports only that the files differ.

recursive r

When using diff to compare the files in two directories, causes the comparisons to extend through subdirectories as well.

unified[=lines] U

lines

 

Uses the easier-to-read unified output format. See the discussion of diff on page 49 for more detail and an example. The lines is the number of lines of context; the default is 3.

ignore-all-space

 

w

(whitespace) Ignores whitespace when comparing lines.

width=columns

 

W

columns

 

Sets the width of the columns that diff uses to display the output to columns. This option is useful with the side-by-side option. The sdiff utility uses a lowercase w to perform the same function: w columns.

side-by-side y

Displays output in a side-by-side format. This option generates the same output as sdiff. Use the width=columns option with this option.


Discussion

When you use diff without any options, it produces a series of lines containing Add (a), Delete (d), and Change (c) instructions. Each of these lines is followed by the lines from the file that you need to add, delete, or change to make the files the same. A less than symbol (<) precedes lines from file1. A greater than symbol (>) precedes lines from file2. The diff output appears in the format shown in Table VI-11. A pair of line numbers separated by a comma represents a range of lines; a single line number represents a single line.

Table VI-11. diff output

Instruction

Meaning (to change file1 to file2)

line1 a line2,line3 > lines from file2


Append line2 through line3 from file2 after line1 in file1

line1,line2 d line3 < lines from file1


Delete line1 through line2 from file1

line1,line2 c line3,line4 < lines from file1 > lines from file 2


Change line1 through line2 in file1 to line3 through line 4 from file2


The diff utility assumes that you will convert file1 to file2. The line numbers to the left of each of the a, c, or d instructions always pertain to file1; the line numbers to the right of the instructions apply to file2. To convert file2 to file1, run diff again, reversing the order of the arguments.

Notes

The sdiff utility is similar to diff but its output may be easier to read. The diff side-by-side option produces the same output as sdiff. See the "Examples" section and refer to the diff and sdiff man and info pages for more information.

The diff3 utility compares three files.

Examples

The first example shows how diff displays the differences between two short, similar files:

$ cat m aaaaa bbbbb ccccc $ cat n aaaaa ccccc $ diff m n 2d1 < bbbbb


The difference between files m and n is that the second line of file m (bbbbb) is missing from file n. The first line that diff displays (2d1) indicates that you need to delete the second line from file1 (m) to make it the same as file2 (n). The next line diff displays starts with a less than symbol (<), indicating that this line of text comes from file1. In this example, you do not need this informationall you need to know is the line number so that you can delete the line.

The side-by-side option and the sdiff utility, both with the output width set to 30 columns (characters), display the same output. In the output a less than symbol points to the extra line in file m, whereas diff/sdiff leaves a blank line in file n where the extra line would go to make the files the same.

$ diff --side-by-side --width=30 m n aaaaa           aaaaa bbbbb         < ccccc           ccccc $ sdiff -w 30 m n aaaaa           aaaaa bbbbb         < ccccc           ccccc


The next example uses the same m file and a new file, p, to show diff issuing an a (append) instruction:

$ cat p aaaaa bbbbb rrrrr ccccc $ diff m p 2a3 > rrrrr


In the preceding example, diff issues the instruction 2a3 to indicate that you must append a line to file m after line 2 to make it the same as file p. The second line that diff displays indicates that the line comes from file p (the line begins with >, indicating file2). In this example, you need the information on this line; the appended line must contain the text rrrrr.

The next example uses file m again, this time with file r, to show how diff indicates a line that needs to be changed:

$ cat r aaaaa -q ccccc $ diff m r 2c2 < bbbbb --- > q


The difference between the two files occurs in line 2: File m contains bbbbb, and file r contains q. The diff utility displays 2c2 to indicate that you need to change line 2. Next diff shows that you must change line 2 in file m (bbbbb) to line 2 in file r (q) to make the files the same. The three hyphens indicate the end of the text in file m that needs to be changed and the start of the text in file r that is to replace it.

Comparing the same files using the side-by-side and width options (y and W) yields an easier-to-read result. The pipe symbol (|) indicates that the line on one side must replace the line on the other side to make the files the same:

$ diff -y -W 30 m r aaaaa           aaaaa bbbbb         | -q ccccc           ccccc


The next examples compare the two files q and v:

$ cat q        $ cat v Monday         Monday Tuesday        Wednesday Wednesday      Thursday Thursday       Thursday Saturday       Friday Sunday         Saturday                Sundae


Running in side-by-side mode diff shows that Tuesday is missing from file v, there is only one Thursday in file q (compared with two in file v), and Friday is missing from file q. The last line is Sunday in file q and Sundae in file v: diff indicates that these lines are different. You can change file q to be the same as file v by removing Tuesday, adding one Thursday and Friday, and substituting Sundae from file v for Sunday from file q. Alternatively, you can change file v to be the same as file q by adding Tuesday, removing one Thursday and Friday, and substituting Sunday from file q for Sundae from file v.

$ diff -y -W 30 q v Monday          Monday Tuesday       < Wednesday       Wednesday Thursday        Thursday               > Thursday               > Friday Saturday        Saturday Sunday        | Sundae


Context diff

With the context option (called a context diff), diff displays output that tells you how to turn the first file into the second file. The top two lines identify the files and show that q is represented by asterisks, whereas v is represented by hyphens. A row of asterisks that indicates the start of a hunk of text is followed by a row of asterisks with the numbers 1,6 in the middle. This line indicates that the instructions in the first section tell you what to remove from or change in file qnamely, lines 1 through 6 (that is, all the lines of file q; in a longer file it would mark the first hunk). The hyphen on the next line means that you need to remove the line with Tuesday. The line with an exclamation point indicates that you need to replace the line with Sunday with the corresponding line from file v. The row of hyphens with the numbers 1,7 in the middle indicates that the next section tells you which lines from file vlines 1 through 7you need to add or change in file q. You need to add a second line with Thursday and a line with Friday, and you need to change Sunday in file q to Sundae (from file v).

$ diff --context q v ***  q   Mon Aug 22 18:26:45 2005 --- v   Mon Aug 22 18:27:55 2005 *************** *** 1,6 ****   Monday - Tuesday   Wednesday   Thursday   Saturday ! Sunday --- 1,7 ----   Monday   Wednesday   Thursday + Thursday + Friday   Saturday ! Sundae


diskutil: Checks, modifies, and repairs local volumes

diskutil action [arguments]

The diskutil utility mounts, unmounts, and displays information about disks and partitions (volumes). It can also format and repair filesystems and divide a disk into partitions.

Arguments

The action specifies what diskutil is to do. Table VI-12 lists common actions along with the argument each takes.

Table VI-12. diskutil actions

Action

Argument

Description

eraseVolume

type name device

Reformats device using the format type and the label name.

  

The filesystem type is most typically HFS+, but can also be UFS or MS-DOS.

  

The name specifies the name of the volume; alphanumeric names are the easiest to work with. You can specify additional options as part of the type. For example, a FAT32 filesystem (as used in Windows 98 and later) would have a type of MS-DOS FAT32. A journaled, case-sensitive, HFS+ filesystem would have a type of Case-sensitive Journaled HFS+.

info

device

Displays information about device. Does not require ownership of device.

list

[device]

Lists partitions on device. Without device lists partitions on all devices. Does not require ownership of device.

mount

device

Mounts device.

mountDisk

device

Mounts all devices on the disk containing device.

reformat

device

Reformats device using its current name and format.

repairVolume

device

Repairs the filesystem on device.

unmount

device

Unmounts device.

unmountDisk

device

Unmounts all devices on the disk containing device.

verifyVolume

device

Verifies the filesystem on device. Does not require ownership of device.


Notes

The diskutil utility provides access to the Disk Management framework, the support code used by the Disk Utility application. It allows some choices that are not supported from the graphical interface. For example, the Disk Utility application on non-Server systems does not support the HFS+ Extended (case-sensitive) format, but diskutil can format a disk as an HFS+ Extended filesystem on any version of Mac OS X.

You must own device, or be working with root privileges, when you specify an action that modifies or changes the state of a volume.

fsck

The diskutil verifyVolume and repairVolume actions are analogous to the fsck utility on other UNIX systems. Under OS X the fsck utility is deprecated except when the system is in single-user mode (page 437).

disktool

Some of the functions performed by diskutil were handled by disktool in the past.

Examples

The first example displays a list of disk devices and volumes available on the local system:

$ diskutil list /dev/disk0    #:                   type name                 size      identifier    0: Apple_partition_scheme                      *152.7 GB disk0    1:    Apple_partition_map                      31.5 KB   disk0s1    2:              Apple_HFS Eva01                30.7 GB   disk0s3    3:              Apple_HFS Users                121.7 GB  disk0s5 /dev/disk1    #:                   type name                 size      identifier    0: Apple_partition_scheme                      *232.9 GB disk1    1:    Apple_partition_map                      31.5 KB   disk1s1    2:         Apple_Driver43                      28.0 KB   disk1s2    3:         Apple_Driver43                      28.0 KB   disk1s3    4:       Apple_Driver_ATA                      28.0 KB   disk1s4    5:       Apple_Driver_ATA                      28.0 KB   disk1s5    6:         Apple_FWDriver                      256.0 KB  disk1s6    7:     Apple_Driver_IOKit                      256.0 KB  disk1s7    8:          Apple_Patches                      256.0 KB  disk1s8    9:              Apple_HFS Spare                48.8 GB   disk1s9   10:              Apple_HFS House                184.1 GB  disk1s10


The next example displays information about one of the mounted volumes:

$ diskutil info disk1s9    Device Node:        /dev/disk1s9    Device Identifier:  disk1s9    Mount Point:        /Volumes/Spare    Volume Name:        Spare    File System:        HFS+    Owners:             Enabled    Partition Type:     Apple_HFS    Bootable:           Is bootable    Media Type:         Generic    Protocol:           FireWire    SMART Status:       Not Supported    UUID:               C77BB3DC-EFBB-30B0-B191-DE7E01D8A563    Total Size:         48.8 GB    Free Space:         48.8 GB    Read Only:          No    Ejectable:          Yes


The next example formats the partition at /dev/disk1s8 as an HFS+ Extended (HFSX) filesystem and labels it Spare2. This command erases all data on the partition:

# diskutil eraseVolume 'Case-sensitive HFS+' Spare2 disk1s10 Started erase on disk disk1s10 Erasing Mounting Disk Finished erase on disk disk1s10


The final example shows the output of a successful verifyVolume operation:

$ diskutil verifyVolume disk1s9 Started verify/repair on volume disk1s9 Spare Checking HFS Plus volume. Checking Extents Overflow file. Checking Catalog file. Checking Catalog hierarchy. Checking volume bitmap. Checking volume information. The volume Spare appears to be OK. Mounting Disk Verify/repair finished on volume disk1s9 Spare


ditto: Copies files and creates and unpacks archives

ditto [options] source-file destination-file

ditto [options] source-file-list destination-directory

ditto c [options] source-directory destination-archive

ditto x [options] source-archive-list destination-directory

The ditto utility copies files, including extended attributes (page 93). It can copy to and from cpio and zip archive files, as well as copy ordinary files and directories.

Arguments

The source-file is the pathname of the file that ditto is to make a copy of. The destination-file is the pathname that ditto assigns to the resulting copy of the file.

The source-file-list specifies one or more pathnames of files and/or directories that ditto makes copies of. The destination-directory is the pathname of the directory that ditto copies the files and directories into. When you specify a destination-directory, ditto gives each of the copied files the same simple filename as its source-file.

The source-directory is a single directory that ditto copies into the destination-archive. The resulting archive holds copies of the contents of source-directory, but not the directory itself.

The source-archive-list specifies one or more pathnames of archives that ditto extracts into destination-directory.

Using a hyphen (-) in place of a filename or directory name causes ditto to read from standard input or write to standard output instead of reading from or writing to that file or directory.

Options

You cannot use the c and x options together.

c

(create archive) Creates an archive file.

x

(extract archive) Extracts files from an archive file.

help

Displays a help message.

k

(pkzip) Uses the zip format, instead of the default cpio (page 693) format, to create or extract archives. For more information on zip, see the tip named "gzip versus zip" on page 56.

norsrc

(no resource) Ignores extended attributes. This option causes ditto to copy only data forks (the default behavior under Mac OS X 10.3 and earlier).

rsrc

(resource) Copies extended attributes, including resource forks (the default behavior under Mac OS X 10.4 and later). Also, rsrc and rsrcFork.

v

(verbose) Sends a line to standard error for each directory copied.

V

(very verbose) Sends a line to standard error for each file, symbolic link, and device node copied.

X

(exclude) Prevents ditto from searching directories in filesystems other than the filesystem(s) that hold the files it was explicitly told to copy.

z

(compress) Uses gzip (page 756) or gunzip to compress or decompress cpio archives.


Notes

The ditto utility does not copy the locked attribute flag (page 95). See the tip on page 92 regarding the uchg flag. The utility also does not copy ACLs.

By default ditto creates and reads archives (page 921) in the cpio (page 693) format.

The ditto utility cannot list the contents of archive files. It can only create or extract files from archives. Use pax or cpio to list the contents of cpio archives, and use unzip with the l option to list the contents of zip files.

Examples

The following examples show three ways to back up a user's home directory, including extended attributes (except as mentioned in "Notes"), preserving timestamps and permissions. For these examples, include the rsrc option if you are working under OS X 10.3 or earlier. The first example copies Zach's home directory to the volume (filesystem) named Backups; the copy is a new directory named zach.0228:

$ ditto /Users/zach /Volumes/Backups/zach.0228


The next example copies Zach's home directory into a single cpio-format archive file on the volume named Backups:

$ ditto -c /Users/zach /Volumes/Backups/zach.0228.cpio


The next example copies Zach's home directory into a zip archive:

$ ditto -c -k /Users/zach /Volumes/Backups/zach.0228.zip


Each of the next three examples restores the corresponding backup archive into Zach's home directory, overwriting any files that are already there:

$ ditto /Volumes/Backups/zach.0228 /Users/zach $ ditto -x /Volumes/Backups/zach.0228.cpio /Users/zach $ ditto -x -k /Volumes/Backups/zach.0228.zip /Users/zach


You can use a hyphen (-) in place of a filename or directory name to read from standard input or write to standard output in place of reading from or writing to that file or directory. The following example copies the Scripts directory to a directory named ScriptsBackups on the remote host bravo. It uses an argument of a hyphen in place of source-directory locally to write to standard output and in place of destination-directory on the remote system to read from standard input:

$ ditto -c Scripts - | ssh bravo ditto -x - ScriptsBackups


The final example copies the local startup disk (the root filesystem) to the volume named Backups.root. Because some of the files can be read only as root, the script must be run by a user with root privileges. The X option keeps ditto from trying to copy other volumes (filesystems) that are mounted under /.

# ditto -X / /Volumes/Backups.root


dmesg: Displays kernel messages

dmesg [options]

The dmesg utility displays the kernel ring buffer, the buffer that the kernel stores its messages in.

Options

M

core

 

The core is the name of the file to process (defaults to /dev/kmem). The core file should be a core dump from an OS X kernel.

N

kernel

 

The kernel is the pathname of a kernel file (defaults to /mach). If you are displaying information about a core dump, kernel should be the kernel that was running at the time the core file was created.


Discussion

When the system boots, the kernel fills its ring buffer with messages regarding hardware and module initialization. Messages in the kernel ring buffer are often useful for diagnosing system problems.

Notes

As a ring buffer, the kernel message buffer keeps the most recent messages it receives, discarding the oldest messages once it fills up. To save a list of kernel boot messages, give the following command immediately after booting the system and logging in:

$ dmesg > dmesg.boot


This command saves the kernel messages in the dmesg.boot file. This list can be educational and quite useful when you are having a problem with the boot process.

The dmesg utility displays the same messages that the system displays on the text console when you hold down COMMAND-V while booting (verbose boot). The /var/log/system.log file holds manybut not allof the kernel messages.

Examples

The following command displays kernel messages in the ring buffer with the string serial in them, regardless of case. It shows that the kernel found a serial port device.

$ dmesg | grep -i serial Apple16X50PCI2: Identified 4 Serial channels at PCI SLOT-2 Bus=5 Dev=2 Func=0


du: Displays information on disk usage by file

du [options] [path-list]

The du (disk usage) utility reports how much disk space is occupied by a directory hierarchy or a file. By default du displays the number of 1,024-byte blocks occupied by the directory or file.

Arguments

Without any arguments, du displays information about the working directory and its subdirectories. The path-list specifies the directories and files that du reports on.

Options

Without any options, du displays the total storage used for each argument in path-list. For directories du displays this total after recursively listing the totals for all of the subdirectories.

a

(all) Displays the space used by all ordinary files along with the total for each directory.

c

Displays a grand total at the end of the output.

d

depth

 

Displays information for subdirectories to a level of depth directories.

h

(human readable) Displays sizes in K (kilobyte), M (megabyte), and G (gigabyte) blocks, as appropriate. Uses powers of 1,024.

H

(dereference) Includes the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not include the files that symbolic links found while descending a directory hierarchy point to.

k

(kilobytes) Displays sizes in 1-kilobyte blocks.

L

(dereference) Includes the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to.

P

(no dereference) Includes the sizes of symbolic links, not the files that the links point to (default).

s

(summarize) Displays only the total size of each directory in path-list.

x

Reports only on files and directories in filesystems that hold the files and directories specified in path-list.


Notes

The du utility supports the BLOCKSIZE environment variable (page 663). The default is 512 bytes. The k option overrides BLOCKSIZE.

Examples

In the first example, du displays size information about subdirectories in the working directory. The last line contains the grand total for the working directory and its subdirectories.

$ du 26        ./Postscript 4         ./RCS 47        ./XIcon 4         ./Printer/RCS 12        ./Printer 105       .


The total (105) is the number of blocks occupied by all ordinary files and directories under the working directory. All files are counted, even though du displays only the sizes of directories.

Next, using the s option, du displays the total for each of the directories in /Users but not for any subdirectories:

# du -s  /Users/* 8       /Users/Shared 3064    /Users/alex 8832    /Users/zach


The c option causes du to display a grand total:

# du -s -c  /Users/* 8       /Users/Shared ... 8832    /Users/zach 20326   total


If you do not have read permission for a file or directory that du encounters, du sends a warning to standard error and skips that file or directory. The following example uses the s (summarize), h (human-readable), and c (total) options:

$ du -shc  /usr/* 107M     /usr/X11R6 156M     /usr/bin  61M     /usr/include du:  /usr/lib/jabber: Permission denied  88M     /usr/lib  76M     /usr/libexec 280K     /usr/local du:  /usr/sbin/authserver: Permission denied  39M     /usr/sbin 283M     /usr/share 344K     /usr/standalone 812M     total


The final example displays, in human-readable format, the total size of all files the user can read in the /usr filesystem. Redirecting standard error to /dev/null (page 444) discards all warnings about files and directories that are unreadable.

$ du -h -s /usr 2>/dev/null 812M     /usr


echo: Displays a message

echo [options] message

The echo utility copies its arguments, followed by a NEWLINE, to standard output. The Bourne Again Shell and TC Shell each has an echo builtin that works similarly to the echo utility.

Arguments

The message consists of one or more arguments, which can include quoted strings, ambiguous file references, and shell variables. A SPACE separates each argument from the next. The shell recognizes unquoted special characters in the arguments. For example, the shell expands an asterisk into a list of filenames in the working directory.

Options

You can configure the tcsh echo builtin to treat backslash escape sequences and the n option in different ways. Refer to echo_style in the tcsh man page. The typical tcsh configuration recognizes the n option.

n

(newline) Suppresses the NEWLINE terminating the message.

e

(escape) Uses escape notation. Available only with the bash echo builtin.


Notes

You can use echo to send messages to the screen from a shell script. See page 134 for a discussion of how to use echo to display filenames using wildcard characters.

The echo builtins in tcsh and bash provide an escape notation to represent certain nonprinting characters in message (Table VI-13). You must use the e option for backslash escape sequences to work with the bash echo builtin. Typically you do not need the e option with the tcsh echo builtin. The echo utility recognizes only \c.

Table VI-13. Backslash escape sequences

Sequence

Meaning

\a

Bell

\c

Suppress trailing NEWLINE

\n

NEWLINE

\t

HORIZONTAL TAB

\v

VERTICAL TAB

\\

BACKSLASH


Examples

The following examples contain messages with the backslash escape sequence \c. In the first example, the shell processes the arguments before calling echo. When the shell sees the \c, it replaces the \c with the character c. The next three examples show how to quote the \c so that the shell passes it to echo, which then does not append a NEWLINE to the end of the message. These examples run under bash and require the e option.

$ echo -e There is a newline after this.\c There is a newline after this.c $ echo -e 'There is no newline after this.\c' There is no newline after this.$ $ echo -e "There is no newline after this.\c" There is no newline after this.$ $ echo -e There is no newline after this.\\c There is no newline after this.$


Under bash you can use the n option in place of e and the trailing \c.

The final example runs under tcsh, which typically uses n to suppress a trailing NEWLINE:

$ tcsh tcsh $ echo -n There is no newline after this. There is no newline after this.$


expr: Evaluates an expression

expr expression

The expr utility evaluates an expression and sends the result to standard output. It evaluates character strings that represent either numeric or nonnumeric values. Operators are used with the strings to form expressions.

Arguments

The expression is composed of strings interspersed with operators. Each string and operator constitute a distinct argument that you must separate from other arguments with a SPACE. You must quote operators that have special meanings to the shell (such as the multiplication operator, *).

The following list of expr operators is given in order of decreasing precedence. Each operator within a group of operators has the same precedence. You can change the order of evaluation by using parentheses.

:

(comparison) Compares two strings, starting with the first character in each string and ending with the last character in the second string. The second string is a regular expression with an implied caret (^) as its first character. If there is a match, expr displays the number of characters in the second string. If there is no match, expr displays a zero.

*

(multiplication)

/

(division)

%

(remainder)

 

Work only on strings that contain the numerals 0 through 9 and optionally a leading minus sign. Convert strings to integer numbers, perform the specified arithmetic operation on numbers, and convert the result back to a string before sending it to standard output.

+

(addition)

-

(subtraction)

 

Function in the same manner as the preceding group of operators.

<

(less than)

<=

(less than or equal to)

= or ==

(equal to)

!=

(not equal to)

>=

(greater than or equal to)

>

(greater than)

 

Relational operators work on both numeric and nonnumeric arguments. If one or both of the arguments are nonnumeric, the comparison is nonnumeric and relies on the machine collating sequence (typically ASCII). If both arguments are numeric, the comparison is numeric. The expr utility displays 1 (one) if the comparison is true and 0 (zero) if it is false.

&

(AND) Evaluates both of its arguments. If neither is zero or a null string, expr displays the value of the first argument. Otherwise, it displays 0 (zero). You must quote this operator.

|

(OR) Evaluates the first argument. If it is neither zero nor a null string, expr displays the value of the first argument. Otherwise, it displays the value of the second argument. You must quote this operator.


Notes

The expr utility returns an exit status of 0 (zero) if the expression evaluates to other than a null string or the number 0, a status of 1 if the expression is null or 0, and a status of 2 if the expression is invalid.

Although expr and this discussion distinguish between numeric and nonnumeric arguments, all arguments to expr are nonnumeric (character strings). When applicable, expr attempts to convert an argument to a number (for example, when using the + operator). If a string contains characters other than 0 through 9 with an optional leading minus sign, expr cannot convert it. Specifically, if a string contains a plus sign or a decimal point, expr considers it to be nonnumeric. If both arguments are numeric, the comparison is numeric. If one is nonnumeric, the comparison is lexicographic.

Examples

The following examples show command lines that call expr to evaluate constants. You can also use expr to evaluate variables in a shell script. The fourth command displays an error message because of the illegal decimal point in 5.3.

$ expr 17 + 40 57 $ expr 10 - 24 -14 $ expr -17 + 20 3 $ expr 5.3 + 4 expr: non-numeric argument


The multiplication (*), division (/), and remainder (%) operators provide additional arithmetic power. You must quote the multiplication operator (precede it with a backslash) so that the shell will not treat it as a special character (an ambiguous file reference). You cannot put quotation marks around the entire expression because each string and operator must be a separate argument.

$ expr 5 \* 4 20 $ expr 21 / 7 3 $ expr 23 % 7 2


The next two examples show how parentheses change the order of evaluation. You must quote each parenthesis and surround the backslash/parenthesis combination with SPACEs:

$ expr 2 \* 3 + 4 10 $ expr 2 \* \( 3 + 4 \) 14


You can use relational operators to determine the relationship between numeric or nonnumeric arguments. The following commands compare two strings to see if they are equal; expr displays 0 when the relationship is false and 1 when it is true:

$ expr fred == sam 0 $ expr sam == sam 1


In the following examples, the relational operators, which must be quoted, establish an order between numeric or nonnumeric arguments. If a relationship is true, expr displays a 1.

$ expr fred \> sam 0 $ expr fred \< sam 1 $ expr 5 \< 7 1


The next command compares 5 with m. When one of the arguments that expr is comparing with a relational operator is nonnumeric, expr considers the other to be nonnumeric. In this case, because m is nonnumeric, expr TReats 5 as a nonnumeric argument. The comparison is between the ASCII (on many systems) values of m and 5. The ASCII value of m is 109 and that of 5 is 53, so expr evaluates the relationship as true.

$ expr 5 \< m 1


The next example shows the matching operator determining that the four characters in the second string match the first four characters in the first string. The expr utility displays the number of matching characters (4).

$ expr abcdefghijkl : abcd 4


The & operator displays 0 if one or both of its arguments are 0 or a null string; otherwise, it displays the first argument:

$ expr '' \& book 0 $ expr magazine \& book magazine $ expr 5 \& 0 0 $ expr 5 \& 6 5


The | operator displays the first argument if it is not 0 or a null string; otherwise, it displays the second argument:

$ expr '' \| book book $ expr magazine \| book magazine $ expr 5 \| 0 5 $ expr 0 \| 5 5 $ expr 5 \| 6 5


file: Displays the classification of a file

file [option] file-list

The file utility classifies files according to their contents.

Arguments

The file-list specifies the pathnames of one or more files that file classifies. You can specify any kind of file, including ordinary, directory, and special files, in the file-list.

Options

files-from file

f

file

  

Takes the names of files to be examined from file rather than from file-list on the command line. The names of the files must be listed one per line in file.

mime

i

Displays MIME (page 943) type strings.

help

 

Displays a help message.

dereference

L

Reports on the files that symbolic links point to, not on the symbolic links themselves. The default is to report on symbolic links (not to dereference files).

uncompress

z

(zip) Attempts to classify files found within a compressed file.


Notes

The file utility can classify more than 5,000 file types. Some of the more common file types found on Mac OS X systems, as displayed by file, are listed here:

archive ascii text c program text commands text core file cpio archive data directory Mach-O executable ppc empty English text executable


The file utility uses a maximum of three tests in its attempt to classify a file: filesystem, magic number, and language tests. When file identifies the type of a file, it ceases testing. The filesystem test examines the return from a stat system call to see whether the file is empty or a special file. The magic number (page 941) test looks for data in particular fixed formats near the beginning of the file. The language test, if needed, determines whether the file is a text file, what kind of encoding it uses, and what language it is written in. Refer to the file man page for a more detailed description of how file works. The results of file are not always correct.

The file utility does not examine Mac file type and creator codes (page 95).

Examples

Some examples of file identification follow:

tabs:             Mach-O executable ppc tabs.c:           ASCII C program text bin:              directory dscn0436.jpg:     JPEG image data, EXIF standard 2.1 0-6.cwk:          data crop0151.tiff:    TIFF image data, big-endian dohlynx.png:      PNG image data, 639 x 431, 8-bit grayscale, non-interlaced


find: Finds files based on criteria

find [options] [directory-list] [expression]

The find utility selects files that are located in specified directory hierarchies and that meet specified criteria.

Arguments

The directory-list specifies which directories find will search. When find searches a directory, it searches all subdirectories to all levels.

The expression contains criteria, as described in the "Criteria" section. The find utility tests each of the files in each of the directories in the directory-list to see whether it meets the criteria described by the expression. When you do not specify an expression, the expression defaults to print.

A SPACE separating two criteria is a Boolean AND operator: The file must meet both criteria to be selected. A or or o separating the criteria is a Boolean OR operator: The file must meet one or the other (or both) of the criteria to be selected.

You can negate any criterion by preceding it with an exclamation point. The find utility evaluates criteria from left to right unless you group them using parentheses.

Within the expression you must quote special characters so that the shell does not interpret them but rather passes them to find. Special characters that you may frequently use with find include exclamation points, parentheses, brackets, question marks, and asterisks.

Each element within the expression is a separate argument. You must separate arguments from each other with SPACEs. A SPACE must appear on both sides of each parenthesis, exclamation point, criterion, or other element.

Options

d

(depth) Takes action on entries in a directory before it acts on the directory itself. When you use find to send filenames to cpio or pax, this option enables cpio or pax to preserve the modification times of directories when you restore files (assuming that you use the m option to cpio; pax preserves modification times by default). See the "Discussion" (page 695) and "Examples" (page 696) sections under cpio.

H

(dereference) Selects the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not select the files that symbolic links found while descending a directory hierarchy point to.

L

(dereference) Selects the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to.

s

(sort) Traverses directories in lexicographical (dictionary) order.

x

(xdev) Prevents find from searching directories in filesystems other than the filesystem(s) that hold the directories it was explicitly told to search.

x

Searches only directories in filesystems that hold the directories specified in directory-list.


Criteria

You can use the following criteria within the expression. In this list, ±n is a decimal integer that can be expressed as +n (more than n), n (fewer than n), or n (exactly n).

anewer filename

(accessed newer) The file being evaluated meets this criterion if it was accessed more recently than filename.

atime ±n

(access time) The file being evaluated meets this criterion if it was last accessed ±n days ago. When you use this option, find changes the access times of directories it searches.

exec command \;

The file being evaluated meets this action criterion if the command returns an exit status of 0 (zero [true]). You must terminate the command with a quoted semicolon. A pair of braces ({}) within the command represents the name of the file being evaluated. You can use the exec action criterion at the end of a group of other criteria to execute the command if the preceding criteria are met. Refer to "Discussion" for more information. See the "Examples" under xargs on page 893 for a more efficient way of doing what this option does.

group name

The file being evaluated meets this criterion if it is associated with the group named name. You can use a numeric group ID in place of name.

inum n

The file being evaluated meets this criterion if its inode number is n.

links ±n

The file being evaluated meets this criterion if it has ±n links.

mtime ±n

(modify time) The file being evaluated meets this criterion if it was last modified ±n days ago.

name filename

The file being evaluated meets this criterion if the pattern filename matches its name. The filename can include wildcard characters (*, ?, and []) but these characters must be quoted.

newer filename

The file being evaluated meets this criterion if it was modified more recently than filename.

nogroup

The file being evaluated meets this criterion if it does not belong to a group in the system group database.

nouser

The file being evaluated meets this criterion if it does not belong to a user in the passwd database.

ok command \;

This action criterion is the same as exec with two exceptions: It displays each command to be executed enclosed in angle brackets, and it executes the command only if it receives a response that starts with a y or Y from standard input.

perm [±]mode

The file being evaluated meets this criterion if it has the access permissions given by mode. If mode is preceded by a minus sign (-), the file access permissions must include all the bits in mode. If mode is preceded by a plus sign (+), the file access permissions must include at least one of the bits in mode. If no plus or minus sign precedes mode, the mode of the file must exactly match mode. You may use either a symbolic or an octal representation for mode (see chmod on page 676).

print

The file being evaluated always meets this action criterion. When evaluation of the expression reaches this criterion, find displays the pathname of the file it is evaluating. If print is the only criterion in the expression, find displays the names of all files in the directory-list. If this criterion appears with other criteria, find displays the name only if the preceding criteria are met. If no action criteria appear in the expression, print is assumed. (Refer to the following "Discussion" and "Notes" sections.)

print0

Similar to print, but follows the pathname with a null character instead of a NEWLINE. Useful with xargs (see the example on page 894).

size ±n[c|k]

The file being evaluated meets this criterion if it is the size specified by ±n, as measured in 512-byte blocks. Follow n with the letter c to measure the size of files in characters.

type filetype

The file being evaluated meets this criterion if its file type is specified by filetype. Select a filetype from the following list:

b Block special file

c Character special file

d Directory file

f Ordinary file

l Symbolic link

p FIFO (named pipe)

s Socket

user name

The file being evaluated meets this criterion if it belongs to the user with the username name. You can use a numeric user ID in place of name.

Discussion

Assume that x and y are criteria. The following command line never tests whether the file meets criterion y if it does not meet criterion x. Because the criteria are separated by a SPACE (the Boolean AND operator), once find determines that criterion x is not met, the file cannot meet the criteria so find does not continue testing. You can read the expression as "(test whether) the file meets criterion x and (SPACE means and) criterion y."

$ find dir x y


The next command line tests the file against criterion y if criterion x is not met. The file can still meet the criteria so find continues the evaluation. You can read the expression as "(test whether) the file meets criterion x or criterion y." If the file meets criterion x, find does not evaluate criterion y as there is no need to do so.

$ find dir x -or y


Action criteria

Certain "criteria" do not select files but rather cause find to take action. The action is triggered when find evaluates one of these action criteria. Therefore the position of an action criterion on the command linenot the result of its evaluationdetermines whether find takes the action.

The print action criterion causes find to display the pathname of the file it is testing. The following command line displays the names of all files in the dir directory (and all its subdirectories), regardless of whether they meet the criterion x:

$ find dir -print x


The following command line displays only the names of the files in the dir directory that meet criterion x:

$ find dir x -print


This common use of print after the testing criteria is the default action criterion. The following command line generates the same output as the previous one:

$ find dir x


Notes

You can use the a operator between criteria to improve readability. This operator is a Boolean AND operator, just as the SPACE is.

In earlier versions of find, the d, H, and x options were implemented as action criteria named depth, follow, and xdev, respectively.

Examples

The simplest find command has only a directory as an argument and lists the files in the specified directory and all subdirectories. The first example lists the contents of the working directory hierarchy; it uses a period to designate the working directory:

$ find . ...


The following command finds the files in the working directory and subdirectories that have filenames beginning with a. To prevent the shell from interpreting a* as an ambiguous file reference, it is enclosed within quotation marks.

$ find . -name 'a*'


The print criterion is implicit in the preceding commands.

The next command sends a list of selected filenames to the pax utility, which writes them to an archive file. (Under Mac OS X 10.3 and earlier, the pax utility did not preserve extended attributes, so this approach is not a suitable way to back up all types of files.) The first part of the command line ends with a pipe symbol, so the shell expects another command to follow and displays a secondary prompt (>) before accepting the rest of the command line. You can read this find command as "find, in the root directory and all subdirectories (/), ordinary files (type f) that have been modified within the past day (mtime 1), with the exception of files whose names are suffixed with .o (! name '* .o')." (An object file carries a .o suffix and usually does not need to be preserved because it can be re-created from the corresponding source file.)

$ find / -type f -mtime -1 ! -name '*.o' -print | > pax -w > /Volumes/Backups/recent.pax


The following command finds, displays the filenames of, and deletes the files in the working directory and subdirectories named *.bak or junk:

$ find . \( -name "*.bak" -o -name junk \) -print -exec rm {} \; ...


The parentheses and the semicolon following exec are quoted so that the shell does not treat them as special characters. SPACEs separate the quoted parentheses from other elements on the command line. Read this find command as "find, in the working directory and subdirectories (.), files named *.bak (name "*.bak") or (o) junk (name junk) [if a file meets these criteria, continue] and (SPACE) print the name of the file (print) and (SPACE) delete the file (exec rm {})."

The next shell script uses find in conjunction with grep to identify files that contain a particular string. This script enables you to look for a file when you remember its contents but cannot recall its filename. The findit script locates files in the working directory and subdirectories that contain the string specified on the command line. The type f criterion is necessary so that find will pass to grep only the names of ordinary files, not directory files.

$ cat findit find . -type f -exec grep -l "$1" {} \; $ findit "Executive Meeting"  ./january/memo.0102  ./april/memo.0415


When called with the string Executive Meeting, findit locates two files containing that string: ./january/memo.0102 and ./april/memo.0415. The period (.) in the pathnames represents the working directory; january and april are subdirectories of the working directory. The grep utility with the recursive option performs the same function as the findit script.

The next command looks in two directories for files that are larger than 100 blocks (size +100) and have been accessed more than five days agothat is, the files have not been accessed within the past five days (atime +5). This find command then asks whether you want to delete the file (ok rm {}). You must respond to each query with y (yes) or n (no). The rm command works only if you have write and execute access permission to the directory.

$ find /Users/alex /Users/barbara -size +100 -atime +5 -ok rm {} \; < rm ... /Users/alex/notes >? y < rm ... /Users/alex/letter >? n ...


In the next example, /Users/alex/memos is a symbolic link to Jenny's directory named /Users/jenny/memos. When you use the H option, find follows the symbolic link and searches the contents of that directory.

$ ls -l /Users/alex lrwxr-xr-x  1 alex  alex  17 Aug 19 17:07 memos -> /Users/jenny/memos -rw-r--r--  1 alex  alex 5119 Aug 19 17:08 report $ find /Users/alex -print /Users/alex /Users/alex/memos /Users/alex/report /Users/alex/.profile $ find -H /Users/alex -print /Users/alex /Users/alex/memos /Users/alex/memos/memo.817 /Users/alex/memos/memo.710 /Users/alex/report /Users/alex/.profile


finger: Displays information about users

finger [options] [user-list]

The finger utility displays the usernames of users, together with their full names, terminal device numbers, times they logged in, and other information. It can retrieve information from both local and remote systems.

Arguments

Without any arguments, finger provides a short (s) report on users who are logged in on the local system. When you specify a user-list, which is a list of usernames that is not case sensitive, finger provides a long (l) report on each user in the user-list.

If a name starts with an at sign (@), finger interprets the name following the @ as the name of a remote host and reports on the users on that system. If a username precedes the @ sign, finger provides information on that user on the remote system.

Options

The options control how much information finger displays.

l

(long) Displays detailed information (the default when you specify a user-list).

m

(match) If a user-list is specified, displays entries only for those users whose username matches one of the names in user-list. Without this option, the user-list names match usernames and full names.

p

(no plan or project) Does not display the contents of .plan or .project files for users. Because these files may contain backslash escape sequences that can change the behavior of the screen, you may not wish to view them. Normally the long listing displays the contents of these files if they exist in the user's home directory.

s

(short) Provides a short report for each user (the default when you do not specify a user-list).


Discussion

The long report includes the user's username, full name, home directory location, and login shell, plus information about when the user last logged in and how long it has been since the user last typed on the keyboard and read her email. After displaying this information, finger displays the contents of the ~/.plan and ~/.project files in the user's home directory. It is up to each user to create and maintain these files, which usually provide more information about the user (such as telephone number, postal mail address, schedule, and interests).

The short report generated by finger is similar to that provided by the w utility. It includes the user's username, his full name, the device number of the user's terminal, the amount of time that has elapsed since the user last typed on the terminal keyboard, the time the user logged in, and, if the user logged in over the network, the name of the remote system.

Notes

When you specify a network address, the finger utility queries a standard network service that runs on the remote system. Although this service is supplied with Mac OS X systems, it is disabled by default. Some administrators choose not to enable it so as to minimize the load on their systems, to eliminate possible security risks, or simply to maintain privacy. If you try to use finger to get information on someone at such a site, the result may be an error message or nothing at all. The remote system determines how much information to share with the local system and in what format. As a result the report displayed for any given system may differ from the examples shown here. See also "finger: Lists Users on the System" on page 61.

.nofinger

A file named ~/.nofinger causes finger to deny the existence of the person whose home directory it appears in. For this subterfuge to work, the fingerd daemon or the finger utility must be able to see the .nofinger file (generally the home directory must have its execute bit for other users set).

Examples

The first example displays information on the users logged in on the local system:

$ finger Login    Name                    TTY   Idle  Login Time   Office     Phone alex     Alex Watson            *con    1d    Jun 25 21:03 hls      Helen Simpson          *p1    13:29  Jun 25 21:02) jenny    Jenny Chen              p2           Jun 26 07:47


The asterisks (*) in front of the names of Helen and Alex's terminal (TTY) lines indicate that they have blocked others from sending messages directly to their screens (see mesg on page 64). A long report displays the string messages off for users who have disabled messages.

The next two examples cause finger to contact the remote system named kudos over the network for information:

$ finger @kudos [kudos] Login    Name           TTY    Idle   Login  Time     Office     Phone alex     Alex Watson    tty1   23:15  Jun 25 11:22 roy      Roy Wong       pts/2         Jun 25 11:22 $ finger watson@kudos [kudos] Login: alex                             Name: Alex Watson Directory: /Users/alex                   Shell: /bin/zsh On since Sat Jun 25 11:22 (PDT) on tty1,  idle 23:22 Last login Sun Jun 26 06:20 (PDT) on ttyp2 from speedy Mail last read Thu Jun 23 08:10 2005 (PDT) Plan: For appointments contact Jenny Chen, x1963.


fmt: Formats text very simply

fmt [option] [file-list]

The fmt utility does simple text formatting, attempting to make all nonblank lines nearly the same length.

Arguments

The fmt utility reads the files in file-list and sends a formatted version of their contents to standard output. If you do not specify a filename or if you specify a filename of , fmt reads from standard input.

Options

c

(center) Centers each line. This option suppresses line splitting and joining.

n

(nroff) Formats lines beginning with a period (.). The default is to leave these lines alone, for compatibility with the nroff text formatter.

s

(spaces) Replaces multiple whitespace characters with a single SPACE.

w

n

 

(width) Changes the output line length to n characters. Without this option, fmt keeps output lines close to 75 characters long. You can also specify this option as n.


Notes

The fmt utility works by moving NEWLINE characters. The indention of lines, as well as the spacing between words, is left intact.

This utility is often used to format text while you are using an editor, such as vim. For example, you can format a paragraph with the vim editor in Command mode by positioning the cursor at the beginning of the paragraph and giving the command !}fmt60. This command replaces the paragraph with the output generated by feeding it through fmt, specifying a line length of 60 characters. Type u immediately if you want to undo the formatting.

Examples

The following example shows how fmt attempts to make all lines the same length. The w 50 option gives a target line length of 50 characters.

$ cat memo One factor that is important to remember while administering the dietary intake of Charcharodon carcharias is that there is, at least from the point of view of the subject, very little differentiating the prepared morsels being proffered from your digits. In other words, don't feed the sharks! $ fmt -w 50 memo One factor that is important to remember while administering the dietary intake of Charcharodon carcharias is that there is, at least from the point of view of the subject, very little differentiating the prepared morsels being proffered from your digits. In other words, don't feed the sharks!


ftp: transfers files over a network

ftp [options] [remote-system]

The ftp utility is a user interface to the standard File Transfer Protocol (FTP), which transfers files between systems that can communicate over a network. To establish an FTP connection, you must have an account (personal, guest, or anonymous) on the remote system.

Security: Use FTP only to download public information

FTP is not a secure protocol. The ftp utility sends your password over the network as cleartext, which is not a secure practice. You can use scp (page 832) for many FTP functions other than allowing anonymous users to download information. Because scp uses an encrypted connection, user passwords and data cannot be sniffed easily.


Arguments

The remote-system is typically the name or network address of the server that is running an ftpd daemon and that you want to exchange files with. In this case ftp connects to the server. If remote-system is a URL (including the protocol such as http:// or ftp://), ftp downloads the file(s) specified by the URL. Without any arguments, ftp runs interactively.

Options

i

(interactive) Turns off prompts during file transfers with mget and mput. See also prompt.

n

(no automatic login) Disables automatic logins.

v

(verbose) Tells you more about how ftp is working. Displays responses from the remote-system and reports transfer times and speeds.


Discussion

When called with an argument that is a URL, ftp attempts to fetch the named file automatically. If the URL uses the FTP protocol and specifies a directory, ftp connects to the server, cds to that directory, and displays a prompt.

When called with an argument that is the name or network address of a server, or when called without an argument, ftp is interactive. After you start it, ftp prompts you to enter commands to set parameters and transfer files. You can use a number of commands in response to the ftp> prompt; following are some of the more common ones.

![command]

Escapes to (spawns) a shell on the local system (use CONTROL-D or exit to return to ftp when you are finished using the local shell). Follow the exclamation point with a command to execute that command only; ftp returns you to the ftp> prompt when the command completes executing. Because the shell that ftp spawns with this command is a child of the shell that is running ftp, changes you make in this shell are not preserved when you return to ftp. Specifically, when you want to copy files to a local directory other than the directory that you started ftp from, you need to use the ftp lcd command to change the local working directory: Issuing a cd command in the spawned shell will not make the desired change. See "lcd (local cd)" on page 743 for an example.

ascii

Sets the file transfer type to ASCII. Allows you to transfer text files from systems that end lines with a RETURN/LINEFEED combination and automatically strip off the RETURN. This type of transfer is useful when the remote computer is a DOS or Windows machine. The cr command must be on for ascii to work.

binary

Sets the file transfer type to binary (default). Allows you to transfer files that contain non-ASCII (unprintable) characters correctly. This option also works for ASCII files that do not require changes to the ends of lines.

bye

Closes the connection to a remote system and terminates ftp. Same as quit.

cd remote-directory

 

Changes to the working directory named remote-directory on the remote system.

close

Closes the connection with the remote system without exiting from ftp.

cr

Toggles RETURN stripping when you retrieve files in ASCII mode. See ascii.

dir [directory [file]]

 

Displays a listing of the directory named directory from the remote system. When you do not specify directory, the working directory is displayed. When you specify file, the listing is saved on the local system in a file named file.

get remote-file [local-file]

 

Copies remote-file to the local system under the name local-file. Without local-file, ftp uses remote-file as the filename on the local system. The remote-file and local-file names can be pathnames.

glob

Toggles filename expansion for mget and mput commands and displays the current state (Globbing on or Globbing off).

help

Displays a list of commands recognized by the ftp utility on the local system.

lcd [local_directory]

 

(local change directory) Changes the working directory on the local system to local_directory. Without an argument, changes the working directory on the local system to your home directory (just as cd does without an argument).

ls [directory [file]]

Similar to dir but produces a more concise listing on some remote systems. When you specify file, the listing is saved on the local system in a file named file.

mget remote-file-list

 

(multiple get) Unlike the get command, the mget command can retrieve multiple files from the remote system. You can name the remote files literally or use wildcards (see glob). See also prompt.

mput local-file-list

 

(multiple put) The mput command can copy multiple files from the local system to the remote system. You can name the local files literally or use wildcards (see glob). See also prompt.

open

Interactively specifies the name of the remote system. This command is useful if you did not specify a remote system on the command line or if the attempt to connect to the system failed.

passive

Toggles between active (PORTthe default) and passive (PASV) transfer modes and displays the transfer mode. See "Passive versus active connections" under "Notes."

prompt

When using mget or mput to receive or send multiple files, ftp asks for verification (by default) before transferring each file. This command toggles that behavior and displays the current state (Interactive mode off or Interactive mode on).

put local-file [remote-file]

 

Copies local-file to the remote system under the name remote-file. Without remote-file, ftp uses local-file as the filename on the remote system. The remote-file and local-file names can be pathnames.

pwd

Causes ftp to display the pathname of the remote working directory. Use !pwd to display the name of the local working directory.

reget remote-file

Attempts to resume an aborted transfer. Similar to get, but instead of overwriting an existing local file, ftp appends new data to it. Not all servers support reget.

quit

Quits the ftp session. Same as bye.

user [username]

If the ftp utility did not log you in automatically, you can specify your account name as username. Without username, ftp prompts you for your username.


Notes

A system running ftp can exchange files with any of the many operating systems that support the FTP protocol. Numerous sites offer archives of free information on an FTP server, although many of them are merely alternatives to easier-to-access Web sites (for example, ftp://ftp.ibiblio.org/pub and http://www.ibiblio.org/pub). Most browsers can connect to and download files from FTP servers.

The ftp utility makes no assumptions about filesystem naming or structure because you can use ftp to exchange files with non-UNIX systems (whose filename conventions may be different).

Anonymous FTP

Many systemsmost notably those from which you can download free softwareallow you to log in as anonymous. Most systems that support anonymous logins accept the name ftp as an easier-to-spell and quicker-to-enter synonym for anonymous. An anonymous user is usually restricted to a portion of a filesystem set aside to hold files that are to be shared with remote users. When you log in as an anonymous user, the server prompts you to enter a password. Although any password may be accepted, by convention you are expected to supply your email address. Many systems that permit anonymous access store interesting files in the pub directory.

Passive versus active connections

A client can ask an FTP server to establish either a PASV (passivethe default) or a PORT (active) connection for data transfer. Some servers are limited to one type of connection. The difference between a passive and an active FTP connection lies in whether the client or the server initiates the data connection. In passive mode, the client initiates the data connection to the server (on port 20 by default); in active mode, the server initiates the data connection (there is no default port). Neither type of connection is inherently more secure than the other. Passive connections are more common because a client behind a NAT (page 944) firewall can connect to a passive server and because it is simpler to program a scalable passive server.

Automatic login

You can store server-specific FTP username and password information so that you do not have to enter it each time you visit an FTP site. Each line of the ~/.netrc file identifies a server. When you connect to an FTP server, ftp reads ~/.netrc to determine whether you have an automatic login set up for that server. The format of a line in .netrc is

machine server login username password passwd


where server is the name of the server, username is your username, and passwd is your password on server. Replace machine with default on the last line of the file to specify a username and password for systems not listed in ~/.netrc. The default line is useful for logging in on anonymous servers. A sample ~/.netrc file follows:

$ cat ~/.netrc machine bravo login alex password mypassword default login anonymous password alex@example.com


Protect the account information in .netrc by making it readable by only the user whose home directory it appears in. Refer to the netrc man page for more information.

Examples

Following are two ftp sessions wherein Alex transfers files from and to an FTP server named bravo. When Alex gives the command ftp bravo, the local ftp client connects to the server, which asks for a username and password. Because he is logged in on his local system as alex, ftp suggests that he log in on bravo as alex. To log in as alex, Alex could just press RETURN. His username on bravo is watson, however, so he types watson in response to the Name (bravo:alex): prompt. Alex responds to the Password: prompt with his normal system password, and the FTP server greets him and informs him that it is Using binary mode to transfer files. With ftp in binary mode, Alex can transfer ASCII and binary files.

Connect and log in

$ ftp bravo Connected to bravo. 220 bravo.example.com FTP server (NetBSD-ftpd 20040809) ready. Name (bravo:alex): watson 331 Password required for watson. Password: 230-     NetBSD 2.0.2 (BRAVO) #0: Sun Feb 20 06:11:02 CST 2005     Welcome to NetBSD! 230 User watson logged in. Remote system type is UNIX. Using binary mode to transfer files. ftp>


After logging in, Alex uses the ftp ls command to display the contents of his remote working directory, which is his home directory on bravo. Then he cds to the memos directory and displays the files there.

ls and cd

ftp> ls 229 Entering Extended Passive Mode (|||63979|) 150 Opening ASCII mode data connection for '/bin/ls'. total 6 drwxr-xr-x    2 500      500          512 Oct 10 23:52 expenses drwxr-xr-x    2 500      500          512 Oct 10 23:59 memos drwxrwxr-x   22 500      500          512 Oct 10 23:32 tech 226 Transfer complete. ftp> cd memos 250 Directory successfully changed. ftp> ls 229 Entering Extended Passive Mode (|||63979|) 150 Opening ASCII mode data connection for '/bin/ls'. total 56 -rw-r--r--    1 500      500          4770 Oct 10 23:58 memo.0514 -rw-r--r--    1 500      500          7134 Oct 10 23:58 memo.0628 -rw-r--r--    1 500      500          9453 Oct 10 23:58 memo.0905 -rw-r--r--    1 500      500          3466 Oct 10 23:59 memo.0921 -rw-r--r--    1 500      500          1945 Oct 10 23:59 memo.1102 226 Transfer complete.


Next Alex uses the ftp get command to copy memo.1102 from the server to the local system. Binary mode ensures that he will get a good copy of the file regardless of whether it is binary or ASCII. The server confirms that the file was copied successfully and notes the size of the file and the time it took to copy. Alex then copies the local file memo.1114 to the remote system. The file is copied into his remote working directory, memos.

get and put

ftp> get memo.1102 local: memo.1102 remote: memo.1102 229 Entering Extended Passive Mode (|||64083|) 150 Opening BINARY mode data connection for 'memo.1102' (77 bytes). 100% |*************************************|    77    335.69 KB/s 00:00 226 Transfer complete. 77 bytes received in 00:00 (0.41 KB/s) ftp> put memo.1114 local: memo.1114 remote: memo.1114 229 Entering Extended Passive Mode (|||64082|) 150 Opening BINARY mode data connection for 'motd'. 100% |*************************************|   974   458.50 KB/s  00:00 226 Transfer complete. 974 bytes sent in 00:00 (1.73 KB/s)


After a while Alex decides he wants to copy all the files in the memo directory on bravo to a new directory on his local system. He gives an ls command to make sure he is going to copy the right files, but ftp has timed out. Instead of exiting from ftp and giving another ftp command from the shell, Alex gives an open bravo command to reconnect to the server. After logging in, he uses the ftp cd command to change directories to memos on the server.

Timeout and open

ftp> ls 421 Timeout (900 seconds): closing control connection. ftp> open bravo Connected to bravo ... ftp> cd memos 250 Directory successfully changed.


Icd (local cd)

At this point, Alex realizes he has not created the new directory to hold the files he wants to download. Giving an ftp mkdir command would create a new directory on the server, but Alex wants a new directory on the local system. He uses an exclamation point (!) followed by a mkdir memos.hold command to invoke a shell and run mkdir on the local system, creating a directory named memos.hold in his working directory on the local system. (You can display the name of the working directory on the local system with the command !pwd.) Next because he wants to copy files from the server to the memos.hold directory on his local system, Alex has to change his working directory on the local system. Giving the command !cd memos.hold will not accomplish what Alex wants to do because the exclamation point spawns a new shell on the local system and the cd command would be effective only in the new shell, which is not the shell that ftp is running under. For this situation, ftp provides the lcd (local cd) command, which changes the working directory for ftp and reports on the new local working directory.

ftp> !mkdir memos.hold ftp> lcd memos.hold Local directory now /Users/alex/memos.hold


Alex uses the ftp mget (multiple get) command followed by the asterisk (*) wildcard to copy all the files in the remote memos directory to the memos.hold directory on the local system. When ftp prompts him for the first file, he realizes that he forgot to turn off prompts, so he responds with n and presses CONTROL-C to stop copying files in response to the second prompt. The server checks whether he wants to continue with his mget command.

Next Alex gives the ftp prompt command, which toggles the prompt action (turns it off if it is on and turns it on if it is off). Now when he gives an mget * command, ftp copies all the files without prompting him.

After getting the files he wants, Alex gives a quit command to close the connection with the server, exit from ftp, and return to the local shell prompt.

mget and prompt

ftp> mget * mget memo.0514 [anpqy]? n mget memo.0628 [anpqy]? CONTROL-C Continue with mget [anpqy]? n ftp> prompt Interactive mode off. ftp> mget * local: memo.0514 remote: memo.0514 229 Entering Extended Passive Mode (|||63989|) 150 Opening BINARY mode data connection for memo.0514 (4770 bytes). 100% |*************************************|   4770   97.65 KB/s   00:00 226 Transfer complete. 19 bytes received in 00:00 (0.09 KB/s) local: memo.0628 remote: memo.0628 227 Entering Passive Mode (192,168,0,6,65,102) 150 Opening BINARY mode data connection for memo.0628 (7134 bytes). 100% |*************************************|  7134  147.62 KB/s   00:00 226 Transfer complete. ... ftp> quit 221 Goodbye.


gcc: Compiles C, Objective-C, and C++ programs

gcc [options] file-list [larg]

g++ [options] file-list [larg]

Mac OS X uses the GNU C compiler, gcc, to preprocess, compile, assemble, and link C and Objective-C language source files. The same compiler with a different front end, g++, processes C++ source code. The gcc and g++ compilers can also assemble and link assembly language source files, link object files only, or build object files for use in shared libraries.

The input to these compilers comes from files you specify on the command line. Unless you use the o option, they store the executable program in a.out.

The gcc and g++ compilers are part of GCC, the GNU Compiler Collection, which includes front ends for C, C++, Objective-C, Fortran, Java, and Ada as well as libraries for these languages. Go to gcc.gnu.org for more information.

Tip: gcc and g++

Although this section specifies the gcc compiler, most of it applies to g++ as well.


Arguments

The file-list specifies the pathnames of one or more files that gcc is to process.

Options

Without any options, gcc accepts C language source files, assembly language files, object files, and other files described in Table VI-14 on page 747. The gcc utility preprocesses, compiles, assembles, and links these files as appropriate, producing an executable file named a.out. If gcc is used to create object files without linking them to produce an executable file, each object file is named by adding the extension .o to the basename of the corresponding source file. If gcc is used to create an executable file, it deletes the object files after linking.

Table VI-14. Filename extensions

Extension

Type of file

.a

Library of object modules

.c

C language source file

.C, .cc, or .cxx

C++ language source file

.i

Preprocessed C language source file

.ii

Preprocessed C++ language source file

.m

Objective-C language source file

.o

Object file

.s

Assembly language source file

.S

Assembly language source file that needs preprocessing


This section lists some of the most commonly used options. When certain filename extensions are associated with an option, you can assume that the extension is added to the basename of the source file.

c

(compile) Suppresses the linking step of compilation. Compiles and/or assembles source code files and leaves the object code in files with the extension .o.

Dname[=value]

 

Usually #define preprocessor directives are given in header, or include, files. You can use this option to define symbolic names on the command line instead. For example, DOSX is equivalent to having the line #define OSX in an include file, and DMACH=PPC is the same as #define MACH PPC.

E

(everything) For source code files, suppresses all steps of compilation except preprocessing and writes the result to standard output. By convention the extension .i is used for preprocessed C source code files and .ii for preprocessed C++ source code files.

fpic

 

Causes gcc to produce position-independent code, which is suitable for installation into a shared library.

fwritable-strings

 

By default the GNU C compiler places string constants into protected memory, where they cannot be changed. Some (usually older) programs assume that you can modify string constants. This option changes the behavior of gcc so that string constants can be modified.

g

(gdb) Embeds diagnostic information in the object files. This information is used by symbolic debuggers, such as gdb (page 501). Although it is necessary only if you later use a debugger, it is a good practice to include this option as a matter of course.

Idirectory

 

Looks for include files in directory before looking in the standard locations. Give this option multiple times to look in more than one directory.

larg

 

(lowercase "l") Searches the directory /usr/lib for a library file named libarg.a or libarg.dylib. If the file is found, gcc then searches this library for any required functions. Replace arg with the name of the library you want to search. For example, the lm option normally links the standard math library libm.dylib. The position of this option is significant: It generally needs to go at the end of the command line but can be repeated multiple times to search different libraries. Libraries are searched in the order in which they appear on the command line. The linker uses the library only to resolve undefined symbols from modules that precede the library option on the command line. You can add the paths of other library directories to search for libarg.a by using the L option.

Ldirectory

 

Adds directory to the list of directories to search for libraries given with the l option. Directories that are added to the list with L are searched before looking in the standard locations for libraries.

ofile

 

(output) Names the executable program that results from linking file instead of a.out.

On

 

(optimize) Attempts to improve (optimize) the object code produced by the compiler. The value of n may be 0, 1, 2, or 3; the default value is 1. Larger values of n result in better optimization but may increase both the size of the object file and the time it takes gcc to run. Using O0 turns off optimization. Many related options control precisely the types of optimizations attempted by gcc when you use O. Refer to the gcc info page for details.

pedantic

 

The C language accepted by the GNU C compiler includes features that are not part of the ANSI standard for the C language. Using this option forces gcc to reject these language extensions and accept only the standard C programming language features.

Q

Displays the names of functions as gcc compiles them. Also displays statistics about each pass.

S

(suppress) Suppresses the assembling and linking steps of compilation on source code files. The resulting assembly language files have .s filename extensions.

traditional

 

Causes gcc to accept only C programming language features that existed in the traditional Kernighan and Ritchie C programming language. This option allows you to compile correctly older programs written using the traditional C language that existed before the ANSI standard C language was defined.

Wall

 

Causes gcc to warn you about questionable code in the source code files. Many related options control warning messages more precisely. (See page 499.)


Notes

The preceding list of options represents only a fraction of the full set of options available with the GNU C compiler. See the gcc info page for a complete list.

See "Programming in C" on page 478 for more information about using the gcc compiler.

Although the o option is generally used to specify a filename in which to store object code, this option also allows you to name files resulting from other compilation steps. In the following example, the o option causes the assembly language produced by the gcc command to be stored in the file acode instead of pgm.s, the default:

$ gcc -S -o acode pgm.c


The lint utility found in many UNIX systems is not available under Mac OS X. However, the Wall option (page 499) performs many of the same checks and can be used in place of lint.

Table VI-14 summarizes the conventions used by the C compiler for assigning filename extensions.

Examples

The first example compiles, assembles, and links a single C program, compute.c. The executable output is put in a.out. The gcc utility deletes the object file.

$ gcc compute.c


The next example compiles the same program using the C optimizer (O option). It assembles and links the optimized code. The o option causes gcc to put the executable output in compute.

$ gcc -O -o compute compute.c


Next a C source file, an assembly language file, and an object file are compiled, assembled, and linked. The executable output goes in progo.

$ gcc -o progo procom.c profast.s proout.o


In the next example, gcc searches the standard math library stored in /lib/libm.a when it is linking the himath program and puts the executable output in a.out:

$ gcc himath.c -lm


In the following example, the C compiler compiles topo.c with options that check the code for questionable source code practices (Wall option) and violations of the ANSI C standard (pedantic option). The g option embeds debugging support in the executable file, which is saved in topo with the o topo option. Full optimization is enabled with the O3 option.

The warnings produced by the C compiler are sent to standard output. Here the first and last warnings result from the pedantic option; the other warnings result from the Wall option:

$ gcc -Wall -g -O3 -pedantic -o topo topo.c In file included from topo.c:2: /usr/include/ctype.h:65: warning: comma at end of enumerator list topo.c:13: warning: return-type defaults to 'int' topo.c: In function 'main': topo.c:14: warning: unused variable 'c' topo.c: In function 'getline': topo.c:44: warning: 'c' might be used uninitialized in this function


When compiling programs that use the X11 include files and libraries, you may need to use the I and L options to tell gcc where to find those include files and libraries. The next example uses those options and instructs gcc to link the program with the basic X11 library:

$ gcc -I/usr/X11R6/include plot.c -L/usr/X11R6/lib -lX11


GetFileInfo: Displays file attributes

GetFileInfo [option] file

The GetFileInfo utility displays file attributes (page 95), including the file's type and creator code, creation and last modification time, and attribute flags such as the invisible and locked flags.

Arguments

The file is a single file that GetFileInfo displays information about.

Options

The options for GetFileInfo correspond to the options for SetFile (page 834).

Without an option, GetFileInfo reports on the metadata of file, indicating which flags are set, the file's type and creator codes, and its creation and modification dates. Missing data is omitted. When you specify an option, GetFileInfo displays the information specified by that option only. This utility accepts a single option; it silently ignores any additional options that you provide.

aflag

 

(attribute) Reports the status of a single attribute flag named flag. Displays 1 if flag is set and 0 if flag is not set. The flag must follow the a immediately, without any intervening SPACEs. See Table 4-3 on page 96 for a list of attribute flags.

c

(creator) Displays the creator code of file. If file has no creator code, this option displays an error message.

d

(date) Displays the creation date of file as mm/dd/yyyy hh:mm:ss, using a 24-hour clock.

m

(modification) Displays the modification date of file as mm/dd/yyyy hh:mm:ss, using a 24-hour clock.

t

(type) Displays the type code of file. If file has no type code, this option displays an error message.


Discussion

Without an option, GetFileInfo displays flags as the string avbstclinmedz, with uppercase letters denoting which flags are set. See page 95 for a discussion of attribute flags.

Notes

The GetFileInfo utility is available in /Developer/Tools when the Developer Tools package (page 478) is installed.

You can use the SetFile utility (page 834) to set file attributes. You can set UNIX permissions and ownership (page 87) by using chmod (page 676) and chown (page 682), and can display this information by using ls (page 777) or stat (page 851).

Directories do not have type or creator codes, and they may not have all flags. The GetFileInfo utility cannot read special files such as device files.

Examples

The first example shows the output from GetFileInfo when you call it without an option. Because this utility is not in the default PATH (page 285), you must either change your PATH variable or call it with an absolute pathname, as shown following:

$ /Developer/Tools/GetFileInfo picture.jpg file: "/private/tmp/picture.jpg" type: "JPEG" creator: "GKON" attributes: avbstClinmedz created: 07/18/2005 15:15:26 modified: 07/18/2005 15:15:26


The only uppercase letter on the attributes line is C, indicating that this flag is set. The c flag tells the Finder to look for a custom icon for this file. See Table 4-3 on page 96 for a list of flags.

The next example uses the a flag to display the attribute flags for a file:

$ /Developer/Tools/GetFileInfo -a /Applications/Games/Alchemy/Alchemy avBstclInmedz


The output shows that the b and i flags are set.

The GetFileInfo utility can process only one file per invocation. The following multiline bash command uses a for loop (page 537) to display the creator codes of multiple files. The echo command displays the name of the file being examined because GetFileInfo does not always display the name of the file:

$ for i in * > do echo -n "$i: "; /Developer/Tools/GetFileInfo -c "$i" > done Desktop: Desktop is a directory and has no creator Documents: Documents is a directory and has no creator ... aa: "" ab: "" ...


grep: Searches for a pattern in files

grep [options] pattern [file-list]

The grep utility searches one or more files, line by line, for a pattern, which can be a simple string or another form of a regular expression. It takes various actions, as specified by its options, each time it finds a line that contains a match for the pattern. This utility takes its input from files you specify on the command line or from standard input.

Arguments

The pattern is a regular expression, as defined in Appendix A. You must quote regular expressions that contain special characters, SPACEs, or TABs. An easy way to quote these characters is to enclose the entire expression within single quotation marks.

The file-list specifies the pathnames of one or more ordinary files that grep searches. With the r option, file-list may contain directories whose contents are searched.

Options

Without any options, grep sends lines that contain a match for pattern to standard output. When you specify more than one file on the command line, grep precedes each line that it displays with the name of the file that it came from followed by a colon.

Major Options

You can use only one of the following three options at a time. Normally you do not need to use any, because grep defaults to G, which is regular grep.

E

(extended) Interprets pattern as an extended regular expression (page 905). The command grep E is the same as egrep. See "Notes" later in this section.

F

(fixed) Interprets pattern as a fixed string of characters. The command grep F is the same as fgrep.

G

(grep) Interprets pattern as a basic regular expression. It is the default major option if none is specified.


Other Options

Accepts the common options described on page 663.

count

c

Displays only the number of lines that contain a match in each file.

context=n

C

n

  

Displays n lines of context around each matching line.

file=file

f

file

  

Reads file, which contains one pattern per line, and finds lines in the input that match a pattern in file.

no-filename

h

(header) Does not display the filename at the beginning of each line when searching through multiple files.

ignore-case

i

Causes lowercase letters in the pattern to match uppercase letters in the file, and vice versa. Use this option when you are searching for a word that may be at the beginning of a sentence (that is, the word may or may not start with an uppercase letter).

files-with-matches

 
 

l

(list, lowercase "l") Displays only the name of each file that contains one or more matches. A filename is displayed just once, even if the file contains more than one match.

max-count=n

mn

  

Stops reading each file, or standard input, after displaying n lines containing matches.

line-number

n

Precedes each line by its line number in the file. The file does not need to contain line numbers.

quiet or silent

q

Does not write anything to standard output; just sets the exit code.

recursive

r or R

  

Recursively descends directories in file-list and processes files within these directories.

no-messages

s

(silent) Does not display an error message if a file in file-list does not exist or is not readable.

invert-match

v

Causes lines not containing a match to satisfy the search. When you use this option by itself, grep displays all lines that do not contain a match for the pattern.

word-regexp

w

With this option, the pattern must match a whole word. This option is helpful if you are searching for a specific word that may also appear as a substring within another word in the file.

line-regexp

x

The pattern matches whole lines only.


Notes

The grep utility returns an exit status of 0 if it finds a match, 1 if it does not find a match, and 2 if the file is not accessible or a syntax error occurs.

egrep and fgrep

Two utilities perform functions similar to that of grep. The egrep utility (same as grep E) allows you to use extended regular expressions (page 905), which include a different set of special characters than basic regular expressions do (page 903). The fgrep utility (same as grep F) is fast and compact but processes only simple strings, not regular expressions.

Examples

The following examples assume that the working directory contains three filestesta, testb, and testc:

File testa   File testb   File testc aaabb        aaaaa        AAAAA bbbcc        bbbbb        BBBBB ff-ff        ccccc        CCCCC cccdd        ddddd        DDDDD dddaa


The grep utility can search for a pattern that is a simple string of characters. The following command line searches testa and displays each line containing the string bb:

$ grep bb testa aaabb bbbcc


The v option reverses the sense of the test. The following example displays the lines in testa without bb:

$ grep -v bb testa ff-ff cccdd dddaa


The n option displays the line number of each displayed line:

$ grep -n bb testa 1:aaabb 2:bbbcc


The grep utility can search through more than one file. Here grep searches through each file in the working directory. The name of the file containing the string precedes each line of output.

$ grep bb * testa:aaabb testa:bbbcc testb:bbbbb


When the search for the string bb is done with the w option, grep produces no output because none of the files contains the string bb as a separate word:

$ grep -w bb * $


The search that grep performs is case sensitive. Because the previous examples specified lowercase bb, grep did not find the uppercase string BBBBB in testc. The i option causes both uppercase and lowercase letters to match either case of letter in the pattern:

$ grep -i bb * testa:aaabb testa:bbbcc testb:bbbbb testc:BBBBB $ grep -i BB * testa:aaabb testa:bbbcc testb:bbbbb testc:BBBBB


The c option displays the number of lines in each file that contain a match:

$ grep -c bb * testa:2 testb:1 testc:0


The f option finds matches for each pattern in a file of patterns. The next example shows gfile, which holds two patterns, one per line. The grep utility searches for matches to the patterns in gfile:

$ cat gfile aaa bbb $ grep -f gfile test* testa:aaabb testa:bbbcc testb:aaaaa testb:bbbbb


The following command line displays from the file text2 those lines that contain a string of characters starting with st, followed by zero or more characters (.* represents zero or more characters in a regular expressionsee Appendix A), and ending in ing:

$ grep 'st.* ing' text2 ...


The ^ regular expression, which matches the beginning of a line, can be used alone to match every line in a file. Together with the n option, ^ can be used to display the lines in a file, preceded by their line numbers:

$ grep -n '^' testa 1:aaabb 2:bbbcc 3:ff-ff 4:cccdd 5:dddaa


The next command line counts the number of times #include statements appear in C source files in the working directory. The h option causes grep to suppress the filenames from its output. The input to sort consists of all lines from *.c that match #include. The output from sort consists of an ordered list of lines that contains many duplicates. When uniq with the c option processes this sorted list, it outputs repeated lines only once, along with a count of the number of repetitions in its input.

$ grep -h '#include' * .c | sort | uniq -c 9 #include "buff.h" 2 #include "poly.h" 1 #include "screen.h" 6 #include "window.h" 2 #include "x2.h" 2 #include "x3.h" 2 #include <math.h> 3 #include <stdio.h>


The final command calls the vim editor with a list of files in the working directory that contain the string Sampson. The $(...) command substitution construct (page 327) causes the shell to execute grep and supply vim with a list of filenames that you want to edit:

$ vim $(grep -l 'Sampson' *) ...


The single quotation marks are not necessary in this example, but they are required if the regular expression you are searching for contains special characters or SPACEs. It is a good habit to quote the pattern so that the shell does not interpret any special characters it may contain.

gzip: Compresses or decompresses files

gzip [options] [file-list]

gunzip [options] [file-list]

zcat [file-list]

The gzip utility compresses files; gunzip restores files compressed with gzip; zcat displays files compressed with gzip.

Arguments

The file-list specifies the pathnames of one or more files that are to be compressed or decompressed. If a directory appears in file-list with no recursive option, gzip/gunzip issues an error message and ignores the directory. With the recursive option, gzip/gunzip recursively compresses/decompresses files within the directory hierarchy.

Without a file-list, or with the special option , gzip reads from standard input. The stdout option causes gzip and gunzip to write to standard output.

The information in this section also applies to gunzip, which is a link to gzip.

Options

Accepts the common options described on page 663.

stdout

c

Writes the results of compression or decompression to standard output instead of overwriting the original file.

decompress or uncompress

d

Decompresses a file compressed with gzip. This option with gzip is equivalent to the gunzip command.

fast or best

n

Controls the tradeoff between the speed of compression and the amount of compression. The n is a digit from 1 to 9. Level 1 is the fastest (least) compression, and level 9 is the best (slowest and most) compression. The default level is 6. The options fast and best are synonyms for 1 and 9, respectively.

force

f

Overwrites an existing output file.

list

l

For each compressed file in file-list, displays the file's compressed and decompressed sizes, the compression ratio, and the name of the file before compression. Use with verbose to display additional information.

quiet

q

Suppresses warning messages.

recursive

r

Recursively descends directories in file-list and compresses/decompresses files within these directories.

test

t

Verifies the integrity of a compressed file. Displays nothing if the file is OK.

verbose

v

Displays the name of the file, the name of the compressed file, and the amount of compression as each file is processed.


Discussion

Compressing files reduces disk space requirements and the time needed to transmit files between systems. When gzip compresses a file, it adds the extension .gz to the filename. For example, compressing the file fname creates the file fname.gz and deletes the original file. To restore fname, use the command gunzip with the argument fname.gz.

Almost all files become much smaller when compressed with gzip. On rare occasions a file will grow in size, but only by a relatively small amount. The type of a file and its contents (as well as the n option) determine how much smaller a file becomes; the sizes of text files are often reduced by 60 to 70 percent.

The attributes of a file, such as its owner, permissions, and modification and access times, are left intact when gzip compresses and gunzip decompresses a file.

If the compressed version of a file already exists, gzip reports that fact and asks for your confirmation before overwriting the existing file. If a file has multiple links to it, gzip issues an error message and exits. The force option overrides the default behavior in both of these situations.

Notes

For more information refer to "gzip: Compresses a File" on page 55.

In addition to the gzip format, gunzip recognizes several other compression formats. For example, it can decompress files that have been compressed with compress.

To see an example of a file that becomes larger when compressed with gzip, compare the size of a file that has been compressed once with the same file compressed with gzip again. Because gzip complains when you give it an argument with the extension .gz, you need to rename the file before compressing it a second time.

The tar utility with the z modifier (page 864) calls gzip.

The following related utilities display and manipulate compressed files. None of these utilities changes the files that it works on.

zcat file-list

Works like cat except that it uses gunzip to decompress file-list as it copies files to standard output.

zdiff [options] file1 [file2]

 

Works like diff (page 707) except that file1 and file2 are decompressed with gunzip as needed. The zdiff utility accepts the same options as diff. If you omit file2, zdiff compares file1 with the compressed version of file1.

zless file-list

Works like less except that it uses gunzip to decompress file-list as it displays files.


Examples

In the first example, gzip compresses two files. Then gunzip decompresses one of the files. When a file is compressed and decompressed, its size changes but its modification time remains the same.

$ ls -l total 175 -rw-rw-r-- 1 alex alex 33557 Jul 20 17:32 patch-2.0.7 -rw-rw-r-- 1 alex alex 143258 Jul 20 17:32 patch-2.0.8 $ gzip * $ ls -l total 51 -rw-rw-r-- 1 alex alex 9693 Jul 20 17:32 patch-2.0.7.gz -rw-rw-r-- 1 alex alex 40426 Jul 20 17:32 patch-2.0.8.gz $ gunzip patch-2.0.7.gz $ ls -l total 75 -rw-rw-r-- 1 alex alex 33557 Jul 20 17:32 patch-2.0.7 -rw-rw-r-- 1 alex alex 40426 Jul 20 17:32 patch-2.0.8.gz


In the next example, the files in Jenny's home directory are archived using the cpio utility (page 809). The archive is compressed with gzip before it is written to the archive file.

$ find /Users/jenny -depth -print | cpio -oBm | gzip > /Volumes/Backups/jenny.cpio.gz


head: Displays the beginning of a file

head [options] [file-list]

The head utility displays the beginning (head) of a file. This utility takes its input from one or more files you specify on the command line or from standard input.

Arguments

The file-list specifies the pathnames of one or more files that head displays. When you specify more than one file, head displays the filename before displaying the first few lines of each file. When you do not specify a file, head takes its input from standard input.

Options

n n

 
 

(lines) Displays the first n lines of a file. You can use n to specify n lines without using the n option. The n must be a positive number.


Notes

The head utility displays the first ten lines of a file by default.

Examples

The examples in this section are based on the following file:

$ cat eleven line one line two line three line four line five line six line seven line eight line nine line ten line eleven


Without any arguments, head displays the first ten lines of a file:

$ head eleven line one line two line three line four line five line six line seven line eight line nine line ten


The next example displays the first three lines (n 3) of the file:

$ head -n 3 eleven line one line two line three


The following example is equivalent to the preceding one:

$ head -3 eleven line one line two line three


kill: Terminates a process by PID number

kill [option] PID-list

The kill utility terminates one or more processes by sending them signals. For kill to work, the process must belong to the user executing kill, with one exception: Superuser can terminate any process.

Arguments

The PID-list specifies process identification (PID) numbers of processes that kill is to terminate.

Options

You can specify a signal number or name, preceded by a hyphen, as an option to cause kill to send the signal you specify to the PID-list. By default, kill sends a software termination signal (SIGTERM, signal number 15).

l (list) Displays a list of signals. (Do not specify PID-list.)

Notes

See also killall on page 763.

See Table 13-5 on page 577 for a list of signals. The command kill l displays a complete list of signal numbers and names.

In addition to the kill utility, kill is a builtin in the Bourne Again and TC Shells. The builtins work similarly to the utility described here. Give the command /bin/kill to use the kill utility and the command kill to use the builtin. It does not usually matter which one you use.

The shell displays the PID number of a background process when you initiate the process. You can also use the ps utility to determine PID numbers.

If the software termination signal does not terminate a process, try using a KILL signal (signal number 9). A process can choose to ignore any signal except KILL.

The kill utility/builtin accepts job identifiers in place of the PID-list. Job identifiers consist of a percent sign (%) followed by either a job number (page 131) or a string that uniquely identifies the job.

To terminate all processes that the current login process initiated and have the operating system log you out, give the command kill 9 0.

Examples

The first example shows a command line executing the file compute as a background process and the kill utility terminating it:

$ compute & [2] 259 $ kill 259 $ RETURN [2]+   Terminated                 compute


The next example shows the ps utility determining the PID number of the background process running a program named robots and the kill utility terminating robots with the TERM signal:

$ ps   PID  TT  STAT        TIME COMMAND  5382  p1  Ss       0:00.27 -bash 18957  p1  S+       0:00.01 robots 14863  p2  Ss       0:00.25 -bash $ kill -TERM 18957 $


killall: Terminates a process by name

killall [option] name-list

The killall utility sends signals to processes executing specified commands. For killall to work, the processes must belong to the user executing killall, with one exception: Superuser can terminate any process.

Arguments

The name-list is a SPACE-separated list of names of programs that are to receive signals.

Options

You can specify a signal number or name, preceded by a hyphen, as an option to cause killall to send the signal you specify to name-list. By default killall sends software termination signals (signal number 15, SIGTERM).

l (list) Displays a list of signals (but kill l displays a better list). (Do not specify a name-list.)

Notes

See also kill on page 761.

See Table 13-5 on page 577 for a list of signals. The command kill l displays a complete list of signal numbers and names.

If the software termination signal does not terminate a process, try using a KILL signal (signal number 9). A process can choose to ignore any signal except KILL.

You can use the ps utility (page 819) to determine the name of the program you want to terminate.

Examples

You can give the following commands to experiment with killall:

$ sleep 60 & [1] 23274 $ sleep 50 & [2] 23275 $ sleep 40 & [3] 23276 $ sleep 120 & [4] 23277 $ killall sleep [1]   Terminated             sleep 60 [2]   Terminated             sleep 50 [3]-  Terminated             sleep 40 [4]+  Terminated             sleep 120


If you want to terminate all instances of the Safari browser, give the following command to determine how Safari was called:

$ ps ax | grep -i safari 20316  ?? S   0:04.38 /Applications/Safari.app/Contents/MacOS/Safari -psn_0 24216  p1 R+  0:00.00 grep -i safari


The next command, run as root, terminates all instances of the Safari browser:

# killall Safari


launchctl: Controls the launchd daemon

launchctl [subcommand [options] [arguments]]

The launchctl utility controls the launchd daemon (page 456).

Arguments

The subcommand is the command that launchctl sends to launchd. Table VI-15 lists the subcommands and the options and arguments that each accepts. Without a subcommand, launchctl reads subcommands, options, and arguments from standard input, one set per line. Without a subcommand, when standard input comes from the keyboard, launchctl prompts you for input.

Table VI-15. launchctl subcommands

Subcommand

Argument

Description

help

None

Displays a help message

list

None

Lists jobs loaded into launchd

load [w]

Job configuration file

Loads the job named by the argument

reloadttys

None

Rereads the /etc/ttys file

shutdown

None

Prepares for shutdown by removing all jobs

start

Job name

Starts the job named by the argument

stop

Job name

Stops the job named by the argument

unload [w]

Job configuration file

Unloads the job named by the argument


Options

Only the load and unload subcommands take options.

w

(write) When loading a file, remove the Disabled key and save the modified configuration file. When unloading a file, add the Disabled key and save the modified configuration file.


Discussion

The launchd daemon (page 456) manages system daemons and background tasks, called jobs. Each job is described by a job configuration file, which is a property list file (page 453) in the format defined by the launchd.plist man page. The launchctl utility is the user interface to launchd.

For security reasons, nonroot users cannot communicate with the system's primary launchd process, which is PID 1. When a nonroot user loads jobs, OS X creates a new instance of launchd for that user. When all of its jobs are unloaded, that instance of launchd quits.

Notes

The launchctl utility and launchd daemon were introduced in Mac OS X version 10.4. Under version 10.3 and earlier, system jobs are managed by init, xinetd, and cron.

For more information refer to "launchctl: Controls launchd" on page 458.

Examples

The first example, run as root, uses the list subcommand to list launchd jobs running on the local system:

# launchctl list com.apple.atprintd.i9900 com.apple.KernelEventAgent com.apple.mDNSResponder com.apple.nibindd com.apple.periodic-daily com.apple.periodic-monthly com.apple.periodic-weekly com.apple.portmap com.apple.servermgrd com.apple.syslogd com.apple.watchdogtimerd com.vix.cron org.postfix.master org.xinetd.xinetd com.openssh.sshd com.apple.cups-lpd


Next root enables the ntalk service. Looking at the ntalk.plist file before and after the launchctl command shows that launchctl has modified the file by removing the Disabled key.

# cat /System/Library/LaunchDaemons/ntalk.plist ... <dict>         <key>Disabled</key>         <true/>         <key>Label</key>         <string>com.apple.ntalkd</string> ... # launchctl load -w /System/Library/LaunchDaemons/ntalk.plist # cat /System/Library/LaunchDaemons/ntalk.plist ... <dict>         <key>Label</key>         <string>com.apple.ntalkd</string> ...


Without any arguments, launchctl prompts for subcommands on standard input. Use CONTROL-D to exit from launchctl. In the last example, root causes launchctl to display a list of jobs and then to stop the job that would launch cron if there were any crontab files (page 697):

# launchctl launchd% list com.apple.KernelEventAgent com.apple.mDNSResponder com.apple.nibindd com.apple.periodic-daily com.apple.periodic-monthly com.apple.periodic-weekly com.apple.portmap com.apple.syslogd com.vix.cron org.postfix.master org.xinetd.xinetd com.openssh.sshd launchd% stop com.vix.cron launchd% CONTROL-D #


less: Displays text files, one screen at a time

less [options] [file-list]

The less utility displays text files, one screen at a time.

Arguments

The file-list specifies the pathnames of one or more files that less is to display. Without a file-list, less reads from standard input.

Options

Accepts the common options described on page 663.

clear-screen

c

Repaints the screen from the top line down instead of scrolling.

quit-at-eof

e

(exit) Normally less requires you to enter q to terminate the utility. This option exits automatically the second time less reads the end of file.

QUIT-AT-EOF

E

(exit) Similar to e, except that less exits automatically the first time it reads the end of file.

quit-if-one-screen

 
 

F

Displays the file and quits if the file can be displayed on a single screen.

ignore-case

i

Causes a search for a string of lowercase letters to match both uppercase and lowercase letters (see /regular-expression on page 770). This option is ignored if you specify a pattern that includes uppercase letters.

IGNORE-CASE

 
 

I

Causes a search for a string of letters of any case to match both uppercase and lowercase letters, regardless of the case of the search pattern (see /regular-expression on page 770).

long-prompt

m

Reports the percentage of the file that you have viewed with each prompt. This option reports byte numbers when less reads from standard input because less has no way of determining how much input there is.

LINE-NUMBERS

 
 

N

Displays a line number at the start of each line.

 

Psprompt

  

(prompt string) Changes the short prompt string (the prompt that appears at the bottom of each screen of output) to prompt. Enclose prompt in quotation marks if it contains SPACEs. You can use special symbols in prompt that less will replace with other values when it displays the prompt. For example, less displays the current filename in place of %f. See the less man page for a list of these special symbols and descriptions of other prompts. Custom prompts are useful if you are running less from within another program and want to give instructions or information to the user of that program. The default prompt is the name of the file displayed in reverse video.

squeeze-blank-lines

 
 

s

Displays multiple, adjacent blank lines as a single blank line. When you use less to display text that has been formatted for printing with blank space at the top and bottom of each page, this option shortens these headers and footers to a single line.

tabs=n

xn

 
  

Sets TAB stops n characters apart. The default is eight characters.

window=n

[z]n

  

Sets the scrolling size to n lines. The default is the size of the display. Each time you move forward or backward a page, you move n lines. See "Commands."

 

+command

  

Any command you can give less while it is running can also be given as an option by preceding it with a plus sign (+) on the command line. See the "Commands" section. A command preceded by a plus sign on the command line is executed as soon as less starts and applies only to the first file.

 

++command

  

Similar to +command except that command is applied to every file in file-list, not just the first one.


Notes

The phrase "less is more" explains the origin of this utility. The more utility is the original Berkeley UNIX pager. The less utility is similar to more but includes many enhancements. (Under OS X, less and more are two links to the same file.) After displaying a screen of text, less displays a prompt and waits for you to enter a command. You can skip forward and backward in the file, invoke an editor, search for a pattern, or perform any number of other tasks.

See the v command in the next section for information on how you can edit the file that you are viewing with less.

You can set the options to less either from the command line when you call less or by setting the LESS environment variable. For example, you can use the following command from bash to use less with the x4 and s options:

$ export LESS="-x4 -s"


Normally you would set LESS in ~/.bash_profile if you are using bash or in ~/.login if you are using tcsh. Once you have set the LESS variable, less is invoked with the specified options each time you call it. Any options you give on the command line override the settings in the LESS variable. The LESS variable is used both when you call less from the command line and when less is invoked by another program, such as man. To specify less as the pager to use with man and other programs, set the environment variable PAGER to less. For example, with bash you can add the following line to ~/.bash_profile:

export PAGER=less


Commands

Whenever less pauses, you can enter any of a large number of commands. This section describes some commonly used commands. Refer to the less man page for the complete list of commands. The optional numeric argument n defaults to 1, with the exceptions noted. You do not need to press RETURN to terminate these commands.

nb or nCONTROL-B

(backward) Scrolls backward n lines. The default value of n is the size of the screen.

nd or nCONTROL-D

(down) Scrolls forward n lines. The default value of n is one-half the screen size. When you specify n, it becomes the new default value for this command.

F

(forward) Scrolls forward. If the end of the input is reached, this command waits for more input and then continues scrolling. It allows you to use less in a manner similar to tail f (page 859), except that less paginates the output as it appears.

ng

(go) Goes to line number n. This command may not work if the file is read from standard input and you have moved too far into the file. The default value of n is 1.

h or H

(help) Displays a summary of all available commands. The summary is displayed using less, as the list of commands is quite long.

nRETURN or nj

(jump) Scrolls forward n lines. The default value of n is 1.

q or :q

Terminates less.

nu or nCONTROL-U

(up) Scrolls backward n lines. The default value of n is one-half the screen size. When you specify n, it becomes the default value for this command.

v

Brings the current file into an editor with the cursor on the current line. The less utility uses the editor specified in the EDITOR environment variable. If EDITOR is not set, less uses vi (which is typically linked to vim).

nw

Scrolls backward like nb, except that the value of n becomes the new default value for this command.

ny or nk

Scrolls backward n lines. The default value of n is 1.

nz

Displays the next n lines like nSPACE except that the value of n, if present, becomes the new default value for the z and SPACE commands.

nSPACE

Displays the next n lines. Pressing SPACE by itself displays the next screen of text.

/regular-expression

 

Skips forward in the file, looking for lines that contain a match for regular-expression. If you begin regular-expression with an exclamation point (!), this command looks for lines that do not contain a match for regular-expression. If regular-expression begins with an asterisk (*), this command continues the search through file-list. (A normal search stops at the end of the current file.) If regular-expression begins with an at sign (@), this command begins the search at the start of file-list and continues to the end of file-list.

?regular-expression

 

This command is similar to the previous one but searches backward through the file (and file-list). Beginning regular-expression with an asterisk (*) causes the search to continue backward through file-list to the beginning of the first file. Beginning regular-expression with an at sign (@) causes the search to start with the last line of the last file in file-list and progress toward the first line of the first file.

{ or ( or [

If one of these characters appears in the top line of the display, this command scrolls forward to the matching right brace, parenthesis, or bracket. For example, typing { causes less to move the cursor forward to the matching }.

} or ) or ]

Similar to the preceding commands, these commands move the cursor backward to the matching left brace, parenthesis, or bracket.

CONTROL-L

Redraws the screen. This command is useful if the text on the screen has become garbled.

[n]:n

Skips to the next file in file-list. With n, skips to the nth next file in file-list.

![command line]

Executes command line under the shell specified by the SHELL environment variable, or sh (a copy of bash) by default. A percent sign (%) in command line is replaced by the name of the current file. If you omit command line, less starts an interactive shell.


Examples

The following example displays the file memo.txt. To see more of the file, the user presses the SPACE bar in response to the less prompt at the bottom left of the screen:

$ less memo.txt ... memo.txt SPACE ...


In the next example, the user changes the prompt to a more meaningful message and uses the N option to display line numbers. The user then instructs less to skip forward to the first line containing the string procedure.

$ less -Ps"Press SPACE to continue, q to quit" -N +/procedure ncut.icn     28 procedure main(args)     29     local filelist, arg, fields, delim     30     31     filelist:=[] ...     45     # Check for real field list     46     #     47     if /fields then stop("-fFIELD_LIST is required.")     48     49     # Process the files and output the fields Press SPACE to continue, q to quit


ln: Makes a link to a file

ln [options] existing-file [new-link]

ln [options] existing-file-list directory

The ln utility creates hard or symbolic links to one or more files. You can create a symbolic linkbut not a hard linkto a directory.

Arguments

In the first format the existing-file is the pathname of the file that ln is to create a link to. The new-link is the pathname of the new link. When you are creating a symbolic link, the existing-file can be a directory. If you omit new-link, ln creates a link to existing-file in the working directory and uses the same simple filename as existing-file.

In the second format the existing-file-list specifies the pathnames of the ordinary files that ln is to create links to. The ln utility establishes the new links in the directory. The simple filenames of the entries in the directory are the same as the simple filenames of the files in the existing-file-list.

Options

f

(force) Normally ln does not create the link if new-link already exists. This option removes new-link before creating the link.

h

(no dereference) If new-link or directory is a symbolic link, do not follow it. Used in conjunction with f, this option replaces an existing symbolic link.

i

(interactive) If new-link already exists, this option prompts you before removing new-link. If you enter y or yes, ln removes new-link before creating the link. If you answer n or no, no new link is made.

s

(symbolic) Creates a symbolic link. When you use this option, the existing-file and new-link may be directories and may reside on different filesystems. Refer to "Symbolic Links" on page 105.


Notes

For more information refer to "Links" on page 102. The ls utility with the l option displays the number of hard links to a file (Figure 4-11, page 88).

Hard links

By default ln creates hard links. A hard link to a file is indistinguishable from the original file. All hard links to a file must be in the same filesystem. For more information refer to "Hard Links" on page 103.

Symbolic links

You can also use ln to create symbolic links. Unlike a hard link, a symbolic link can exist in a different filesystem from the linked-to file. Also, a symbolic link can point to a directory. For more information refer to "Symbolic Links" on page 105.

If new-link is the name of an existing file, ln does not create the link unless you use the f option or answer yes when using the i option.

Examples

The following command creates a link between the memo2 file in the /Users/zach/literature directory and the working directory. The file appears as memo2 (the simple filename of the existing file) in the working directory:

$ ln /Users/zach/literature/memo2 .


You can omit the period that represents the working directory from the preceding command. When you give a single argument to ln, it creates a link in the working directory.

The next command creates a link to the same file. This time the file appears as new_memo in the working directory:

$ ln /Users/zach/literature/memo2 new_memo


The following command creates a link that causes the same file to appear in another user's directory:

$ ln /Users/zach/literature/memo2 /Users/jenny/new_memo


You must have write and execute access permissions to the other user's directory for this command to work. If you own the file, you can use chmod to give the other user write access permission to the file.

The next command creates a symbolic link to a directory. The ls ld command shows the link:

$ ln -s /usr/local/bin bin $ ls -ld bin lrwxr-xr-x 1 zach zach 14 Feb 10 13:26 bin -> /usr/local/bin


The final example attempts to create a symbolic link named memo1 to the file memo2. Because the file memo1 already exists, ln refuses to make the link. When you use the i option, ln asks whether you want to replace the existing memo1 file with the symbolic link. If you enter y, ln removes the old memo1 file and creates the link.

$ ls -l memo? -rw-rw-r--  1 zach group 224 Jul 31 14:48 memo1 -rw-rw-r--  1 zach group 753 Jul 31 14:49 memo2 $ ln -s memo2 memo1 ln: memo1: File exists $ ln -s -i memo2 memo1 ln: replace 'memo1'? y $ ls -l memo? lrwxr-xr-x  1 zach group 5 Jul 31 14:49 memo1 -> memo2 -rw-rw-r--  1 zach group 753 Jul 31 14:49 memo2


You can also use the f option to cause ln to overwrite a file.

lpr: Sends files to printers

lpr [options] [file-list]

lpq [options] [job-identifier-list]

lprm [options] [job-identifier-list]

The lpr utility places one or more files into a print queue, providing orderly access to printers for several users or processes. This utility can work with printers attached to remote systems. You can use the lprm utility to remove files from the print queues and the lpq utility to check the status of files in the queues.

Arguments

The file-list specifies the pathnames of one or more files that lpr is to print. Often these files are text files, but many systems are configured so that lpr can print a variety of file types. Without a file-list, lpr accepts input from standard input.

The job-identifier-list is a list of job numbers or usernames. If you do not know the job number of a print job, use lpq to display a list of print jobs.

Options

Some of the following options depend on what type of file is being printed as well as on how the system is configured for printing.

l

(lowercase "l") Specifies that lpr should not preprocess (filter) the file being printed. Use this option when the file is already formatted for the printer.

P

printer

 

Sends the print jobs to the queue for the printer named printer. If you do not use this option, print jobs are sent to the default printer for the local system. The acceptable values for printer are found in the file /etc/printcap and vary from system to system.

r

(remove) Deletes the files in file-list after calling lpr.

#

n

 

Prints n copies of each file.


Discussion

The lpr utility takes input from files you specify on the command line or from standard input and adds the files to the print queue as print jobs. It also assigns a unique identification number to each print job. The lpq utility displays the job numbers of the print jobs that lpr has set up; you can use the lprm utility to remove a print job from the print queue.

lpq

The lpq utility displays information about jobs in a print queue. Without an argument, lpq lists the print jobs queued for the default printer. Use lpr's P printer option with lpq to look at other print queueseven those for printers connected to other systems. With the l (lowercase "l") option, lpq displays more information about each job. If you supply a username as an argument, lpq displays only the print jobs belonging to that user.

lprm

One item displayed by lpq is the job number for each print job in the queue. To remove a job from the print queue, supply the job number as an argument to lprm. Unless you are Superuser, you can remove only your own print jobs. Even as Superuser you may not be able to remove a job from a queue for a remote printer. If you do not give any arguments to lprm, it removes the currently active print job (that is, the job that is now printing) from the queue, if you own that job.

Notes

If you normally use a printer other than the system default printer, you can set up lpr to use another printer as your personal default by assigning the name of this printer to the environment variable PRINTER. For example, if you use bash, you can add the following line to ~/.bash_profile to set your default printer to the printer named ps:

export PRINTER=ps


lpstat

Printers configured through the Mac OS X GUI are accessible through lpr. The command lpstat t displays the names of the printers you can use.

LPD and LPR

Traditionally UNIX had two printing systems: the BSD Line Printer Daemon (LPD) and the System V Line Printer system (LPR). Both of these systems have undergone modifications and replacements. A newer system, CUPS, is the default printing system under Mac OS X.

CUPS

CUPS (Common UNIX Printing System) is a cross-platform print server built around IPP (Internet Printing Protocol), which is based on HTTP. CUPS provides a number of printer drivers and can print different types of files, including PostScript files. CUPS provides System V and BSD command line interfaces and, in addition to IPP, supports the LPD/LPR, HTTP, SMB, and JetDirect (socket) protocols, among others.

This section describes the LPD command line interface that runs under CUPS.

Examples

The first command sends the file named memo2 to the default printer:

$ lpr memo2


Next a pipe sends the output of ls to the printer named deskjet:

$ ls | lpr -Pdeskjet


The next example paginates and sends the file memo to the printer:

$ pr -h "Today's memo" memo | lpr


The next example shows a number of print jobs queued for the default printer. Alex owns all of these jobs as well as the one that is being printed (the active job). Jobs 635 and 639 were created by sending input to lpr's standard input; job 638 was created by giving ncut.icn as an argument to the lpr command. The last column shows the size of each print job.

$ lpq deskjet is ready and printing Rank   Owner      Job Files                                Total Size active alex       635 (stdin)                             38128 bytes 1st    alex       638 ncut.icn                             3587 bytes 2nd    alex       639 (stdin)                              3960 bytes 


The final command removes job 638 from the default print queue:

$ lprm 638


ls: Displays information about one or more files

ls [options] [file-list]

The ls utility displays information about one or more files. It lists the information alphabetically by filename unless you use an option to change the order.

Arguments

When you do not provide an argument, ls displays the names of the visible files in the working directory (those files whose filenames do not begin with a period).

The file-list is a list of one or more pathnames of ordinary, directory, or device files. It can include ambiguous file references.

When you specify a directory, ls displays the contents of the directory. It displays the name of the directory only when needed to avoid ambiguity, such as when the listing includes more than one directory. When you specify an ordinary file, ls displays information about that one file.

Options

The options determine the type of information ls displays as well as the manner and order in which it displays the information. Without an option, ls displays a short list that contains only the names of files.

a

(all) Includes invisible files (those whose filenames begin with a period) in the listing. Without this option, ls does not list information about invisible files unless you include the name of an invisible file in the file-list. The * ambiguous file reference does not match a leading period in a filename (see page 134).

A

(almost all) The same as a but does not list the . and .. entries (the default behavior when running as root).

b

(backslash) Displays nonprinting characters in a filename, using backslash escape sequences similar to those used in C language strings. Table VI-16 lists some of these escape sequences. Other nonprinting characters are displayed as a backslash followed by an octal number.


Table VI-16. Backslash escape sequences

Sequence

Meaning

\b

BACKSPACE

\n

NEWLINE

\r

RETURN

\t

HORIZONTAL TAB

\v

VERTICAL TAB

\\

BACKSLASH


d

(directory) Displays the names of directories without displaying their contents. Without an argument, this option displays information about the working directory. This option does not dereference symbolic links (it lists a link, not the directory the link points to).

e

(extended) Displays ACLs (page 97) in a long listing (with the l option).

F

(file type) Displays a slash (/) after a directory, an asterisk (*) after an executable file, an at sign (@) after a symbolic link, an equal sign (=) after a socket, and a vertical bar (|) after a FIFO.

h

(human readable) Displays sizes in K (kilobyte), M (megabyte), and G (gigabyte) blocks, as appropriate. Works with the l option only.

i

(inode) Displays the inode number of each file. With the l option, this option displays the inode number in column 1 and shifts all other items one column to the right.

l

(long, lowercase "l") Lists more information about each file. Use this option with h to make file sizes more easily readable and with e to display ACLs. See "Discussion" for more information.

L

(dereference) Lists information about the file referenced by a symbolic link rather than information about the link itself.

m

(stream) Displays filenames in a comma-separated list that fills the width of the screen.

o

(flags) Displays file flags (page 92) when used with the l option.

q

(question mark) Displays nonprinting characters in a filename as question marks. When output goes to the screen, this is the default behavior.

r

(reverse) Displays the list of filenames in reverse sorted order.

R

(recursive) Recursively lists subdirectories.

s

(size) Displays the number of blocks allocated to the file. The size precedes the filename. With the l option, this option displays the size in column 1 and shifts all other items one column to the right. Set BLOCKSIZE (page 663) to specify a block size (the default is 512 bytes).

t

(time) Displays files sorted by modification time instead of by filename.

x

Displays files sorted by lines (the default display is sorted by columns).

1

(number 1) Displays files one per line. When the output does not go to the screen, this behavior is the default.


Discussion

The ls long, extended listing (le option) displays the eight columns shown in Figure 4-11 on page 88. The first column, which contains 11 characters, is divided as described in the following paragraphs. The first character describes the type of file, as shown in Table VI-17.

Table VI-17. First character in a long ls display

Character

Meaning

Ordinary

b

Block device

c

Character device

d

Directory

p

FIFO (named pipe)

l

Symbolic link


The next nine characters of the first column represent the access permissions associated with the file. They are divided into three sets of three characters each.

The first three characters represent the owner's access permissions. If the owner has read access permission for the file, r appears in the first character position. If the owner is not permitted to read the file, a hyphen appears in this position. The next two positions represent the owner's write and execute access permissions. If w appears in the second position, the owner is permitted to write to the file; if x appears in the third position, the owner is permitted to execute the file. An s in the third position indicates that the file has both setuid and execute permissions. An S indicates setuid without execute permission. A hyphen indicates that the owner does not have the access permission associated with the character position.

In a similar manner the second and third sets of three characters represent the access permissions of the group the file is associated with and the access permissions of other users, respectively. An s in the third position of the second set of characters indicates that the file has setgid permission with execute permission, and an S indicates setgid without execute permission.

The last character is t if the sticky bit (page 955) is set with execute permission and T if it is set without execute permission. Refer to chmod on page 676 for information on changing access permissions.

When called with the le options, ls displays a plus sign (+) in the second column if the file has an ACL. If the file does not have an ACL, the second column is empty. See page 97 for more information on ACLs.

The third column indicates the number of hard links to the file. Refer to page 102 for more information on links.

The fourth and fifth columns display the name of the owner of the file and the name of the group the file is associated with, respectively.

The sixth column indicates the size of the file in bytes or, if information about a device file is being displayed, the major and minor device numbers. In the case of a directory, this number is the size of the directory file, not the size of the files that are found within the directory. (Use du to display the sum of the sizes of all files in a directory.) Use the h option to display the size of files in kilobytes, megabytes, or gigabytes.

The last two columns display the date and time the file was last modified and the filename, respectively.

Notes

Refer to page 133 for examples of using ls with ambiguous file references.

Examples

The first command line shows the ls utility with the x option, which sorts the files horizontally. The ls utility displays an alphabetical list of the names of the files in the working directory:

$ ls -x bin     c           calendar execute     letters     shell


The F option appends a slash (/) to files that are directories, an asterisk to files that are executable, and an at sign (@) to symbolic links:

$ ls -Fx bin/      c/          calendar execute*  letters/    shell@


Next the l (long) option displays a long list. The files are still in alphabetical order:

$ ls -l total 8 drwxrwxr-x  2 jenny jenny   80  May 20 09:17 bin drwxrwxr-x  2 jenny jenny  144  Mar 26 11:59 c -rw-rw-r--  1 jenny jenny  104  May 28 11:44 calendar -rwxrw-r--  1 jenny jenny   85  May  6 08:27 execute drwxrwxr-x  2 jenny jenny   32  Mar  6 22:56 letters drwxrwxr-x 16 jenny jenny 1296  Jun  6 17:33 shell


The a (all) option lists all files, including invisible ones:

$ ls -a .      .profile   c           execute    shell ..     bin        calendar    letters


Combining the a and l options displays a long listing of all files, including invisible files, in the working directory. This list is still in alphabetical order:

$ ls -al total 12 drwxrwxr-x  6 jenny jenny  480 Jun  6 17:42 . drwxrwxr-t 26 root  admin  816 Jun  6 14:45 .. -rw-rw-r--  1 jenny jenny  161 Jun  6 17:15 .profile drwxrwxr-x  2 jenny jenny   80 May 20 09:17 bin drwxrwxr-x  2 jenny jenny  144 Mar 26 11:59 c -rw-rw-r--  1 jenny jenny  104 May 28 11:44 calendar -rwxrw-r--  1 jenny jenny   85 May  6 08:27 execute drwxrwxr-x  2 jenny jenny   32 Mar  6 22:56 letters drwxrwxr-x 16 jenny jenny 1296 Jun  6 17:33 shell


When you add the r (reverse) option to the command line, ls produces a list in reverse alphabetical order:

$ ls -ral total 12 drwxrwxr-x 16 jenny jenny 1296 Jun  6 17:33 shell drwxrwxr-x  2 jenny jenny   32 Mar  6 22:56 letters -rwxrw-r--  1 jenny jenny   85 May  6 08:27 execute -rw-rw-r--  1 jenny jenny  104 May 28 11:44 calendar drwxrwxr-x  2 jenny jenny  144 Mar 26 11:59 c drwxrwxr-x  2 jenny jenny   80 May 20 09:17 bin -rw-rw-r--  1 jenny jenny  161 Jun  6 17:15 .profile drwxrwxr-t 26  root admin  816 Jun  6 14:45 .. drwxrwxr-x  6 jenny jenny  480 Jun  6 17:42 .


Use the t and l options to list files so that the most recently modified file appears at the top of the list:

$ ls -tl total 8 drwxrwxr-x 16 jenny jenny 1296 Jun  6 17:33 shell -rw-rw-r--  1 jenny jenny  104 May 28 11:44 calendar drwxrwxr-x  2 jenny jenny   80 May 20 09:17 bin -rwxrw-r--  1 jenny jenny   85 May  6 08:27 execute drwxrwxr-x  2 jenny jenny  144 Mar 26 11:59 c drwxrwxr-x  2 jenny jenny   32 Mar  6 22:56 letters


Together the r and t options cause the file you modified least recently to appear at the top of the list:

$ ls -trl total 8 drwxrwxr-x  2 jenny jenny   32 Mar  6 22:56 letters drwxrwxr-x  2 jenny jenny  144 Mar 26 11:59 c -rwxrw-r--  1 jenny jenny   85 May  6 08:27 execute drwxrwxr-x  2 jenny jenny   80 May 20 09:17 bin -rw-rw-r--  1 jenny jenny  104 May 28 11:44 calendar drwxrwxr-x 16 jenny jenny 1296 Jun  6 17:33 shell


The next example shows ls with a directory filename as an argument. The ls utility lists the contents of the directory in alphabetical order:

$ ls bin c      e     lsdir


To display information about the directory file itself, use the d (directory) option. This option lists information only about the directory:

$ ls -dl bin drwxrwxr-x 2 jenny jenny 80 May 20 09:17 bin


The following command displays a list of all invisible filenames (those starting with a period) in your home directory. Using this command is a convenient way to list the startup files in your home directory:

$ ls -d ~/.* /Users/sam/.                    /Users/sam/.bashrc /Users/sam/..                   /Users/sam/.history ...


A plus sign (+) to the right of the permissions in a long listing denotes the presence of an ACL for a file:

$ ls -l memo -rw-r--r-- + 1 alex   alex   19 Jul 19 21:59 memo


Use the le options to display an ACL:

$ ls -le memo -rw-r--r-- + 1 alex   alex 19 Jul 19 21:59 memo  0: user:jenny allow  read


See page 680 for more examples of using ls to display ACLs.

make: Keeps a set of programs current

make [options] [target-files] [arguments]

The GNU make utility keeps a set of executable programs current, based on differences in the modification times of the programs and the source files that each program is dependent on.

Arguments

The target-files refer to targets on dependency lines in the makefile. When you do not specify a target-file, make updates the target on the first dependency line in the makefile. Command line arguments of the form name=value set the variable name to value inside the makefile. See "Discussion" for more information.

Options

If you do not use the f option, make takes its input from a file named GNUmakefile, makefile, or Makefile (in that order) in the working directory. In this section, this input file is referred to as makefile. Many users prefer to use the name Makefile because it shows up earlier in directory listings.

C

directory

 

(change directory) Makes directory the working directory before starting.

d

(debug) Displays information about how make decides what to do.

f

file

 

(input file) Uses file as input instead of makefile.

j

n

 

(jobs) Runs up to n commands at the same time instead of the default of one command. Running multiple commands simultaneously is especially effective if you are running OS X on a multiprocessor system. If you omit n, make does not limit the number of simultaneous jobs.

k

(keep going) Continues with the next file from the list of target-files instead of quitting when a construction command fails.

n

(no execution) Displays, but does not execute, the commands that make would execute to bring the target-files up-to-date.

s

(silent) Does not display the names of the commands being executed.

t

(touch) Updates the modification times of target files but does not execute any construction commands (page 489). Refer to touch on page 877.


Discussion

The make utility bases its actions on the modification times of the programs and the source files that each program is dependent on. Each of the executable programs, or target-files, is dependent on one or more prerequisite files. The relationships between target-files and prerequisites are specified on dependency lines in a makefile. Construction commands follow the dependency line, specifying how make can update the target-files.

Documentation

Refer to page 489 for more information about make and makefiles. For additional information refer to www.gnu.org/software/make/manual/make.html and to the make info page.

Although the most common use of make is to build programs from source code, this general-purpose build utility is suitable for a wide range of applications. Anywhere you can define a set of dependencies to get from one state to another represents a candidate for using make.

Much of make's power derives from the features you can set up in a makefile. For example, you can define variables using the same syntax found in the Bourne Again Shell. Always define the variable SHELL in a makefile; set it to the pathname of the shell you want to use when running construction commands. To define the variable and assign it a value, place the following line near the top of a makefile:

SHELL=/bin/sh


Assigning the value /bin/sh to SHELL allows you to use a makefile on other computer systems. On OS X systems, /bin/sh is a copy of /bin/bash. The make utility uses the value of the environment variable SHELL if you do not set SHELL in a makefile. If SHELL does not hold the path of the shell you intended to use and if you do not set SHELL in a makefile, the construction commands may fail.

Following is a list of additional features associated with make:

  • You can run specific construction commands silently by preceding them with an @ sign. For example, the following lines display a short help message when you run the command make help:

     help:     @echo "You can make the following:"     @echo " "     @echo "libbuf.a       -- the buffer library"     @echo "Bufdisplay     -- display any-format buffer"     @echo "Buf2ppm        -- convert buffer to pixmap"

    Without the @ signs in the preceding example, make would display each of the echo commands before executing it. This way of displaying a message works because no file is named help in the working directory. As a result make runs the construction commands in an attempt to build this file. Because the construction commands display messages but do not build the file help, you can run make help repeatedly with the same result.

  • You can cause make to ignore the exit status of a command by preceding the command with a hyphen (-). For example, the following line allows make to continue regardless of whether the call to /bin/rm is successful (the call to /bin/rm fails if libbuf.a does not exist):

    -/bin/rm libbuf.a

  • You can use special variables to refer to information that might change from one use of make to the next. Such information might include the files that need updating, the files that are newer than the target, or the files that match a pattern. For example, you can use the variable $? in a construction command to identify all prerequisite files that are newer than the target file. This variable allows you to print any files that have changed since the last time you printed files.

    list:      .list .list:     Makefile buf.h xtbuff_ad.h buff.c buf_print.c xtbuff.c pr $? | lpr date >.list

  • The target list depends on which source files need to be printed. The construction command pr $? | lpr prints only those source files that are newer than the file .list. The line date > .list modifies the .list file so that it is newer than any of the source files. The next time you run the command make list, only the files that have been changed are printed.

  • You can include other makefiles as if they were part of the current makefile. The following line causes make to read Make.config and treat the contents of that file as though it were part of the current makefile, allowing you to collect information common to more than one makefile in a single place:

    include Make.config

Notes

The section "make: Keeps a Set of Programs Current" on page 489 provides more information about make.

Examples

The first example causes make to bring the target-file named analysis up-to-date by issuing three cc commands. It uses a makefile named GNUmakefile, makefile, or Makefile in the working directory.

$ make analysis cc -c analy.c cc -c stats.c cc -o analysis analy.o stats.o


The following example also updates analysis but uses a makefile named analysis.mk in the working directory:

$ make -f analysis.mk analysis 'analysis' is up to date.


The next example lists the commands make would execute to bring the target-file named credit up-to-date. Because of the n option, make does not execute the commands.

$ make -n credit cc -c -0 credit.c cc -c -0 accounts.c cc -c -0 terms.c cc -o credit credit.c accounts.c terms.c


The next example uses the t option to update the modification time of the target-file named credit. After you use this option, make thinks that credit is up-to-date.

$ make -t credit $ make credit 'credit' is up to date.


Next a simple makefile builds a utility named ff. Because the cc command needed to build ff is complex, using a makefile allows you to rebuild ff easily, without having to remember and retype the cc command.

$ cat Makefile # Build the ff command from the fastfind.c source SHELL=/bin/sh ff: cc -traditional -02 -g -DBIG=5120 -o ff fastfind.c myClib.a $ make ff cc -traditional -02 -g -DBIG=5120 -o ff fastfind.c myClib.a


Advanced example

The following example shows a much more sophisticated makefile that uses features not discussed in this section. Refer to the sources cited under "Documentation" on page 784 for information about these and other advanced features.

$ cat Makefile ########################################################### ## Build and maintain the buffer library ########################################################### SHELL=/bin/sh ########################################################### ## Flags and libraries for compiling. The XLDLIBS are needed #   whenever you build a program using the library. The CCFLAGS #   give maximum optimization. CC=gcc CCFLAGS=-02 $(CFLAGS) XLDLIBS= -lXaw3d -lXt -lXmu -lXext -lX11 -lm BUFLIB=libbuf.a ########################################################### ## Miscellaneous INCLUDES=buf.h XINCLUDES=xtbuff_ad.h OBJS=buff.o buf_print.o xtbuff.o ########################################################### ## Just a 'make' generates a help message help:   Help         @echo "You can make the following:"         @echo " "         @echo " libbuf.a       -- the buffer library"         @echo " bufdisplay     -- display any-format buffer"         @echo " buf2ppm        -- convert buffer to pixmap" ########################################################### ## The main target is the library libbuf.a:  $(OBJS)     -/bin/rm libbuf.a     ar rv libbuf.a $(OBJS)     ranlib libbuf.a ########################################################### ## Secondary targets -- utilities built from the library bufdisplay: bufdisplay.c libbuf.a     $(CC) $(CCFLAGS) bufdisplay.c -o bufdisplay $(BUFLIB) $(XLDLIBS) buf2ppm: buf2ppm.c libbuf.a     $(CC) $(CCFLAGS) buf2ppm.c -o buf2ppm $(BUFLIB) ########################################################### ## Build the individual object units buff.o: $(INCLUDES) buff.c     $(CC) -c $(CCFLAGS) buff.c buf_print.o:$(INCLUDES) buf_print.c     $(CC) -c $(CCFLAGS) buf_print.c xtbuff.o: $(INCLUDES) $(XINCLUDES) xtbuff.c     $(CC) -c $(CCFLAGS) xtbuff.c


The make utility can be used for tasks other than compiling code. As a final example, assume that you have a database that lists IP addresses and the corresponding hostnames in two columns and that the database dumps these values to a file named hosts.tab. You need to extract only the hostnames from this file and generate a Web page named hosts.html containing these names. The following makefile is a simple report writer:

$ cat makefile # SHELL=/bin/bash # hosts.html: hosts.tab         @echo "<HTML><BODY>" > hosts.html         @awk '{print $$2, "<br>"}' hosts.tab >> hosts.html         @echo "</BODY></HTML>" >> hosts.html


man: Displays documentation for commands

man [options] [section] command

man k keyword

The man utility provides online documentation for Mac OS X commands. In addition to user commands, documentation is available for many other commands and details that relate to OS X. Because some OS X commands come from GNU, the GNU info utility (page 30) sometimes provides more complete information.

Each manual page begins with a one-line header. This header consists of a command name, the section of the manual in which the command is found, and a brief description of what the command does. These headers are stored in a database so that you can perform quick searches on keywords associated with each man page.

Arguments

The section argument tells man to limit its search to the specified section of the manual (see page 29 for a listing of manual sections). Without this argument, man searches the sections in numerical order and displays the first man page it finds. In the second form of the man command, the k option searches for the keyword in the database of man page headers; man displays a list of headers that contain the keyword. A man k command performs the same function as apropos (page 59).

Options

a

(all) Displays man pages for all sections of the manual. Without this option, man displays only the first page it finds. Use this option when you are not sure which section contains the information you are looking for.

k

keyword

 

(keyword) Displays manual page headers that contain the string keyword. You can scan this list for commands of interest. This option is equivalent to the apropos command (page 59).

K

keyword

 

(keyword search) Searches for keyword in all man pages. This option can take a long time to run.

M

path

 

(manpath) Searches the directories in path for man pages, where path is a colon-separated list of directories.

t

(troff) Formats the page for printing on a PostScript printer. The output goes to standard output.


Discussion

The manual pages are organized in sections, with each section pertaining to a separate aspect of the Mac OS X system. Section 1 contains user-callable commands and is most likely to be accessed by users who are not system administrators or programmers. Other sections of the manual describe system calls, library functions, and commands used by system administrators. See page 29 for a listing of the manual sections.

Pager

The man utility uses less to display manual pages that fill more than one screen. To change to another pager, set the environment variable PAGER to the pathname of the desired pager. For example, adding the following line to the ~/.bash_profile file allows a bash user to use more instead of less. Under OS X, less and more are both links to the same file, but they work slightly differently.

export PAGER=/usr/bin/more


MANPATH

You can tell man where to look for man pages by setting the environment variable MANPATH to a colon-separated list of directories. For example, bash users can add the following line to ~/.bash_profile to cause man to search the /usr/bin/man, /usr/share/man, and /usr/X11R6/man directories:

export MANPATH=/usr/bin/man:/usr/share/man:/usr/X11R6/man


As a privileged user, you can edit /usr/share/misc/man.conf to further configure man. Refer to the man man page for more information.

Notes

See page 28 for a discussion of man pages.

The argument to man is not always a command name. For example, the command man ascii lists the ASCII characters and their various representations; the command man k postscript lists man pages that pertain to PostScript.

The man pages are stored in an unformatted form. When you request a man page, it has to be formatted before being displayed.

Some utilities described in the manual pages have the same name as shell builtin commands. The behavior of the shell builtin may differ slightly from the behavior of the utility as described in the manual page. For information about shell builtins, see the man page for builtin or the man page for a specific shell.

References to man pages frequently use section numbers in parentheses; write(2) refers to the man page for write in section 2 of the manual (page 29).

Examples

The following example uses man to display the documentation for the command write, which sends messages to another user's terminal:

$ man write WRITE(1)              BSD General Commands Manual                  WRITE(1) NAME write -- send a message to another user SYNOPSIS      write user [ttyname] DESCRIPTION The write utility allows you to communicate with other users, by copying lines from your terminal to theirs. ...


The next example displays the man page for another commandthe man command itself, a good starting place for someone learning about the system:

$ man man man(1)                                                            man(1) NAME        man - format and display the on-line manual pages SYNOPSIS  man [-acdfFhkKtwW] [--path] [-m system] [-p string] [-C config_file]   [-M pathlist] [-P pager] [-S section_list] [section] name ... DESCRIPTION  man formats and displays the on-line manual pages. If you specify section,  man only looks in that section of the manual. name is normally  the name of the manual page, which is typically the name of a command,  function, or file. However, if name contains a slash (/) then man  interprets it as a file specification, so that you can do man ./foo.5  or even man /cd/foo/bar.1.gz. ...


The next example demonstrates how you can use the man utility to find the man pages that pertain to a certain topic. In this case man k displays man page headers containing the string latex. The apropos utility (a shell script stored in /usr/bin/apropos) functions similarly to man k.

$ man -k latex Pod::LaTeX(3pm)     - Convert Pod data to formatted Latex pod2latex(1)        - convert pod documentation to latex format


The search for the keyword entered with the k option is not case sensitive. The 3pm on the first line indicates that the man page is from section 3 (Subroutines) of the UNIX System Manual and comes from the Perl Programmers Reference Guide (it is a Perl subroutine; see www.perl.org for more information on the Perl programming language).

mkdir: Creates a directory

mkdir [option] directory-list

The mkdir utility creates one or more directories.

Arguments

The directory-list is a list of one or more pathnames of directories that mkdir creates.

Options

m

mode

 

(mode) Sets the permission to mode. You can specify the mode absolutely by using an octal number (page 677) or symbolically (see Table VI-3 on page 676).

p

(parents) Creates any directories that do not exist in the path to the directory you wish to create.

v

(verbose) Displays the name of each directory created. This option is helpful when used with the p option.


Notes

You must have permission to write to and search (execute permission) the parent directory of the directory you are creating. The mkdir utility creates directories that contain the standard invisible entries (. and ..).

Examples

The following command creates the accounts directory as a subdirectory of the working directory and the prospective directory as a subdirectory of accounts:

$ mkdir -p accounts/prospective


Without changing working directories, the same user creates another subdirectory within the accounts directory:

$ mkdir accounts/existing


Next the user changes the working directory to the accounts directory and creates one more subdirectory:

$ cd accounts $ mkdir closed


The last example shows the user creating another subdirectory. This time the m option removes all access permissions for the group and others:

$ mkdir -m go= accounts/past_due


mv: Renames or moves a file

mv [options] existing-file new-filename

mv [options] existing-file-list directory

mv [options] existing-directory new-directory

The mv utility, which renames or moves one or more files, has three formats. The first renames a single file with a new filename that you supply. The second renames one or more files so that they appear in a specified directory. The third renames a directory. The mv utility physically moves the file if it is not possible to rename it (that is, if you move the file from one filesystem [volume] to another).

Arguments

In the first form, the existing-file is a pathname that specifies the ordinary file that that mv is to rename. The new-filename is the new pathname of the file.

In the second form, the existing-file-list specifies the pathnames of the files that mv is to rename and the directory specifies the new parent directory for the files. The files you rename will have the same simple filenames as each of the files in the existing-file-list but new absolute pathnames.

The third form renames the existing-directory with the new-directory name. This form works only when the new-directory does not already exist.

Options

f

(force) Causes mv not to prompt you if a move would overwrite an existing file that you do not have write permission for. You must have write permission for the directory holding the target file.

i

(interactive) Prompts you for confirmation if mv would overwrite a file. If your response begins with a y or Y, mv overwrites the file; otherwise, mv does not move the file.

n

(no overwrite) Causes mv not to overwrite existing files, even if you have write permission for both the file and the directory holding it.

v

(verbose) Lists files as they are moved.


Notes

When mv copies a file to a different filesystem (volume), it first copies the existing-file to the new-file. It then deletes the existing-file. If the new-file already exists, mv may delete it before copying.

As with rm, you must have write and execute access permissions to the parent directory of the existing-file, but you do not need read or write access permission to the file itself. If the move would overwrite a file that you do not have write permission for, mv displays the file's access permissions and waits for a response. If you enter y or Y, mv overwrites the file; otherwise, it does not move the file. If you use the f option, mv does not prompt you for a response but simply overwrites the file.

Although earlier versions of mv could move only ordinary files between filesystems, mv can now move any type of file, including directories and device files.

Examples

The first command renames letter, a file in the working directory, as letter.1201:

$ mv letter letter.1201


The next command renames the file so that it appears, with the same simple filename, in the user's ~/archives directory:

$ mv letter.1201 ~/archives


The following command moves all files in the working directory whose names begin with memo so that they appear in the /p04/backup directory:

$ mv memo* /p04/backup


nice: Changes the priority of a command

nice [option] [command-line]

The nice utility reports the priority of the shell or alters the priority of a command. An ordinary user can decrease the priority of a command. Only Superuser can increase the priority of a command. The TC Shell includes a nice builtin that has a different syntax. Refer to "Notes" for more information.

Arguments

The command-line is the command line that nice is to execute at a different priority. Without any options or arguments, nice displays the priority of the shell running nice.

Options

Without an option, nice defaults to an adjustment of 10, lowering the priority of the command by 10typically from 0 to 10. As you raise the priority value, the command runs at a lower priority.

n

value

 

(nice) Changes the priority by the increment (or decrement) specified by value. The range of priorities is from 20 (the highest priority) to 20 (the lowest priority). A positive value lowers the priority, whereas a negative value raises the priority. Only Superuser can specify a negative value. When you specify a value outside this range, nice sets the priority to the limit of the range.


Notes

You can use renice (page 825) to change the priority of a running process.

Higher (more positive) priority values mean that the kernel schedules a job less often. Lower (more negative) values cause the job to be scheduled more often.

When Superuser schedules a job to run at the highest priority, this setting can affect the performance of the system for all other jobs, including the operating system itself. For this reason you should be careful when using nice with negative values.

tcsh

The TC Shell includes a nice builtin. Under tcsh, use the following syntax to change the priority at which command-line is run:

nice [±value] command line


The default priority is 4. You must include the plus sign for positive values.

Examples

The following command executes find in the background at the lowest possible priority. The ps l command displays the nice value of the command in the NI column:

# nice -n 20 find / -name '*.txt' -print > txtfiles.out & [1] 2610 #ps -l UID   PID PPID CPU PRI  NI  VSZ  RSS WCHAN  STAT  TT  TIME   COMMAND 501  9705 9701   0   31  0 27792  856 -      Ss    p1 0:00.15  -bash 501 10548 9705   0   12 20 27252  516 -      RN   p1 0:00.62 find  / 501   559  558   0   31  0 27792 1368 -       S    p2 0:00.02 -bash


The next command finds very large files and runs at a high priority (15):

# nice -n -15 find / -size +50000k


nidump: Displays contents of a NetInfo database

nidump database domain

The nidump (NetInfo dump) utility displays the contents of a NetInfo database.

Arguments

The database is the NetInfo database that nidump is to display. Table VI-18 lists the NetInfo databases. You must specify the domain, which is typically /, the default domain.

Table VI-18. NetInfo databases

aliases

group

protocols

bootparams

hosts

rpc

bootptab

networks

services

exports

passwd

 

fstab

printcap

 


Notes

The NetInfo databases hold the information that a traditional UNIX system stores in flat files with corresponding names in /etc. For example, the passwd and group databases specify the user and group account information stored in /etc/passwd and /etc/group on traditional UNIX systems.

The format of the passwd database under Mac OS X is different from that of the corresponding database under traditional UNIX. The OS X passwd database is kept in the 4.4BSD format, which adds three fields between the group ID (page 934) field and the user information or GECOS (page 934) field. The fields hold login class and account timestamp information that OS X does not use.

The nidump utility is useful for porting shell scripts that refer to traditional UNIX administration files. For example, if a script searches /etc/passwd for data, you can use nidump passwd / to list the records the script is looking for.

The nidump utility does not display encrypted passwords. Instead, it displays eight asterisks (********) in the password field or a single asterisk (*) if the account is disabled.

The lookupd daemon (page 455) provides consistent access to NetInfo databases, flat files, and other data sources. The nidump utility displays NetInfo databases only.

See page 441 for more information on NetInfo.

Examples

The first example displays the hosts database. This database is small because its only purpose is to allow the local system to look up names it may need before the network is configured. After that, lookupd passes these requests to DNS.

$ nidump hosts / 127.0.0.1       localhost 255.255.255.255 broadcasthost


The next example uses nidump to look at accounts that have the string root in their entries in the passwd database:

$ nidump passwd / | grep root root:********:0:0::0:0:System Administrator:/private/var/root:/bin/sh daemon:*:1:1::0:0:System Services:/var/root:/usr/bin/false


The final example displays the groups that have Alex as a member:

$ nidump group / | grep alex appserverusr:*:79:appserver,alex admin:*:80:root,alex appserveradm:*:81:appserver,alex alex:*:501:


nohup: Runs a command that keeps running after you log out

nohup command-line

The nohup utility executes a command line such that the command keeps running after you log out. In other words, nohup causes a process to ignore a SIGHUP signal. Depending on how the shell is configured, without nohup the shell may kill your background processes when you log out. The TC Shell includes a nohup builtin.

Arguments

The command-line is the command line that nohup is to execute.

Notes

Accepts the common options described on page 663.

If you do not redirect the output from a command that you execute using nohup, both standard output and standard error are sent to the file named nohup.out in the working directory. If you do not have write permission for the working directory, nohup sends output to ~/nohup.out.

Unlike the nohup utility, the TC Shell's nohup builtin does not send output to nohup.out. Background jobs started from tcsh continue to run after you log out.

Examples

The following command executes find in the background, using nohup:

$ nohup find / -name '*.txt' -print > txtfiles.out & [1] 14235


od: Dumps the contents of a file

od [options] [file-list]

The od (octal dump) utility dumps the contents of a file. Such a dump is useful for viewing executable (object) files and text files that include embedded nonprinting characters. This utility takes its input from the files you specify on the command line or from standard input.

Arguments

The file-list specifies the pathnames of the files that od dumps. When you do not specify a file-list, od reads from standard input.

Options

A

base

 

(address radix) Specifies the base used to display the offsets shown for positions in the file. By default offsets are given in octal. Possible values for base are d (decimal), o (octal), x (hexadecimal), and n (no offsets displayed).

j

n

 

(jump) Skips n bytes before displaying data.

N

n

 

(maximum) Reads a maximum of n bytes and quits.

t

type [n]

 

Specifies the output format to use when displaying data from a file. You can repeat this option with different format types to see the file in several different formats. Table VI-19 lists the possible values for type.

 

By default od dumps a file as 2-byte octal numbers. You can specify the number of bytes od uses to compose each number by specifying a length indicator, n. You can specify a length indicator for all types except a and c. Table VI-21 lists the possible values of n.


Table VI-19. Output formats

type

Output format

a

Named character. Displays nonprinting control characters using their official ASCII names. For example, FORMFEED is displayed as ff.

c

ASCII character. Displays nonprinting control characters as backslash escape sequences (Table VI-20, next page) or three-digit octal numbers.

d

Signed decimal.

f

Floating point.

o

Octal (default).

u

Unsigned decimal.

x

Hexadecimal.


Table VI-20. Output format type c backslash escape sequences

Sequence

Meaning

\0

NULL

\a

BELL

\b

BACKSPACE

\n

NEWLINE

\r

RETURN

\t

HORIZONTAL TAB

\v

VERTICAL TAB


Table VI-21. Length indicators

n

 

Number of bytes to use

Integers (types d, o, u, and x)

  

C

(character)

Uses single characters for each decimal value

S

(short integer)

Uses 2 bytes

I

(integer)

Uses 4 bytes

L

(long)

Uses 4 bytes

Floating point (type f)

  

F

(float)

Uses 4 bytes

D

(double)

Uses 8 bytes

L

(long double)

Uses 16 bytes


Notes

To retain backward compatibility with older, non-POSIX versions of od, the od utility includes the options listed in Table VI-22 as shorthand versions of many of the preceding options.

Table VI-22. Shorthand format specifications

Shorthand

Equivalent specification

a

t a

b

t o1

c

t c

f

t fF

h

t x2

i

t dI

l

t dL

o

t o2

x

t x2


Examples

The file ac, which is used in the following examples, contains all of the ASCII characters. In the first example, the bytes in this file are displayed as named characters. The first column shows the offset of each byte from the start of the file. The offsets are given as octal values.

$ od -t a ac 0000000  nul  soh stx  etx  eot  enq ack bel  bs ht  nl  vt ff cr so  si 0000020  dle  dc1 dc2  dc3  dc4  nak syn etb can em sub esc fs gs rs  us 0000040   sp    !   "    #    $    %   &   '   (  )   *   +  ,  -  .   / 0000060    0    1   2    3    4    5   6   7   8  9   :   ;  <  =  >   ? 0000100    @    A   B    C    D    E   F   G   H  I   J   K  L  M  N   O 0000120    P    Q   R    S    T    U   V   W   X  Y   Z   [  \  ]  ^   _ 0000140    `    a   b    c    d    e   f   g   h  i   j   k  l  m  n   o 0000160    p    q   r    s    t    u   v   w   x  y   z   {  |  }  ~ del 0000200   80   81  82   83   84   85  86  87  88 89  8a  8b 8c 8d 8e  8f ... 0000360   f0   f1  f2   f3   f4   f5  f6  f7  f8 f9  fa  fb fc fd fe  ff 0000400   nl 0000401


The next example displays the bytes as octal numbers, ASCII characters, or printing characters preceded by a backslash (refer to Table VI-20 on page 800):

$ od -t c ac 0000000  \0 001 002 003 004 005 006  \a  \b  \t  \n  \v  \f  \r 016 017 0000020 020 021 022 023 024 025 026 027 030 031 032 033 034 035 036 037 0000040       !   "   #   $   %   &   '   (   )   *   +   ,   -   .   / 0000060   0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ? 0000100   @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O 0000120   P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _ 0000140   `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o 0000160   p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~ 177 0000200 200 201 202 203 204 205 206 207 210 211 212 213 214 215 216 217 ... 0000360 360 361 362 363 364 365 366 367 370 371 372 373 374 375 376 377 0000400  \n 0000401


The final example uses od to display the beginning of a file's resource fork (page 93). In some cases, information in the resource fork will give insight into the file's origins or contents. In this case, the file has been manipulated by the Graphic Converter application, a popular shareware image converter.

$ od -t c picture.jpg/..namedfork/rsrc | head 0000000      \0  \0 001  \0  \0 002   $   T  \0 002   #   T  \0  \0  \0 372 0000020      \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0 * 0000400      \0  \0  \0 021 020   G   r   a   p   h   i   c   C   o   n   v 0000420       e   r   t   e   r  \0  \0  \0   ! 005     200  \0  \0  \0 003 0000440       5   .   2 026   (   f   o   r      G    r   a   p   h   i   c 0000460       C   o   n   v   e   r   t   e   r   )  \0  \0   _  \0   i   c 0000500       n   s  \0  \0   _  \0   i   c   h   #  \0  \0 002   H 377 377 0000520     377 377 376  \0 356 356 356 356 357  \0 335 335 335 335 336 200 0000540     340  \0  \0  \0 002   @ 240   B 022   " 002     322 001     201


The line with only an asterisk (*) indicates a series of identical lines.

open: Opens files, directories, and URLs

open [option] [file-list]

The open utility opens one or more files, directories, or URLs.

Arguments

The file-list specifies the pathnames of one or more files, directories, or URLs that open is to open.

Options

Without any options, open opens the files in file-list as though you had double-clicked each of the files' icons in the Finder.

a application

 

Opens file-list using application. Equivalent to dragging file-list to the application's icon in the Finder.

b bundle

 

Opens file-list using the application with bundle identifier bundle. A bundle identifier is a string, registered with the system, that identifies an application that can open files. For example, the bundle identifier com.apple.TextEdit specifies the TextEdit editor.

e

(edit) Opens file-list using the TextEdit application.

t

(text) Opens file-list using the default text editor (see "Discussion").

f

(file) Opens standard input as a file in the default text editor. Does not accept file-list.


Discussion

Opening a file brings up the application associated with that file. For example, opening a disk image file mounts it. The open command returns immediately, without waiting for the application to launch.

LaunchServices is a system framework that identifies applications that can open files. It maintains lists of available applications and user preferences about which application to use for each file type. LaunchServices also keeps track of the default text editor used by the t and f options.

Some options are not available under Mac OS X 10.3 and earlier.

Notes

When a file will be opened by a GUI application, you must run open from Terminal or another terminal emulator that is running under a GUI; otherwise the operation will fail.

Examples

The first example mounts the disk image file backups.dmg. The disk is mounted in /Volumes, using the name it was formatted with.

$ ls /Volumes House Spare Tiger $ open backups.dmg $ ls /Volumes Backups   House    Spare   Tiger


The next command opens the file picture.jpg. You must run this and the following example from a textual window within a GUI (e.g., Terminal). The application selected depends on the file attributes. If the file's type and creator code specify a particular application, open opens the file using that application. Otherwise, open uses the system's default program for handling .jpg files.

$ open picture.jpg


The final example opens the /usr/bin directory in the Finder. The /usr directory is normally hidden from the Finder because its invisible file attribute flag (page 95) is set. However, the open command can open any file you can access from the shell, even if it is not normally accessible from the Finder.

$ open /usr/bin


otool: Displays object, library, and executable files

otool options file-list

The otool utility displays information about, or part of, object, library, and executable files.

Arguments

The file-list specifies the pathnames of one or more files that otool is to display.

Options

You must use at least one of the L, M, t, or T options to specify which part of each file in file-list otool is to display.

L

(libraries) Displays the names and version numbers of the shared libraries an object file uses.

M

(module) Displays the module table of a shared library.

p

name

 

(print) Begins output at the symbol named name. Requires the t option and either the v or V option.

t

(text) Displays the TEXT section of an object file.

T

(table of contents) Displays the table of contents of a shared library.

v

(verbose) Displays data symbolically. When displaying code, this option causes otool to display the names of instructions instead of numeric codes.

V

(very verbose) Displays even more data symbolically. When displaying code, this option causes otool to display the names of called routines instead of their addresses.


Discussion

The otool utility displays information about the contents and dependencies of object files. You can use this information to help debug a program. For example, when setting up a chroot jail (page 461), otool can report which libraries are needed to run a given program.

Some options are useful only with some types of object modules. For example, the T option does not report anything for a typical executable file.

Notes

An otool L command performs a function similar to the ldd utility on systems using the ELF binary format.

Examples

The examples in this section use the compiled version of the following C program:

$ cat myname.c #include <stdio.h> int main(void) { printf("My name is Peter.\n"); return 0; }


In the first example, otool displays the libraries the program is linked with:

$ otool -L myname myname:     /usr/lib/libmx.A.dylib (compatibility version 1.0.0, current version 92.0.0)     /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.0.0)


In some cases, a library used by a program will depend on other libraries. You can use otool -L on a library to see whether it uses other libraries:

$ otool -L /usr/lib/libmx.A.dylib /usr/lib/libSystem.B.dylib /usr/lib/libmx.A.dylib:     /usr/lib/libmx.A.dylib (compatibility version 1.0.0, current version 92.0.0)     /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.0.0) /usr/lib/libSystem.B.dylib:     /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.0.0)     /usr/lib/system/libmathCommon.A.dylib (compatibility version 1.0.0, current ...


The next example disassembles the code for the main function. When compiling programs, the compiler sometimes modifies symbol names. The compiler gives functions, such as main, a leading underscore, so the symbol name is _main.

$ otool -Vt -p _main myname myname: (__TEXT,__text) section _main: 00002ac0        mfspr   r0,lr 00002ac4        stmw    r30,0xfff8(r1) 00002ac8        stw     r0,0x8(r1) 00002acc        stwu    r1,0xffb0(r1) 00002ad0        or      r30,r1,r1 00002ad4        bcl     20,31,0x2ad8 00002ad8        mfspr   r31,lr 00002adc        addis   r2,r31,0x0 00002ae0        addi    r3,r2,0x4b8 00002ae4        bl      _printf$LDBLStub 00002ae8        li      r0,0x0 00002aec        or      r3,r0,r0 00002af0        lwz     r1,0x0(r1) 00002af4        lwz     r0,0x8(r1) 00002af8        mtspr   lr,r0 00002afc        lmw     r30,0xfff8(r1) 00002b00        blr ...


paste: Joins corresponding lines from files

paste [option] [file-list]

The paste utility reads lines from the file-list and joins corresponding lines in its output. By default, output lines are separated by a TAB character.

Arguments

The file-list specifies the pathnames of one or more ordinary files. When you omit the file-list, paste reads from standard input.

Options

d

dlist

 

(delimiter) The dlist is a list of characters that will be used to separate the output fields. If dlist contains a single character, paste uses that character instead of the default TAB character to separate fields. If dlist contains more than one character, the characters are used in turn to separate output fields and are then reused from the beginning of the list as necessary.

s

(serial) Processes one file at a time; pastes horizontally. See "Examples."


Notes

A common use of paste is to rearrange the columns of a table. A utility, such as cut, can place the desired columns in separate files, and then paste can join them in any order.

Examples

The following example uses the files fnames and acctinfo. These files can easily be created by using cut (page 699) and nidump (page 796). The paste command puts the full-name field first, followed by the remaining user account information. A TAB character separates the two output fields.

$ cat fnames Jenny Chen Alex Watson Sam Adams Helen Simpson $ cat acctinfo jenny:********:501:501::0:0:/Users/jenny:/bin/zsh alex:********:502:502::0:0:/Users/alex:/bin/bash sam:********:504:504::0:0:/Users/sam:/bin/tcsh hls:********:505:505::0:0:/Users/hls:/bin/bash $ paste fnames acctinfo Jenny Chen         jenny:********:501:501::0:0:/Users/jenny:/bin/zsh Alex Watson        alex:********:502:502::0:0:/Users/alex:/bin/bash Sam Adams        sam:********:504:504::0:0:/Users/sam:/bin/tcsh Helen Simpson      hls:********:505:505::0:0:/Users/hls:/bin/bash


The next examples use the files p1, p2, p3, and p4. The last example in this group uses the d option to give paste a list of characters to use to separate output fields.

$ cat p1 1 one ONE $ cat p2 2 two TWO extra $ cat p3 3 three THREE $ cat p4 4 four FOUR $ paste p4 p3 p2 p1 4          3       2       1 four       three   two     one FOUR       THREE   TWO     ONE                    extra $ paste -d "+-=" p3 p2 p1 p4 3+2-1=4 three+two-one=four THREE+TWO-ONE=FOUR +extra-=


The final example uses the s option to paste the files one at a time:

$ paste -s p1 p2 p3 p4 1          one     ONE 2          two     TWO         extra 3          three   THREE 4          four    FOUR


pax: Creates an archive, restores files from an archive, or copies a directory

pax [options] [pattern-list]

pax w [options] [source-files]

pax r [options] [pattern-list]

pax rw [options] destination-directory

The pax utility has four modes of operation: List mode displays the list of files in an archive, Create mode places multiple files into a single archive file, Extract mode restores files from an archive, and Copy mode makes a copy of a directory hierarchy. The archive files created by pax may be saved on disk, removable media, or a remote system.

List mode (no major options) reads an archive from standard input and displays the list of the files stored in the archive. Create mode (w for write) reads a list of ordinary or directory filenames from the command line or standard input and writes the resulting archive file to standard output. Extract mode (r for read) reads an archive from standard input and extracts files from that archive. Copy mode (rw) reads a list of ordinary or directory filenames from the command line or standard input and copies the files to an existing directory.

Arguments

In Create mode pax reads the names of files that will be included in the archive from source-files on the command line. If source-files is not present, pax reads the names from standard input.

In Extract mode pax extracts, and in List mode it displays the names of, all files found in the archive that it reads from standard input. You can choose to extract or display the names of files selectively by supplying a pattern-list. If the name of a file in the archive matches a pattern in the pattern-list, that file is extracted; otherwise, it is ignored. The pax patterns are similar to shell wildcards (page 133) except that they match slashes (/) and a leading period (.) in a filename. See the fnmatch man page for more information on pax patterns.

The pax utility does not create destination-directory in Copy mode. Instead, the destination-directory must exist before you give pax a Copy mode command.

Options

A major option specifies the mode in which pax operates: Create, Extract, or Copy. You can omit the other options.

Major Options

Three options determine the mode in which pax operates. You must include none or one of these options. Without a major option, pax runs in List mode.

r

(read) Puts pax in Extract mode, in which it reads the archive from standard input and extracts files. Without a pattern-list on the command line, pax exTRacts all files from the archive. With a pattern-list, pax exTRacts only those files with names that match one of the patterns in the pattern-list. The following example extracts from the root.pax archive file on an external drive only those files whose names end in .c:

$ pax -r \*.c < /Volumes/Backups/root.pax


 

The backslash prevents the shell from expanding the * before it passes the argument to pax.

w

(write) Puts pax in Create mode, in which it constructs an archive from the files named on the command line or standard input. These files may be ordinary or directory files, and each must appear on a separate line. The archive is written to standard output. The find utility frequently generates the filenames that pax uses. The following command builds an archive of the /Users directory and writes it to the archive file named Users.pax on /Volumes/Backups:

[View full width]

# find -d /Users -print | pax -w > /Volumes /Backups/Users.pax


 

The d option causes find to search for files in a depth-first manner, reducing the likelihood of permissions problems when you restore the files from the archive. See the discussion of this find option on page 696.

rw

(copy) Puts pax in Copy mode, in which it copies files named on the command line or standard input from one place on the system to another. Instead of constructing an archive file containing the files named on standard input, pax copies them into the destination-directory (the last argument on the pax command line). The effect is the same as if you had created an archive in Create mode and then extracted the files in Extract mode, except that using Copy mode avoids creating an archive.

 

The following example copies the working directory hierarchy into /Users/alex/code. The code directory must exist before you give this command. Make sure that ~alex/code is not a subdirectory of the working directory or you will perform a recursive copy.

$ pax -rw. ~alex/code



Other Options

The options listed in this section alter the behavior of pax.

c

(complement) Reverses the sense of the test done on pattern-list. Files are listed or put in the archive only if they do not match any of the patterns in pattern-list.

f

archive

 

(file) Uses archive as the name of the archive file. In List and Extract modes, reads from archive instead of standard input. In Create mode, writes to archive instead of standard output. You can use this option to access a device on another system on a network; see the --file option to tar (page 863) for more information.

H

(dereference) Copies the files that symbolic links given on the command line point to, not the symbolic links themselves. Does not copy the files that symbolic links found while descending a directory hierarchy point to.

l

(link) In Copy mode, when possible, makes hard links instead of copying files.

L

(dereference) Copies the files that symbolic links point to, not the symbolic links themselves. Includes the files that symbolic links found while descending a directory hierarchy point to.

P

(no dereference) Copies symbolic links, not the files that the links point to (default).

p

preserve-list

 

Preserves or discards the file attributes specified by preserve-list. The preserve-list is a string of one or more letters as shown in Table VI-23. By default pax preserves file access and modification times but does not preserve ownership or file permissions. This option works in Extract and Copy modes only.


Table VI-23. Preserve flags

Letter

Meaning

a

Discard access time

e

Preserve everything

m

Discard modification time

o

Preserve ownership

p

Preserve permissions


s

subcmd

 

Executes subcmd, a substitution command, on filenames while storing them in any of the modes. The subcmd has the following format:

s/search-string/replacement-string/[gp]


 

The pax utility replaces occurrences of the regular expression search-string with replacement-string. A trailing g indicates a global replacement; without it only the first instance of search-string in each filename is replaced. The p causes pax to display each substitution it makes. The subcmd is similar to vim's search and replace feature described on page 172, except that it lacks an address.

v

(verbose) In List mode, displays output similar to that produced by ls l. In other modes, displays a list of files being processed.

X

In Copy and Create modes, prevents pax from searching directories in filesystems other than the filesystem(s) that hold the files it was explicitly told to copy.

x

format

 

In Create mode, writes the archive in format format, as shown in Table VI-24. If you do not specify a format, pax writes a (POSIX) tar format file.

z

(gzip) In Create mode, compresses archives with gzip. In Extract mode, decompresses archives with gunzip.


Table VI-24. Archive formats

format

Description

cpio

The format specified for cpio archives in POSIX

sv4cpio

The format used for cpio archives under UNIX System V, release 4

tar

The historical Berkeley tar format (default)

ustar

The POSIX tar format


Discussion

The pax utility is a general replacement for tar, cpio, and other archive programs.

In Create and Copy modes, pax processes specified directories recursively. In List and Extract modes, if a pattern in pattern-list matches a directory name, pax lists or extracts the files from the named directory.

Notes

There is no native pax format. Instead, the pax utility can read and write archives in a number of formats. By default it creates POSIX tar format archives. See Table VI-24 for a list of formats supported by pax.

The pax utility determines the format of an archive file; it does not allow you to specify an archive format (x option) in List or Extract mode.

Under Mac OS X version 10.4 and later, pax archives extended attributes (page 93). Under version 10.3 and earlier, pax does not archive extended attributes. Under version 10.3 and earlier, you can use ditto (page 715) to copy files with their extended attributes.

Examples

In the first example, pax creates an archive named corres.0901.pax. This archive stores the contents of the corres directory.

$ pax -w corres > corres.0901.pax


The w option puts pax in Create mode, where the list of files to be put in an archive is supplied by command line arguments (corres in the preceding example) or from standard input. The pax utility sends the archive to standard output. The preceding example redirects that output to a file named corres.0901.pax.

Next without any options, pax displays a list of files in the archive it reads from standard input:

$ pax < corres.0901.pax corres corres/hls corres/max corres/max/0823 corres/max/0828 corres/max/0901 corres/memo1 corres/notes


The following command uses the f option to name the input file and performs the same function as the preceding command:

$ pax -f corres.0901.pax


When pax reads an archive file, as in the previous examples, it determines the format of the fileyou do not have to (nor are you allowed to) specify the format.

The next example attempts to create an archive of the /etc directory hierarchy in the default tar format. In this case pax is run by a user with root privileges because some of the files in this hierarchy cannot be read by ordinary users. Because pax does not follow (dereference) symbolic links by default, and because /etc is a symbolic link, pax copies the link and not the directory that the link points to. The first command creates the archive; the second command shows the link in the archive; and the third command uses the v option to show that it is a link:

# pax -w -f /tmp/etc.tar /etc # pax -f /tmp/etc.tar /etc # pax -v -f /tmp/etc.tar lrwxr-xr-x         1 root     admin         0 May 21 01:48 /etc => private/etc pax: ustar    vol 1, 1 files, 10240 bytes read, 0 bytes written.


The L option follows (dereferences) links. In the next example, pax creates the desired archive of /etc:

# pax -wLf /tmp/etc.tar /etc # pax -f /tmp/etc.tar /etc /etc/6to4.conf /etc/AFP.conf /etc/afpovertcp.cfg /etc/aliases /etc/aliases.db /etc/amavisd.conf /etc/amavisd.conf.personal /etc/appletalk.cfg ...


The next example uses pax to create a backup of the memos directory, preserving ownership and file permissions. The destination directory must exist before you give pax a Copy mode command.

$ mkdir memos.0625 $ pax -rw -p e memos memos.0625 $ ls memos.0625 memos


The preceding example copies the memos directory into the destination directory. You can use pax to make a copy of a directory in the working directory without putting it in a subdirectory. In the next example, the s option causes pax to replace the name of the memos directory with the name . (the name of the working directory) as it writes files to the memos.0625 directory:

$ pax -rw -p e -s /memos/./ memos memos.0625


The final example uses find to build a list of files that begin with the string memo and that are located in the working directory hierarchy. The pax utility writes these files to an archive in the historical cpio format. The output from pax goes to standard output, which is sent through a pipe to bzip2, which in turn compresses it before writing it to the archive file.

$ find. -type f -name "memo*" | pax -w -x cpio | bzip2 > memos.cpio.bz2


plutil: Manipulates property list files

plutil [options] file-list

The plutil utility converts property list files (page 453) between formats and checks their syntax.

Arguments

The file-list specifies the pathnames of one or more files that plutil is to manipulate.

Options

convert format

 

Converts file-list to format, which must be either xml1 or binary1.

e extension

 

Gives output files a filename extension of extension.

help

 

Displays a help message.

lint

 

Checks the syntax of files (default).

o file

 

(output) Names the converted file file.

s

(silent) Does not display any messages for successfully converted files.


Discussion

The plutil utility converts files from the XML property list format to binary format, and vice versa. The plutil utility can read, but not write, the older plain-text property list format.

Notes

Refer to "Property List Files" on page 453 for a discussion of property list formats and more examples of the use of plutil.

The plutil utility accepts -- to mark the end of the options on the command line. For more information refer to "Common Options" on page 663

Examples

The following example checks the syntax of the file named java.plist.

$ plutil java.plist java.plist: OK


The next example shows the output of plutil as it checks a damaged property list file:

$ plutil broken.plist broken.plist: XML parser error:     Encountered unexpected element at line 2 (plist can only include one object) Old-style plist parser error:     Malformed data byte group at line 1; invalid hex


The next example converts the file StartupParameters.plist to binary format, overwriting the original file:

$ plutil -convert binary1 StartupParameters.plist


The final example converts the binary format property list file loginwindow.plist in the working directory to XML format and, because of the o option, puts the converted file in /tmp/lw.p:

$ plutil -convert xml1 -o /tmp/lw.p loginwindow.plist


pr: Paginates files for printing

pr [options] [file-list]

The pr utility breaks files into pages, usually in preparation for printing. Each page carries a header with the name of the file, date, time, and page number.

The pr utility takes its input from files you specify on the command line or from standard input. The output from pr goes to standard output and is frequently redirected by a pipe to a printer.

Arguments

The file-list specifies the pathnames of one or more text files that pr is to paginate. When you omit the file-list, pr reads from standard input.

Options

col

 

(columns) Displays the output in col columns with a default of one. This option may truncate lines and cannot be used with the m option.

d

(double-space) Double-spaces the output.

F

(formfeed) Uses a FORMFEED character to skip to the next page rather than filling the current page with NEWLINE characters.

h head

 

(header) Displays head at the top of each page instead of the filename. If head contains SPACEs, you must enclose it within quotation marks.

l lines

 

(lines) Sets the page length to lines lines. The default is 66 lines.

m

(merge) Displays all specified files simultaneously in multiple columns. This option cannot be used with the col option.

n [c[num]]

 

(number) Numbers the lines of output. The c is a character that pr appends to the number to separate it from the contents of the file (the default is a TAB). The num specifies the number of digits in each line number (the default is 5).

o spaces

 

(indent) Indents the output by spaces characters (specifies the left margin).

s[c]

 

(separate) Separates columns with the single character c (defaults to TAB when you omit c). By default pr uses SPACEs to align columns, padding them to a constant width.

t

(no trailer) Causes pr not to display its five-line page header and trailer. The header that pr normally displays includes the name of the file, the date, time, and page number. The trailer is five blank lines.

w num

 

(width) Sets the page width to num columns. This option is effective only with multicolumn output (the m or c option).

+firstpage

 

(start at) Output begins with the page numbered firstpage and runs through the last page of the document. This option begins with a plus sign, not a hyphen.


Notes

When you use the col option to display the output in multiple columns, pr displays the same number of lines in each column (with the possible exception of the last column).

Examples

The first command shows pr paginating a file named memo and sending its output through a pipe to lpr for printing:

$ pr memo | lpr


Now memo is sent to the printer again, this time with a special heading at the top of each page. The job is run in the background.

$ pr -h 'MEMO RE: BOOK' memo | lpr & [1] 4904


Finally pr displays the memo file on the screen, without any header, starting with page 3:

$ pr -t +3 memo ...


ps: Displays process status

ps [options]

The ps utility displays status information about processes running on the local system.

Options

The ps utility accepts options without a leading hyphen for compatibility with the historical BSD ps utility. Without any options, ps reports on processes that you own. Unless you specify otherwise, ps sorts output by controlling terminal and then by PID number.

a

(all) Reports on all processes that are controlled by a terminal.

A

(all) Reports on all processes including those without a controlling terminal. Equivalent to ax.

e

(environment) Appends to the COMMAND field the environment of each process.

l

(long) Displays a lot of information about the processes. (See Table VI-26.)

u

(user oriented) For each process, displays the username of the user running the process, the time the process was started, the percentage of CPU and memory the process is using, and other information. The output is sorted by CPU usage.

U

username

 

(user) Reports on processes being run by username, a user on the local system.

w

(wide) Extends the display to 132 characters. A second w option causes ps to display complete lines, regardless of their length. Without this option, ps truncates output lines at the right side of the screen.

x

(extended) Reports on processes that you own, including those without a controlling terminal.


Discussion

Without any options, ps displays the statuses of all active processes that your terminal controls. Table VI-25 lists the heading and content of each of the five columns that ps displays when you call it without any options.

Table VI-25. Column headings I

Heading

Meaning

PID

The process identification number.

TT (terminal)

The name of the terminal that controls the process.

STAT

The current state of the process (see Table VI-26 for more information on this column).

TIME

The number of hours, minutes, and seconds the process has been running.

COMMAND

The command line the process was called with. The command is truncated to fit on one line. Use the w option to display more of the command line.


The columns that ps displays depend on your choice of options. Table VI-26 lists the headings and contents of the most common columns.

Table VI-26. Column headings II

Heading

Meaning

%CPU

The percentage of total CPU time that the process is using. Because of the way that OS X handles process accounting, this figure is approximate and the total of this column may exceed 100%.

%MEM (memory)

The percentage of RAM that the process is using. This value is approximate.

COMMAND

The command line the process was called with. The command is truncated to fit on one line. Use the w option to see more of the command line. This column is always displayed last on a line.

FLAGS

The flags associated with the process.

NI

nice value (priority).

PID

The process identification number.

PPID (parent PID)

The process identification number of the parent process.

PRI (priority)

The priority of the process.

RSS (resident set size)

The number of blocks of memory that the process is using.

STARTED

The time and date the process started.

STAT (status)

The status of the process as specified by one or more letters from the following list:

<

High priority

I

Idle (sleeping > ~20 seconds)

L

Pages locked in memory (real-time and custom I/O)

N

Low priority

R

Available for execution (in the run queue)

S

Sleeping (sleeping < ~20 seconds)

s

Session leader

T

Stopped

U

Sleeping and cannot be interrupted

W

Has no pages resident in RAM (swapped out)

X

Being traced or debugged

Z

Zombie process that is waiting for its child processes to terminate before it terminates


TIME

The number of minutes and seconds that the process has been running.

TT (terminal)

The name of the terminal controlling the process.

USER or UID

The username of the user who owns the process.

WCHAN (wait channel)

If the process is waiting for an event, the address of the kernel function that caused the process to wait. It is for processes that are not waiting or are sleeping.


Notes

Use top (page 874) to display process status information dynamically.

Examples

The first example shows ps, without any options, displaying the user's process that is running the shell (bash):

$ ps      PID TT STAT    TIME COMMAND    10607 p3 Ss   0:00.79 -bash


With the l (long) option, ps displays more information about the processes:

$ ps -l UID   PID  PPID CPU PRI NI      VSZ  RSS WCHAN STAT TT        TIME COMMAND 502 10607 10603    0  31  0    27800  912 -      Ss  p3      0:00.79 -bash


The u option shows various types of information about the process, including how much of the local system CPU time and memory it is using:

$ ps -u USER   PID %CPU %MEM      VSZ    RSS  TT  STAT STARTED     TIME COMMAND alex 10607   0.0 -0.0    27800    908  p3  Ss   10:16PM   0:00.79 -bash


ps and kill

The next sequence of commands shows how to use ps to determine the PID number of a process running in the background and how to terminate that process by using the kill command. In this case it is not necessary to use ps because the shell displays the PID number of the background processes. The ps utility verifies the PID number.

The first command executes find in the background. The shell displays the job and PID numbers of the process, followed by a prompt.

$ find ~ -name memo -print > memo.out & [1] 16292


Next ps confirms the PID number of the background task. If you did not already know this number, ps offers an easy way to discover it.

$ ps      PID TT STAT     TIME COMMAND    10607 p3 Ss    0:00.80 -bash    16292 p3 U     0:01.12 find ~ -name memo -print


Finally kill (page 761) terminates the process:

$ kill 16292 $ RETURN [1]+    Terminated               find ~ -name memo -print >memo.out $


rcp: Copies one or more files to or from a remote system

rcp [options] source-file destination-file

rcp [options] source-file-list destination-directory

The rcp utility copies one or more ordinary files between two systems that can communicate over a network.

Security: rcp is not secure

The rcp utility uses host-based trust, which is not secure, to authorize files to be copied. Use scp (page 832) instead.


Arguments

The source-file, source-file-list, and destination-file specify pathnames of ordinary files, and the destination-directory specifies the pathname of a directory file. A pathname that does not contain a colon (:) identifies a file on the local system. A pathname of the form name@host:path specifies a file on the remote system named host. The path is relative to the home directory of the user name (unless path is an absolute pathname). When you omit the name@ portion of the destination, a relative pathname is relative to the home directory on the host of the user giving the rcp command.

Like cp, rcp has two modes of operation: The first copies one file to another file, and the second copies one or more files to a directory. The source-file[-list] is a list of the name(s) of the file(s) that rcp will copy; destination-file is the name that rcp assigns to the resulting copy of the file, or destination-directory is the name of the directory that rcp puts the copied files in. When rcp copies files to a destination-directory, the files maintain their original simple filenames.

Options

p

(preserve) Sets the modification time and file access permissions of each copy to match those of the source-file. When you do not use p, rcp uses the file-creation mask (umask; see page 883) on the remote system to modify the access permissions.

r

(recursive) When a file in the source-file-list is a directory, copies the contents of that directory and any subdirectories into the destination-directory. You can use this option only when the destination is a directory.


Notes

You must have an account on the remote system to copy files to or from it using rcp. The rcp utility does not prompt for a password but uses several alternative methods to verify that you have the authority to read or write files on the remote system.

One method requires that the name of the local system be specified in the /etc/hosts.equiv file on the remote system. If the name is there, rcp allows you to copy files if your usernames are the same on both systems and your account on the remote system has the permissions necessary to access files there.

Authorization can also be specified on a per-user basis. With this method, the remote user's home directory must contain a file named ~/. rhosts that lists trusted remote systems and users. Your local and remote usernames do not have to match in this case, but your local username must appear on the line in the remote ~/.rhosts file that starts with the name of the local system. See "Examples" for rlogin (page 826) for a sample .rhosts file.

If you use a wildcard (such as *) in a remote pathname, you must quote the wildcard character or pathname so that the wildcard is interpreted by the shell on the remote system and not by the local shell. As with cp, if the destination-file exists before you execute rcp, rcp overwrites the file.

For security reasons, the rcp service is not enabled by default on Mac OS X systems. Even without the service enabled, you can use rcp to connect to remote systems that provide an rcp service.

Examples

The first example copies the files with filenames ending in .c into the archives directory on the remote system named bravo. Because a username is not specified, rcp uses the local user's username on the remote system. Because the full pathname of the archives directory is not specified, rcp assumes that it is a subdirectory of the user's home directory on bravo. Each of the copied files retains its simple filename.

$ rcp *.c bravo:archives


The next example copies memo from the /Users/jenny directory on bravo to the working directory on the local system:

$ rcp bravo:/Users/jenny/memo .


Next rcp copies the files named memo.new and letter to Jenny's home directory on the remote system bravo. The absolute pathnames of the copied files on bravo are /Users/jenny/memo.new and /Users/jenny/letter:

$ rcp memo.new letter bravo:/Users/jenny


The final command copies all the files in Jenny's reports directory on bravo to the oldreports directory on the local system, preserving the original modification dates and file access permissions on the copies:

$ rcp -p 'bravo:reports/*' oldreports


renice: Changes the priority of a process

renice priority process-list

renice n increment process-list

The renice utility alters the priority of a running process. An ordinary user can decrease the priority of a process that he owns. Only Superuser can increase the priority of a process or alter the priority of another user's process.

Arguments

The process-list specifies the PID numbers of the processes that are to have their priorities altered. Each process has its priority set to priority or, in the second format, has its priority incremented by a value of increment (which can be negative).

Options

The options, which you can specify throughout process-list, change the interpretation of the arguments that follow them on the command line.

p

(process) Interprets the following arguments as process ID (PID) numbers.

u

(user) Interprets the following arguments as usernames or user ID numbers.


Notes

The range of priorities is from -20 (the highest priority) to +20 (the lowest priority). Higher (more positive) priority values mean that the kernel schedules a job less often. Lower (more negative) values cause the job to be scheduled more often.

When Superuser schedules a job to run at the highest priority, this change can affect the performance of the system for all other jobs, including the operating system itself. For this reason you should be careful when using renice with negative values.

See nice (page 794) if you want to start a process with a nondefault priority.

Examples

The first example decreases the priority of all tasks owned by Alex:

$ renice -n 5 -u alex


Following, root uses ps to check the priority of the process running find. The NI (nice) column shows a value of 19 and the administrator decides to increase the priority by 5:

#ps -l UID   PID PPID CPU PRI NI      VSZ     RSS WCHAN  STAT  TT      TIME COMMAND 501  9705 9701   0  31  0     27792     856 -      Ss    p1    0:00.15 -bash 501 10548 9705   0  12 19     27252    516 -      RN    p1    0:00.62 find / # renice -n -5 10548


rlogin: Logs in on a remote system

rlogin [option] remote-system

The rlogin utility establishes a login session on a remote system over a network.

Security: rlogin is not secure

The rlogin utility uses host-based trust, which is not secure, to authorize your login. Alternatively, it sends your password over the network as cleartext, which is not a secure practice. Use ssh (page 847) when it is available.


Arguments

The remote-system is the name of a system that the local system can reach over a network.

Options

l

username

 

(login) Logs you in on the remote system as the user specified by username.


Notes

If the file named /etc/hosts.equiv located on the remote system specifies the name of the local system, the remote system will not prompt you to enter your password. Systems that are listed in the /etc/hosts.equiv file are considered as secure as the local system.

An alternative way to specify a trusted relationship is on a per-user basis. Each user's home directory can contain a file named ~/.rhosts that holds a list of trusted remote systems and users. See "Examples" for a sample .rhosts file.

For security, the rlogin service is not enabled by default on Mac OS X systems. Even without the service enabled, you can use rlogin to connect to remote systems that provide an rlogin service.

Examples

The following example illustrates the use of rlogin. On the local system, Alex's username is alex; on the remote system bravo, his username is watson. The remote system prompts Alex to enter a password because he is logging in using a username different from the one he uses on the local system.

$ who am i alex      tty06         Oct 14 13:26 $ rlogin -l watson bravo Password:


~/.rhosts file

If the local system is named hurrah, the following .rhosts file on bravo allows the user alex to log in as the user watson without entering a password:

$ cat /Users/watson/.rhosts hurrah alex


rm: Removes a file (deletes a link)

rm [options] file-list

The rm utility removes hard and/or symbolic links to one or more files. When you remove the last hard link to a file, the file is deleted.

Caution: Be careful when you use rm with wildcards

Because you can remove a large number of files with a single command, use rm cautiously, especially when you are working with ambiguous file references. If you have doubts about the effect of an rm command with an ambiguous file reference, first use echo with the same file reference and evaluate the list of files generated by the reference. Alternatively, you can use the i option.


Arguments

The file-list specifies the pathnames of one or more files that rm is to delete.

Options

f

(force) Without asking for your consent, removes files for which you do not have write access permission (you must have execute and write access permissions for the parent directory of the file). This option also suppresses informative output if a file does not exist.

i

(interactive) Asks before removing each file. If you use r with this option, rm also asks you before examining each directory.

r

(recursive) Deletes the contents of the specified directory, including all its subdirectories, and the directory itself. Use this option cautiously.

v

(verbose) Displays the name of each file as it is removed.


Notes

To delete a file, you must have execute and write access permissions for the parent directory of the file, but you do not need read or write access permission for the file itself. If you are running rm interactively (that is, if rm's standard input is coming from the keyboard) and you do not have write access permission for the file, rm displays your access permission and waits for you to respond. If your response starts with a y or Y, rm deletes the file; otherwise, it takes no action. If standard input is not coming from a keyboard, rm deletes the file without question.

Refer to page 103 for information on hard links and page 105 for information on symbolic links. Page 107 includes a discussion about removing links. Refer to the rmdir utility (page 829) if you need to remove an empty directory.

When you want to remove a file whose name begins with a hyphen, you must prevent rm from interpreting the filename as an option. One way to do so is to give the special option -- before the name of the file. This option tells rm that no more options follow: Any arguments that come after it are filenames, even if they look like options.

Security: rm does not remove a file securely

Using rm does not securely delete a fileit is possible to recover a file deleted with rm. See the example "Wiping a file" on page 704 for a way to delete files more securely.


Examples

The following commands delete files both in the working directory and in another directory:

$ rm memo $ rm letter memo1 memo2 $ rm /Users/jenny/temp


The next example asks the user before removing each file in the working directory and its subdirectories:

$ rm -ir .


This command is useful for removing filenames that contain special characters, especially SPACEs, TABs, and NEWLINEs. (You should not create filenames containing these characters on purpose, but it may happen accidentally.)

rmdir: Removes a directory

rmdir directory-list

The rmdir utility deletes empty directories.

Arguments

The directory-list specifies the pathnames of empty directories that rmdir removes.

Options

p (parents) Removes a series of empty, nested directories, starting with the child.

Notes

Use the rm utility with the r option if you need to remove directories that are not empty, together with their contents.

Examples

The following command deletes the empty literature directory from the working directory:

$ rmdir literature


The next command removes the letters directory, using an absolute pathname:

$ rmdir /Users/jenny/letters


The final command removes the letters, march, and 05 directories, assuming the directories are empty except for other directories named in the path:

$ rmdir -p letters/march/05


rsh: Executes commands on a remote system

rsh [option] host [command-line]

The rsh utility runs command-line on host by starting a shell on the remote system. Without a command-line, rsh calls rlogin, which logs you in on the remote system.

Security: rsh is not secure

The rsh utility uses host-based trust, which is not secure, to authorize your login. Alternatively, it sends your password over the network as cleartext, which is not a secure practice. Use ssh (page 847) when it is available.


Arguments

The host is the name of the remote system. The rsh utility runs command-line on the remote system. You must quote special characters in command-line so that the local shell does not expand them prior to passing them to rsh.

Options

l

username

 

(login) Logs you in on the remote system as the user specified by username.


Notes

If the file named /etc/hosts.equiv located on the remote system specifies the name of the local system, the remote system will not prompt you to enter your password. Systems that are listed in the /etc/hosts.equiv file are considered as secure as the local system.

An alternative way to specify a trusted relationship is on a per-user basis. Each user's home directory can contain a file named ~/.rhosts that holds a list of trusted remote systems and users. See "Examples" under rlogin (page 826) for a sample .rhosts file.

For security reasons, the rsh service is not enabled by default on Mac OS X systems. Even without the service enabled, you can use rsh to connect to remote systems that provide an rsh service.

Examples

In the first example, Alex uses rsh to obtain a listing of the files in his home directory on bravo:

$ rsh bravo ls cost_of_living info preferences work


Next the output of the previous command is redirected into the file bravo.ls. Because the redirection character (>) is not escaped, it is interpreted by the local shell, and the file bravo.ls is created on the local system.

$ rsh bravo ls > bravo_ls $ cat bravo_ls cost_of_living info preferences work


The next example quotes the redirection character (>) so that the file bravo.ls is created on the remote system (bravo), as shown by ls run on bravo:

$ rsh bravo ls ">" bravo.ls $ rsh bravo ls bravo.ls cost_of_living info preferences work


In the final example, rsh without command-line logs in on the remote system. Alex has used the l watson option to log in on bravo as watson. The /Users/watson/.rhosts file must be configured to allow Alex to log in on the account in this manner. See "Examples" under rlogin (page 826) for a sample .rhosts file.

$ rsh -l watson bravo Last login: Sat Jul 30 16:13:53 from kudos $ hostname bravo $ exit rlogin: connection closed.


scp: Securely copies one or more files to or from a remote system

scp [[user@]from-host:]source-file [[user@]to-host:][destination-file]

The scp (secure copy) utility copies an ordinary or directory file from one system to another on a network. It uses ssh to transfer files and the same authentication mechanism as ssh; therefore it provides the same security as ssh. The scp utility asks you for a password when it is needed.

Arguments

The from-host is the name of the system you are copying files from; the to-host is the system you are copying files to. When you do not specify a host, scp assumes the local system. The user on either system defaults to the user on the local system who is giving the command; you can specify a different user with user@. The scp utility permits you to copy between two remote systems.

The source-file is the file you are copying, and the destination-file is the resulting copy. You can specify ordinary or directory files as relative or absolute pathnames. A relative pathname is relative to the specified or implicit user's home directory. When the source-file is a directory, you must use the r option to copy its contents. When the destination-file is a directory, each of the source files maintains its simple filename.

Options

E

(extended) Preserves extended attributes (page 93) when copying files. Requires both systems to be running Mac OS X 10.4 or later.

p

(preserve) Preserves the modification and access times as well as the permissions of the original file.

q

(quiet) Does not display the progress meter.

r

(recursive) Recursively copies a directory hierarchy.

v

(verbose) Displays debugging messages about the connection and transfer. This option is useful if things are not going as expected.


Notes

The scp utility is one of the OpenSSH suite of secure network connectivity tools. See "Notes" on page 848 for a discussion of OpenSSH security. Refer to "Message on initial connection to a server" on page 848 for information about a message you may get when using scp to connect to a remote system for the first time.

You can copy from or to the local system or between two remote systems. Make sure that you have read permission for the file you are copying and write permission for the directory you are copying it into.

You must quote a wildcard character (such as *) in a remote pathname so that it is interpreted by the shell on the remote system and not by the local shell.

As with cp, if the destination-file exists before you run scp, scp overwrites the file.

Under OS X version 10.3 and earlier, or when you do not use the E option under version 10.4 or later, scp does not preserve extended attributes (page 93).

Examples

The first example copies the files with filenames ending in .c from the working directory on the local system into the ~jenny/archives directory on bravo. The wildcard character is not quoted, so the local shell will expand it. Because archives is a relative pathname, scp assumes that it is a subdirectory of Jenny's home directory on bravo. Each of the copied files retains its simple filename.

$ scp *.c jenny@bravo:archives


Next Alex copies the directory structure under ~alex/memos on bravo to ~jenny/alex.memos.bravo on kudos. He must have the necessary permissions to write to Jenny's home directory on kudos.

$ scp -r bravo:memos jenny@kudos:alex.memos.bravo


Finally Alex copies the files with filenames ending in .c from Jenny's archives directory on bravo to the jenny.c.bravo directory in his working directory. The wildcard character is quoted to protect it from expansion by the local shell; it will be interpreted by the remote system, bravo.

$ scp -r 'jenny@bravo:archives/*.c' jenny.c.bravo


It is important to remember that whenever you copy multiple files or directories, the destinationeither local or remotemust exist and be a directory, not an ordinary file.

SetFile: Sets file attributes

SetFile [options] file-list

The SetFile utility sets file attributes (page 95), including the file's type and creator code, creation and last modification time, and attribute flags such as the invisible and locked flags.

Arguments

The file-list specifies the pathnames of one or more files that SetFile works on.

Options

The options for SetFile correspond to options for GetFileInfo (page 749).

a

flags

 

(attribute) Sets the attribute flags specified by flags. An uppercase letter for a flag sets that flag and a lowercase letter unsets the flag. The values of unspecified flags are not changed. See Table 4-3 on page 96 or the SetFile man page for a list of attribute flags.

c

creator

 

Sets the creator code to creator.

d

date

 

Sets the creation date to date. You must format the date as mm/dd/[yy]yy [hh:mm:[:ss] [AM | PM]]. If you do not specify AM or PM, SetFile assumes a 24-hour clock. You must enclose a date string that contains SPACEs within quotation marks.

m

date

 

(modification) Sets the modification date to date. The format of date is the same as that used with the d option.

t

type

 

Sets the type code to type.


Notes

The SetFile utility is available in /Developer/Tools when the Developer Tools package (page 478) is installed.

Minor differences distinguish the options to SetFile and the corresponding options to GetFileInfo. For example, you can specify multiple attribute flags with the a option to SetFile but only a single flag with GetFileInfo. Also, SetFile requires a SPACE between the a option and the list of flags; GetFileInfo does not allow a SPACE there.

Examples

The first example sets the type and creator codes of the file named arch to SIT5 and SIT!, respectively, indicating that it is a StuffIt archive. The GetFileInfo utility displays these codes. Because these utilities are not in the default PATH (page 285), you must either change your PATH variable or call them with absolute pathnames as shown:

$ /Developer/Tools/SetFile -t SIT5 -c SIT! arch $ /Developer/Tools/GetFileInfo -c arch "SIT!" $ /Developer/Tools/GetFileInfo -t arch "SIT5"


The next example marks the file named secret as invisible and locked. The file will not show up in the Finder, and most OS X applications will be unable to overwrite it.

$ /Developer/Tools/SetFile -a VL secret


The final example clears the invisible attribute flag from every file in the working directory:

$ /Developer/Tools/SetFile -a v *


sleep: Creates a process that sleeps for a specified interval

sleep time

The sleep utility causes the process executing it to go to sleep for the time specified.

Arguments

The time denotes the number of seconds that the process sleeps for. The time does not have to be an integer; you can specify a decimal fraction.

Examples

You can use sleep from the command line to execute a command after a period of time. The following example executes in the background a process that reminds you to make a phone call in 20 minutes (1,200 seconds):

$ (sleep 1200; echo "Remember to make call.") & [1] 4660


You can also use sleep within a shell script to execute a command at regular intervals. The per shell script executes a program named heartbeat every 90 seconds:

$ cat per #!/bin/bash while true do     heartbeat     sleep 90 done


If you execute a shell script such as per in the background, you can terminate it only by using kill.

The final shell script accepts the name of a file as an argument and waits for that file to be created. If the file does not exist, the script sleeps for 1 minute and 45 seconds before checking for the file again:

$ cat wait_for_file #!/bin/bash if [ $# != 1 ]; then    echo "Usage: wait_for_file filename"    exit 1 fi while true do     if [ -f "$1" ]; then         echo "$1 is here now"         exit 0     fi     sleep 105 done


sort: Sorts and/or merges files

sort [options] [file-list]

The sort utility sorts and/or merges one or more text files.

Arguments

The file-list specifies the pathnames of one or more ordinary files that contain the text to be sorted. If the file-list is omitted, sort takes its input from standard input. Without the o option, sort sends its output to standard output. This utility sorts and merges files unless you use the m (merge only) or c (check only) option.

Options

When you do not specify an option, sort orders the file in the machine collating sequence (usually ASCII). Without a k option, sort orders a file based on full lines. Use k to specify sort fields within a line. You can follow a k option with additional options without a leading hyphen; see "Discussion" for more information. The sort utility accepts the standard help and version long options.

b

(blanks) Blanks (TAB and SPACE characters) normally mark the beginning of fields in the input file. Without this option, sort considers leading blanks to be part of the field they precede. This option ignores leading blanks within a field, so sort does not consider these characters in sort comparisons.

c

(check) Checks whether the file is properly sorted. The sort utility does not display anything if everything is in order. It displays a message if the file is not in sorted order and returns an exit status of 1.

d

(dictionary) Ignores all characters that are not alphanumeric or blanks. For example, sort does not consider punctuation with this option.

f

(fold) Considers all lowercase letters to be uppercase letters. Use this option when you are sorting a file that contains both uppercase and lowercase text.

help

Displays a help message.

i

(ignore) Ignores nonprinting characters.

k

start[,stop]

 

(key) Specifies a sort field within a line. Without this option, sort orders a file based on full lines. The sort field starts at the position on the line specified by start and ends at stop, or at the end of the line if stop is omitted. The start and stop pointers are in the format f[.c], where f is the field number and c is the optional character within the field. Numbering starts with 1. When c is omitted from start, it defaults to the first character in the field; when c is omitted from stop, it defaults to the last character in the field. See "Discussion" for further explanation of sort fields and "Examples" for illustrations of their use.

m

(merge) Assumes that multiple input files are all in sorted order and merges them without verifying that they are sorted.

n

(numeric) Sorts in arithmetic sequence; does not order lines or sort fields in the machine collating sequence. With this option, minus signs and decimal points take on their arithmetic meanings.

o

filename

 

(output) Sends the output to filename instead of standard output; filename can be the same as one of the names in the file-list.

r

(reverse) Reverses the sense of the sort (for example, z precedes a).

t

x

 

(separator) Specifies x as the field separator. See "Discussion" for more information on field separators.

version

Displays a version message.

u

(unique) Outputs repeated lines only once. When you use this option with c, sort displays a message if the same line appears more than once in the input file, even if the file is in sorted order.


Discussion

Without any options, sort bases its ordering on full lines.

In the following description, a field is a sequence of characters in a line of input. Without the t option, fields are bounded by the empty string preceding a group of one or more blanks (TAB and SPACE characters). You cannot see the empty string that delimits the fields; it is an imaginary point between two fields. Fields are also bounded by the beginning and end of the line. The line shown in (Figure VI-1) holds the fields Toni, SPACEBarnett, and SPACESPACESPACESPACE55020. These fields are used to define sort fields. Sometimes fields and sort fields are the same.

Figure VI-1. Fields and sort fields


Sort field

A sort field is a sequence of characters that sort uses to put lines in order. It can contain all or part of one or more fields (Figure VI-1).

The k option specifies pairs of pointers that define subsections of each line (sort fields) for comparison. See the k option for details.

Leading blanks

The b option causes sort to ignore leading blanks in a sort field. If you do not use this option, sort considers each leading blank to be a character in the sort field and includes it in the sort comparison.

Options

You can specify options that pertain only to a given sort field by immediately following the stop pointer (or the start pointer if there is no stop pointer) with one of the options b, d, f, i, n, or r. In this case you must not precede the option with a hyphen.

Multiple sort fields

When you specify more than one sort field, sort examines the sort fields in the order that they appear on the command line. If the first sort field of two lines is the same, sort examines the second sort field. If these are again the same, sort looks at the third field. This process continues for all the sort fields you specify. If all the sort fields are the same, sort examines the entire line.

Examples

The examples in this section demonstrate some of the features and uses of the sort utility. The examples assume that the list file shown here is in the working directory:

$ cat list Tom Winstrom           94201 Janet Dempsey          94111 Alice MacLeod          94114 David Mack             94114 Toni Barnett           95020 Jack Cooper            94072 Richard MacDonald      95510


This file contains a list of names and ZIP codes. Each line of the file contains three fields: the first name field, the last name field, and the ZIP code field. For the examples to work, make sure the blanks in the file are SPACEs, not TABs.

The first example demonstrates sort without any optionsthe only argument is the name of the input file. In this case sort orders the file on a line-by-line basis. If the first characters on two lines are the same, sort looks at the second characters to determine the proper order. If the second characters are the same, sort looks at the third characters. This process continues until sort finds a character that differs between the lines. If the lines are identical, it does not matter which one sort puts first. In this example, sort needs to examine only the first three characters (at most) of each line. The sort utility displays a list that is in alphabetical order by first name.

$ sort list Alice MacLeod          94114 David Mack             94114 Jack Cooper            94072 Janet Dempsey          94111 Richard MacDonald      95510 Tom Winstrom           94201 Toni Barnett           95020


You can instruct sort to skip any number of fields and characters on a line before beginning its comparison. Blanks normally mark the beginning of a field. The next example sorts the same list by last name, the second field. The k 2 argument instructs sort to begin its comparison with the second field. Because there is no second pointer, the sort field extends to the end of the line. Now the list is almost in last-name order, but there is a problem with Mac.

$ sort -k 2 list Toni Barnett           95020 Jack Cooper            94072 Janet Dempsey          94111 Richard MacDonald      95510 Alice MacLeod          94114 David Mack             94114 Tom Winstrom           94201


In the preceding example, MacLeod comes before Mack. After finding that the sort fields of these two lines were the same through the third letter (Mac), sort put L before k because it arranges lines based on ASCII character codes, in which uppercase letters come before lowercase ones.

The f option makes sort treat uppercase and lowercase letters as equals and fixes the problem with MacLeod and Mack:

$ sort -f -k 2 list Toni Barnett           95020 Jack Cooper            94072 Janet Dempsey          94111 Richard MacDonald      95510 David Mack             94114 Alice MacLeod          94114 Tom Winstrom           94201


The next example attempts to sort list on the third field, the ZIP code. In this case sort does not put the numbers in order but rather puts the shortest name first in the sorted list and the longest name last. The k 3 argument instructs sort to begin its comparison with the third field. A field starts with a blank and includes subsequent blanks. In the case of the list file, the blanks are SPACEs. The ASCII value of a SPACE character is less than that of any other printable character, so sort puts the ZIP code that is preceded by the most SPACEs first and the ZIP code that is preceded by the fewest SPACEs last.

$ sort -k 3 list David Mack             94114 Jack Cooper            94072 Tom Winstrom           94201 Toni Barnett           95020 Janet Dempsey          94111 Alice MacLeod          94114 Richard MacDonald      95510


The b option causes sort to ignore leading SPACEs within a field. With this option, the ZIP codes come out in the proper order. When sort determines that MacLeod and Mack have the same ZIP codes, it compares the entire lines, putting Alice MacLeod before David Mack (because A comes before D).

$ sort -b -k 3 list Jack Cooper            94072 Janet Dempsey          94111 Alice MacLeod          94114 David Mack             94114 Tom Winstrom           94201 Toni Barnett           95020 Richard MacDonald      95510


To sort alphabetically by last name when the ZIP codes are the same, sort needs to make a second pass that sorts on the last name field. The next example shows how to make this second pass by specifying a second sort field and uses the f option to keep the Mack/MacLeod problem from cropping up again:

$ sort -b -f -k 3 -k 2 list Jack Cooper             94072 Janet Dempsey           94111 David Mack              94114 Alice MacLeod           94114 Tom Winstrom            94201 Toni Barnett            95020 Richard MacDonald       95510


The next example shows a sort command that skips not only fields but also characters. The k 3.4 option causes sort to start its comparison with the fourth character of the third field. Because the command does not define an end to the sort field, it defaults to the end of the line. The sort field is the last two digits in the ZIP code.

$ sort -fb -k 3.4 list Tom Winstrom 94201 Richard MacDonald 95510 Janet Dempsey 94111 Alice MacLeod 94114 David Mack 94114 Toni Barnett 95020 Jack Cooper 94072


The problem of how to sort by last name within the last two digits of the ZIP code is solved by making a second pass covering the last-name field. The f option following the k 2 affects the second pass, which orders by last name only.

$ sort -b -k 3.4 -k 2f list Tom Winstrom            94201 Richard MacDonald       95510 Janet Dempsey           94111 David Mack              94114 Alice MacLeod           94114 Toni Barnett            95020 Jack Cooper             94072


The next set of examples uses the cars data file. Each column in this file is separated from the next by SPACEs, not TABs. From left to right, the columns in the file contain each car's make, model, year of manufacture, mileage, and price:

$ cat cars plym    fury    1970    73    2500 chevy   malibu  1999    60    3000 ford    mustang 1965    45    10000 volvo   s80     1998    102   9850 ford    thundbd 2003    15    10500 chevy   malibu  2000    50    3500 bmw     325i    1985    115   450 honda   accord  2001    30    6000 ford    taurus  2004    10    17000 toyota  rav4    2002    180   750 chevy   impala  1985    85    1550 ford    explor  2003    25    9500


Without any options, sort displays a sorted copy of the file:

$ sort cars bmw      325i    1985    115    450 chevy    impala  1985    85     1550 chevy    malibu  1999    60     3000 chevy    malibu  2000    50     3500 ford     explor  2003    25     9500 ford     mustang 1965    45     10000 ford     taurus  2004    10     17000 ford     thundbd 2003    15     10500 honda    accord  2001    30     6000 plym     fury    1970    73     2500 toyota   rav4    2002    180    750 volvo    s80     1998    102    9850


The objective of the next example is to sort by manufacturer and by price within manufacturer. Unless you specify otherwise, a sort field extends to the end of the line. The k 1 sort field specifier sorts from the beginning of the line. The command line instructs sort to sort on the entire line and then make a second pass, sorting on the fifth field all lines whose first-pass sort fields were the same (k 5):

$ sort -k 1 -k 5 cars bmw      325i      1985    115    450 chevy    impala    1985    85     1550 chevy    malibu    1999    60     3000 chevy    malibu    2000    50     3500 ford     explor    2003    25     9500 ford     mustang   1965    45     10000 ford     taurus    2004    10     17000 ford     thundbd   2003    15     10500 honda    accord    2001    30     6000 plym     fury      1970    73     2500 toyota   rav4      2002    180    750 volvo    s80       1998    102    9850


Because no two lines are the same, sort makes only one pass, sorting on each entire line. (If two lines differed only in the fifth field, they would be sorted properly on the first pass anyway, so the second pass would be unnecessary.) Look at the lines containing taurus and thundbd. They are sorted by the second field rather than the fifth field, demonstrating that sort never made a second pass and so never sorted on the fifth field.

The next example forces the first-pass sort to stop at the end of the first field. The k 1,1 option specifies a start pointer of the first character of the first field and a stop pointer of the last character of the first field. When you do not specify a character within a start pointer, it defaults to the first character; when you do not specify a character within a stop pointer, it defaults to the last character. Now taurus and thundbd are properly sorted by price. But look at explor: It is less expensive than the other Fords, but sort has it positioned as the most expensive. The sort utility put the list in ASCII collating sequence order, not in numeric order: Thus 9500 comes after 10000 because 9 comes after 1.

$ sort -k 1,1 -k 5 cars bmw      325i       1985    115    450 chevy    impala     1985    85     1550 chevy    malibu     1999    60     3000 chevy    malibu     2000    50     3500 ford     mustang    1965    45     10000 ford     thundbd    2003    15     10500 ford     taurus     2004    10     17000 ford     explor     2003    25     9500 honda    accord     2001    30     6000 plym     fury       1970    73     2500 toyota   rav4       2002    180    750 volvo    s80        1998    102    9850


The n (numeric) option on the second pass puts the list in the proper order:

$ sort -k 1,1 -k 5n cars bmw      325i       1985    115    450 chevy    impala     1985    85     1550 chevy    malibu     1999    60     3000 chevy    malibu     2000    50     3500 ford     explor     2003    25     9500 ford     mustang    1965    45     10000 ford     thundbd    2003    15     10500 ford     taurus     2004    10     17000 honda    accord     2001    30     6000 plym     fury       1970    73     2500 toyota   rav4       2002    180    750 volvo    s80        1998    102    9850


The next example again demonstrates that, unless you instruct it otherwise, sort orders a file starting with the field you specify and continuing to the end of the line. It does not make a second pass unless two of the first sort fields are the same. Because there is no stop pointer on the first sort field specifier, the sort field for the first pass includes the third field through the end of the line. Although this example sorts the cars by years, it does not sort them by model within manufacturer within years (ford thndbd comes before ford explor, when these lines should be reversed).

$ sort -k 3 -k 1 cars ford     mustang  1965    45     10000 plym     fury     1970    73     2500 bmw      325i     1985    115    450 chevy    impala   1985    85     1550 volvo    s80      1998    102    9850 chevy    malibu   1999    60     3000 chevy    malibu   2000    50     3500 honda    accord   2001    30     6000 toyota   rav4     2002    180    750 ford     thundbd  2003    15     10500 ford     explor   2003    25     9500 ford     taurus   2004    10     17000


Specifying an end to the sort field for the first pass allows sort to perform its secondary sort correctly:

$ sort -k 3,3 -k 1 cars ford    mustang  1965     45     10000 plym    fury     1970     73     2500 bmw     325i     1985     115    450 chevy   impala   1985     85     1550 volvo   s80      1998     102    9850 chevy   malibu   1999     60     3000 chevy   malibu   2000     50     3500 honda   accord   2001     30     6000 toyota  rav4     2002     180    750 ford    explor   2003     25     9500 ford    thundbd  2003     15     10500 ford    taurus   2004     10     17000


The next examples demonstrate several important sorting techniques: putting a list in alphabetical order, merging uppercase and lowercase entries, and eliminating duplicates. The unsorted list follows:

$ cat short Pear Pear apple pear Apple


Following is a plain sort:

$ sort short Apple Pear Pear apple pear


The following folded sort is a good start, but it does not eliminate duplicates:

$ sort -f short Apple apple Pear Pear pear


The u (unique) option eliminates duplicates, but without the f the uppercase entries come first:

$ sort -u short Apple Pear apple pear


When you attempt to use both u and f, some of the entries get lost:

$ sort -uf short apple Pear


Two passes is the answer. Both passes are unique sorts, and the first folds lowercase letters onto uppercase ones:

$ sort -u -k 1f -k 1 short Apple apple Pear pear


split: Divides a file into sections

split [options] [filename [prefix]]

The split utility breaks its input into 1,000-line sections named xaa, xab, xac, and so on. The last section may be shorter than the others. Options can change the sizes of the sections and lengths of the names.

Arguments

The filename is the pathname of the file that split processes. If you do not specify an argument or if you specify a hyphen () instead of a filename, split reads from standard input. The prefix is one or more characters that split uses to prefix the names of the files it creates. The default prefix is x.

Options

a

len

 

(suffix length) Specifies that the filename suffix is len characters long (the default is 2).

b

n[u]

 

(bytes) Breaks the input into files that are n bytes long. The u is an optional unit of measure (k for kilobytes or m for megabytes). If you include a unit of measure, split counts by this unit instead of by bytes.

l

num

 

(lines) Breaks the input into files that are num lines long (the default is 1,000).


Discussion

By default split names the first file it creates xaa. The x is the default prefix. You can change this prefix with the prefix argument. You can change the number of characters in each filename following the prefix with the a option.

Examples

By default split breaks a file into 1,000-line sections with the names xaa, xab, xac, and so on. The wc utility with the l option shows the number of lines in each file. The last file, xar, is smaller than the rest.

$ split bigfile $ wc -l xa*   1000 xaa   1000 xab   1000 xac  ...   1000 xap   1000 xaq    103 xar  17103 total


The next example uses the prefix argument to specify a filename prefix of SEC and uses a to change the number of letters in the filename suffix to 3:

$ split -a 3 /etc/services SEC $ ls SECaaa  SECaac  SECaae  SECaag  SECaai  SECaak SECaab  SECaad  SECaaf  SECaah  SECaaj  SECaal


ssh: Securely executes commands on a remote system

ssh [option] [user@]host [command-line]

The ssh (secure shell) utility runs command-line on host by starting a shell on the remote system or logs you in on host. The ssh utility, which can replace rsh and rlogin, provides secure, encrypted communication between two systems on an insecure network.

Arguments

The host is the system that you want to log in or run a command on. Unless you have one of several kinds of authentication established, ssh prompts you for a username and password for the remote system. When ssh is able to log in automatically, it logs in as the user running the ssh command or as user if user@ appears on the ssh command line.

The command-line runs on the remote system. Without command-line, ssh logs you in on the remote system. You must quote special characters in command-line if you do not want the local shell to expand them.

Options

f

(not foreground) Sends ssh to the background after asking for a password and before executing command-line. This option is useful when you want to run the command-line in the background but must supply a password. Its use implies n.

l

user

 

(login) Attempts to log in as user. This option is equivalent to using user@ on the command line.

n

(null) Redirects standard input to the ssh utility to come from /dev/null (page 444). See f.

p

port

 

(port) Connects to port port on the remote host.

q

(quiet) Suppresses warning and diagnostic messages.

t

(tty) Allocates a pseudo-tty to the ssh process on the remote system. Without this option, when you run a command on a remote system, ssh does not allocate a tty (terminal) to the process. Instead, ssh attaches standard input and standard output of the remote process to the ssh sessionthat is normally, but not always, what you want. This option forces ssh to allocate a tty on the remote system so that programs that require a tty will work.

v

(verbose) Displays debugging messages about the connection and transfer. This option is useful if things are not going as expected.

x

(X11) Turns off X11 forwarding.

X

(X11) Turns on X11 forwarding. You may not need this optionX11 forwarding may be turned on in a configuration file.


Notes

OpenSSH security

Using public-key encryption, OpenSSH provides two levels of authentication: server and client/user. First, the client (ssh or scp) verifies that it is connected to the correct server and OpenSSH encrypts communication between the client and the server. Second, once a secure, encrypted connection has been established, OpenSSH confirms that the user is authorized to log in on or copy files from and to the server. Once the system and user have been verified, OpenSSH allows different services to pass through the connection. These services include interactive shell sessions (ssh), remote command execution (ssh and scp), X11 client/server connections, and TCP/IP port tunneling.

Message on initial connection to a server

When you connect to an OpenSSH server for the first time, the OpenSSH client prompts you to confirm that you are connected to the correct system. This check can help prevent a person-in-the-middle attack.

The authenticity of host 'grape (192.168.0.3)' can't be established. RSA key fingerprint is c9:03:c1:9d:c2:91:55:50:e8:19:2b:f4:36:ef:73:78. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'grape,192.168.0.3' (RSA) to the list of known hosts.


Before you respond to the preceding query, verify that you are logging in on the correct system and not on an imposter. If you are not sure, a telephone call to someone who logs in on that system locally can verify that you are on the intended system. When you answer yes (you must spell it out), the client appends the server's public host key to the user's ~/.ssh/known_hosts file on the local system, creating the ~/.ssh directory if necessary. So that it can keep track of which line in known_hosts applies to which server, OpenSSH prepends the name of the server and the server's IP address to the line. Subsequently, when you use OpenSSH to connect to that server, the client verifies that it is connected to the correct server by comparing this key to the one supplied by the server.

Examples

In the first example, Alex uses ssh to display a list of the files in his home directory on kudos:

$ ssh kudos ls alex@kudos's password: Work code graphs reports


Next the output of the previous command is redirected to the file kudos_ls. Because the redirection character (>) is not escaped, it is interpreted by the local shell, and the file kudos_ls is created on the local system.

$ ssh kudos ls > kudos_ls alex@kudos's password: $ cat kudos_ls Work code graphs reports


The next example quotes the entire command that will run on the remote system. As a result the local shell does not interpret the redirection character (>) but rather passes it to the remote shell. The file kudos.ls is created on the remote system (kudos), as shown by ls run on kudos:

$ ssh kudos "ls > kudos.ls" alex@kudos's password: $ ssh kudos ls alex@kudos's password: Work code graphs kudos.ls reports


The next command does not quote the pipe symbol (|). As a result the pipe is interpreted by the local shell, which sends the output of the remote ls to standard input of less on the local system:

$ ssh kudos ls | less


Next ssh executes a series of commands, connected with pipes, on a remote system. The commands are enclosed within single quotation marks so that the local shell does not interpret the pipe symbols and all the commands are run on the remote system.

$ ssh kudos 'ps -ef | grep nmbd | grep -v grep | cut -c10-15 |xargs kill -1'


The output of ps is piped through grep, which passes all lines containing the string nmbd to another invocation of grep. The second grep passes all lines not containing the string grep to cut (page 699). The cut utility extracts the process ID numbers and passes them to xargs (page 892), which kills the listed processes with a HUP signal (kill 1).

In the following example, ssh without command-line logs in on the remote system. Here Alex has used watson@kudos to log in on kudos as watson:

$ ssh watson@kudos watson@kudos's password: Last login: Sat Sep 17 06:51:59 from bravo $ hostname kudos $ exit


Alex now decides to change the password for his watson login on kudos:

$ ssh watson@kudos passwd Password: Old password:por


Alex stops as soon as he sees passwd (running on kudos) displaying his password: He knows that something is wrong. For the passwd to work, it must run with a tty (terminal) so that it can turn off character echo (stty echo) and thus not display a password as the user enters it. The t option solves this problem by associating a pseudo-tty with the process running passwd on the remote system:

$ ssh -t watson@kudos passwd watson@kudos's password: Changing password for watson Old password: New password: Retype new password: Connection to kudos closed. $


The t option is also useful when you are running a program that uses a character-based/pseudographical interface.

The final example uses tar (page 862) to create an archive file of the contents of the working directory hierarchy. The f option causes tar to send its output to standard output. A pipe sends the output of tar running on the local system, via ssh, to dd (page 703) running on the remote system.

$ cat buwd #! /bin/bash # back up the working directory to the user's # home directory on the remote system specified # by $machine # remote system: machine=speedy dir=$(basename $(pwd)) filename=$$.$dir.tar echo Backing up $(pwd) to your home directory on $machine tar -cf - . | ssh $machine "dd obs=256k of=$filename" echo done. Name of file on $machine is $filename


stat: Displays information about files

stat [options] [file-list]

The stat utility displays information about files.

Arguments

The file-list specifies the pathnames of one or more files that stat displays information about. Without a file-list, stat displays information about standard input.

Options

Without any options, stat displays all of the available information about each file it processes.

F

(file type) Displays a slash (/) after each directory, an asterisk (*) after each executable file, an at sign (@) after a symbolic link, an equal sign (=) after a socket, and a pipe (|) after a FIFO.

L

(dereference) Displays information about the file a link points to, not the link itself.

q

(quiet) Suppresses error messages.

l

(long) Uses the same format as ls l (page 87).

s

(shell) Displays information in a format that can be used to initialize shell variables. See the "Examples" section.

x

(Linux) Displays a more verbose format that is compatible with the version of stat found on some Linux distributions.

f

format

 

Formats output using format. The format string is similar to that used by printf. See the "Examples" section and the stat man page for more information.


Discussion

The stat utility is a front end for the stat() system call (give the command man 2 stat to see the man page). The stat utility displays the permissions and timestamps of a file, but not its file attributes (page 95). Use GetFileInfo (page 749) to display file attributes.

Notes

The stat utility was introduced in Mac OS X 10.4.

Examples

By default stat does not label the information it displays. The first example displays information about the root filesystem (startup volume):

$ stat / 234881026 2 drwxrwxr-t 41 root admin 0 1496 "Jul 19 23:41:32 2005" "Jul 17 23:21:05 2005" "Jul 17 23:21:05 2005" 4096 0 0 /


The first value in the preceding output is the device number. The x option formats and labels the information, with the device number displayed as a pair of numbers separated by a comma:

$ stat -x /   File: "/"   Size: 1496         FileType: Directory   Mode: (0775/drwxrwxr-t)         Uid: (    0/    root)  Gid: (   80/   admin) Device: 14,2   Inode: 2    Links: 41 Access: Tue Jul 19 23:41:32 2005 Modify: Sun Jul 17 23:21:05 2005 Change: Sun Jul 17 23:21:05 2005


The s option displays information as a set of shell variable assignments. The names of the variables correspond to the members of the structure returned by the stat() system call. You can use this output to set shell variables using the eval builtin (page 374).

$ stat -s / st_dev=234881026 st_ino=2 st_mode=041775 st_nlink=41 st_uid=0 st_gid=80 st_rdev=0 st_size=1496 st_atime=1121834492 st_mtime=1121660465 st_ctime=1121660465 st_blksize=4096 st_blocks=0 st_flags=0 $ eval $(stat -s /) $ echo $st_uid 0


The st_uid variable indicates the file's owner as a numeric user ID; 0 is the user ID for root.

The following examples show different ways of displaying information about standard input. The first command displays the output in stat's default format. The second command displays the permissions (%p, the same as st_mode above) field using various formats. The S flag displays data as a string, not as a number. The H and M flags display the high and middle components of the value, respectively.

$ stat 31090580 32514436 crw--w---- 1 zach tty 67108867 0 "May  9 16:17:23 2005" "May  9 16:17:23 2005" "May  9 16:17:23 2005" 131072 0 0 (stdin) $ stat -f "p: %p Sp: %Sp Hp: %Hp SHp: %SHp Mp: %Mp SMp: %SMp" p: 20620 Sp: crw--w---- Hp: 2 SHp: rw- Mp: 0 SMp: -w-


The high/middle/low components are applicable only to some fields and may select different parts of a field in different formats. For example, the high component of permissions in string form is the user permissions bits; in numeric form it is the file's type bit.

strings: Displays strings of printable characters

strings [options] file-list

The strings utility displays strings of printable characters from object and other nontext files.

Arguments

The file-list specifies the pathnames of one or more files that strings processes.

Options

a

(all) Searches all sections of object files. Without this option, strings processes only the initialized and loaded parts of an object file.

(this option is a hyphen) Searches entire files. This is the default behavior except when processing object files. By default string processes only relevant parts of object files.

n min

 

(minimum) Displays strings of characters that are at least min characters long (the default is 4). Also min.


Discussion

The strings utility can help you determine the contents of nontext files. One application for strings is determining the owner of files in a lost+found directory.

Examples

The following example displays the strings of four or more printable characters found in the executable file for the man utility. If you did not know what this file was, these strings could help you determine that it was the man executable.

$ strings /usr/bin/man ... LC_CTYPE APROPOS %s %Q WHATIS MAN_HP_DIREXT MAN_IRIX_CATNAMES manpath sman %s/%s%s%s/%s.%s%s %s/cat%s%s/%s.%s%s /man /MAN /share/man /man1 /man8 ...


stty: Displays or sets terminal parameters

stty [options] [arguments]

Without any arguments, stty displays certain parameters affecting the operation of the terminal/terminal emulator. For a list of some of these parameters and an explanation of each, see "Arguments." The arguments establish or change parameters.

Options

a

(all) Reports on all parameters. This option does not accept arguments.

e

(everything) Reports on all parameters in a slightly different format from that produced by the a option. The command stty all generates the same output.

f /dev/device

 

(file) Affects device. Without this option, stty affects the device attached to standard input. You can change the characteristics of a device only if you own its device file or if you are Superuser.

g

(generate) Generates a report of the current settings in a format you can use as arguments to another stty command. This option does not accept arguments.


Arguments

The arguments to stty specify which terminal parameters stty is to alter. Turn on each of the parameters that is preceded by an optional hyphen (indicated in the following list as []) by specifying the parameter without the hyphen. Turn it off by using the hyphen. Unless specified otherwise, this section describes the parameters in their on states.

Special Keys and Characteristics

columns n

Sets the line width to n columns.

ek

(erase kill) Sets the erase and line kill keys to their default values. Many systems use DELETE and CONTROL-U, respectively, as the defaults.

erase x

Sets the erase key to x. To specify a control character, precede x with CONTROL-V (for example, use CONTROL-V CONTROL-H to indicate CONTROL-H) or use the notation ^h, where ^ is a caret (SHIFT-6 on most keyboards).

intr x

Sets the interrupt key to x. See erase x for conventions.

kill x

Sets the line kill key to x. See erase x for conventions.

rows n

Sets the number of screen rows to n.

sane

Sets the terminal parameters to values that are usually acceptable. The sane argument is useful when several stty parameters have changed, making it difficult to use the terminal to run stty to set things right. If sane does not appear to work, try entering the following characters:

CONTROL-J stty sane CONTROL-J


susp x

(suspend) Sets the suspend (terminal stop) key to x. See erase x for conventions.

werase x

(word erase) Sets the word erase key to x. See erase x for conventions. Some programs use CONTROL-W as the word erase key regardless of how you set werase.

Modes of Data Transmission

[]cooked

See raw.

[]cstopb

(stop bits) Selects two stop bits (cstopb specifies one stop bit).

[]parenb

(parity enable) Enables parity generation and checking on input and output. When you specify parenb, the system does not generate or expect a parity bit when communicating with the terminal.

[]parodd

(parity odd) Selects odd parity (parodd selects even parity).

[]raw

The normal state is raw. When the system reads input in its raw form, it does not interpret the following special characters: erase (usually DELETE), line kill (usually CONTROL-U), interrupt execution (CONTROL-C), and EOF (CONTROL-D). In addition, the system does not use parity bits. Reflecting the humor that is typical of UNIX's heritage, you can specify raw as cooked.

Treatment of Characters

[]echo

Echoes characters as they are typed (full-duplex operation). If a terminal is half-duplex and displays two characters for each one it should display, turn the echo parameter off (echo). Use echo when the user is entering a password.

[]echoe

(echo erase) The normal setting is echoe, which causes the kernel to echo the character sequence BACKSPACE SPACE BACKSPACE when you use the erase key to delete a character. The effect is to move the cursor backward across the line, removing characters as you delete them.

[]echoke

(echo kill erase) The normal setting is echoke. When you use the kill character to delete a line while this option is set, all characters back to the prompt are erased on the current line. When this option is negated, pressing the kill key moves the cursor to the beginning of the next line.

[]nl

Accepts only a NEWLINE character as a line terminator. With nl in effect, the system accepts a RETURN character from the terminal as a NEWLINE but sends a RETURN followed by a NEWLINE to the terminal instead of a NEWLINE.

[]tabs

Transmits each TAB character to the terminal as a TAB character. When tabs is turned off (tabs), the kernel translates each TAB character into the appropriate number of SPACEs and transmits them to the terminal.

Job Control Parameters

[]tostop

Stops background jobs if they attempt to send output to the terminal (tostop allows background jobs to send output to the terminal).

Notes

The name stty is an abbreviation for set teletypewriter, or set tty (page 882), the first terminal that UNIX was run on. Today stty is commonly thought of as set terminal.

The shells retain some control over standard input when you use them interactively. As a consequence, a number of the options available with stty appear to have no effect. For example, the command stty echo appears to have no effect under tcsh:

tcsh $ stty -echo tcsh $ date Fri Feb 18 21:21:14 PST 2005


While stty echo does work when you are using bash interactively, stty echoe does not. However, you can still use these options to affect shell scripts and other utilities.

$ cat testit #!/bin/bash stty -echo echo -n "Enter a value: " read a echo echo "You entered: $a" stty echo $ testit Enter a value: You entered: 77


In the preceding example, the kernel does not display the user's response to the Enter a value: prompt. The value is retained by the a variable and is displayed by the echo "You entered: $a" statement.

Examples

The first example shows that stty without any arguments displays several terminal operation parameters. (Your system may display more or different parameters.) The character following erase = is the erase key. A ^ preceding a character indicates a CONTROL key. In the example, the erase key is CONTROL-H. If stty does not display the erase character, it is set to its default value of DELETE. If you do not see a kill character, it is set to its default of CONTROL-U.

$ stty speed 38400 baud; lflags: echoe echoke echoctl pendin oflags: onocr onlret cflags: cs8 -parenb erase ^H


Next the ek argument returns the erase and line kill keys to their default values:

$ stty ek


The next example verifies the change. The stty utility does not display either the erase character or the line kill character, indicating that both are set to their default values:

$ stty speed 38400 baud; lflags: echoe echoke echoctl pendin oflags: onocr onlret cflags: cs8 -parenb


The next example sets the erase key to CONTROL-H. The CONTROL-V quotes the CONTROL-H so that the shell does not interpret it and passes it to stty:

$ stty erase CONTROLV CONTROLH $ stty speed 38400 baud; ... erase ^H


Next stty sets the line kill key to CONTROL-X. This time the user entered a caret (^) followed by an x to represent CONTROL-X. You can use either a lowercase or an uppercase letter.

$ stty kill ^X $ stty speed 38400 baud; ... erase   kill ^H      ^X


Now stty changes the interrupt key to CONTROL-C:

$ stty intr CONTROLVCONTROLC


In the following example, stty turns off TABs so that the appropriate number of SPACEs are sent to the terminal in place of a TAB. Use this command if a terminal does not automatically expand TABs.

$ stty -tabs


sysctl: Displays and alters kernel variables

sysctl [options] [variable-list]

sysctl [options] w [var=value ... ]

The sysctl utility displays and alters kernel variables including kernel tuning parameters.

Arguments

The variable-list is a list of kernel variables whose values sysctl displays. In the second format, each value is assigned to the variable named var.

Options

a

(all) Displays all kernel variables.

b

(binary) Displays kernel variables as binary data without terminating NEWLINEs.

n

(no label) Displays variables without labels.


Discussion

The sysctl utility provides access to a number of kernel variables, including the maximum number of processes that the kernel will run at one time, the filename used for core files, and the system security level. Some variables cannot be altered or can be altered only in certain ways. For example, the security level can never be lowered.

Notes

During startup, /etc/rc uses sysctl to alter any variables specified in /etc/sysctl.conf, if it exists.

Examples

One common use of sysctl is tuning the kernel. The default limit on the number of processes running with a given user ID is 100 under Mac OS X. (It is higher in Mac OS X Server.) The process limits can be displayed without root privileges, but can be altered only by root. In this example, Alex changes this limit using sudo to gain root privileges temporarily:

$ sysctl -a | grep proc kern.maxproc = 532 kern.maxfilesperproc = 10240 kern.maxprocperuid = 100 kern.aioprocmax = 16 kern.proc_low_pri_io = 0 $ sudo sysctl -w kern.maxprocperuid=200 Password: kern.maxprocperuid: 100 -> 200 $


tail: Displays the last part of a file

tail [options] [file-list]

The tail utility displays the last part, or end, of a file.

Arguments

The file-list specifies the pathnames of one or more files that tail displays. When you specify more than one file, tail displays the filename of each file before displaying the lines of the file. If you do not specify an argument or if you specify a hyphen (-) instead of a filename, tail reads from standard input.

Options

c [+]n

 

(characters) Counts by bytes (characters) instead of lines. The n is an integer that specifies the number of bytes. Thus the command tail c 5 displays the last 5 bytes of a file.

 

If you put a plus sign (+) in front of n, tail counts from the start of the file instead of the end. The tail utility still displays to the end of the file, even though it starts counting from the beginning. Thus tail c +5 causes tail to display from the fifth character through the end of the file.

f

(flush) After copying the last line of the file, tail enters an endless loop, waiting and copying additional lines from the file if the file grows. If you specify multiple files in file-list with this option, tail includes a new header each time it displays output from a different file so that you know which file is being added to. This option is useful for tracking the progress of a process that is running in the background and sending its output to a file. The tail utility continues to wait indefinitely, so you must use the interrupt key to terminate it.

n [+]n

 

(lines) Counts by lines (the default). The n is an integer that specifies the number of lines. Although it is not documented, you can use ±n to specify a number of lines without using this option.

 

If you put a plus sign (+) in front of n, tail counts from the beginning of the file instead of the end. The tail utility still displays to the end of the file, even though it starts counting from the beginning. Thus tail n +5 causes tail to display from the fifth line through the last line of the file.


Notes

The tail utility displays the last ten lines of its input by default.

Examples

The examples are based on the eleven file:

$ cat eleven line one line two line three line four line five line six line seven line eight line nine line ten line eleven


First tail displays the last ten lines of the eleven file (no options):

$ tail eleven line two line three line four line five line six line seven line eight line nine line ten line eleven


Next it displays the last three lines (n 3) of the file:

$ tail -n 3 eleven line nine line ten line eleven


The following example displays the file starting at line 8 (+8):

$ tail -n +8 eleven line eight line nine line ten line eleven


The next example displays the last six characters in the file (c 6). Only five characters are evident (leven); the sixth is a NEWLINE.

$ tail -c 6 eleven leven


The final example demonstrates the f option. Here tail tracks the output of a make command, which is being sent to the file accounts.out:

$ make accounts > accounts.out & $ tail -f accounts.out         cc -c trans.c         cc -c reports.c ... CONTROL-C $


In the preceding example, using tail with f has the same effect as running make in the foreground and letting its output go to the terminal. However, using tail offers some advantages. First, the output of make is saved in a file. (The output would not be saved if you let it go to the terminal.) Second, if you decide to do something else while make is running, you can kill tail and use the screen while make continues in the background. When you are running a large job, such as compiling a large program, you can use tail with the f option to check its progress periodically.

tar: Stores or retrieves files to/from an archive file

tar option [modifiers] [file-list]

The tar (tape archive) utility creates, adds to, lists, and retrieves files from an archive file.

Arguments

The file-list specifies the pathnames of one or more files that tar creates an archive with, adds to an archive, or extracts from an archive.

Options

Use only one of the following options to indicate which action tar should take. You can alter the action of the option by following it with one or more modifiers.

create

c

Creates an archive. This option stores the files named in file-list in a new archive. If the archive already exists, it is deleted before the new archive is created. If the file-list is a directory, tar recursively copies the files within the directory into the archive. Without the file option, the archive is written to standard output.

compare

d

(diff) Compares an archive with the corresponding disk files and reports on the differences.

help

 

Displays a list of options and modifiers, with short descriptions of each.

append

r

Writes the files named in file-list to the end of the archive. This option leaves files that are already in the archive intact, so duplicate copies of files may appear in the archive when tar finishes. When tar extracts the files, the most recent copy of a file in the archive ends up on the disk.

list

t

(table of contents) Without a file-list, this option produces a table of contents listing all files in an archive. With a file-list, it displays the name of each file in the file-list each time it occurs in the archive. You can use this option with the verbose option to display detailed information about each file in an archive. Without the file option, the archive is read from standard input.

update

u

Adds the files from file-list if they are not already in the archive or if they have been modified since they were last written to the archive. Because of the additional checking required, tar runs more slowly when you specify this option.

extract

x

Extracts file-list from the archive and writes it to the disk. Overwrites existing files with the same names. Without a file-list, this option extracts all files from the archive. If file-list includes a directory, tar extracts that directory hierarchy. The tar utility attempts to keep the owner, modification time, and access privileges the same as those associated with the original files. If it reads the same file more than once, the last version read will appear on the disk when tar is finished. Without the file option, the archive is read from standard input.


Modifiers

You can specify one or more modifiers following an option. If you use the single-character form of the modifier, a leading hyphen is not required, although it is a good practice to use it.

If a modifier takes an argument, that modifier must be the last one in a group. For example, the arguments are arranged legally in the following tar command:

$ tar -cb 10 -f memos.tar memos


Conversely, the following tar command generates an error:

$ tar -cbf 10 memos.tar memos tar: f: Invalid blocking factor Try 'tar --help' for more information.


The error occurs because the b modifier takes an argument but is not the last modifier in a group.

blocking-factor=n

 
 

b n

  

Uses n as the blocking factor for creating an archive. Use this option only when tar is creating an archive directly to a tape. (When tar reads a tape archive, it automatically determines the blocking factor.) The value of n is the number of 512-byte blocks to write as a single block on the tape. Apple does not supply a tape driver for OS X, but third-party tape drivers are available.

directory=dir

C dir

  

Changes the working directory to dir before processing.

checkpoint

 

Displays periodic messages. This option lets you know tar is running without displaying all the verbose messages.

file=filename

f filename

  

Uses filename as the name of the file (device) that holds the archive. The filename can be the name of an ordinary file or a device (such as a tape drive). You can use a hyphen (-) instead of the filename to refer to standard input when creating an archive and to refer to standard output when extracting files from an archive. The following two commands are equivalent ways of creating a compressed archive of the files under the /Users directory in the /tmp directory:

$ tar -zcf /tmp/Users.tgz /Users $ tar -cf - /Users | gzip > /tmp/Users.tgz


dereference

h

Archives the files that symbolic links point to, not the links themselves.

exclude=file

 

Does not process the file named file. If file is a directory, no files or directories within that directory hierarchy are processed. The file can be an ambiguous file reference; quote special characters as needed.

ignore-failed-read

 
  

When creating an archive, tar normally quits with a nonzero exit status if any file in file-list is unreadable. This option causes tar to continue processing, skipping unreadable files.

bzip

j

Uses bzip2 (page 668) to compress/decompress files when creating an archive and extracting files from an archive.

one-file-system

l

(lowercase "l") When a directory name appears in file-list while tar is creating an archive, tar recursively processes the files and directories below the named directory. With this option, tar stays in the filesystem that contains the named directory and does not process directories in other filesystems.

tapelength=n

L n

  

Asks for a new tape after writing n*1,024 bytes to the current tape. This feature is useful when you are building archives that are too large to fit on a single tape.

touch

m

Sets the modification time of an extracted file to the time of extraction. Without this option, tar attempts to maintain the modification time of the original file.

absolute-paths

P

The default behavior of tar is to force all pathnames to be relative paths by stripping leading slashes. This option disables this feature, so absolute pathnames remain as absolute paths.

sparse

S

UNIX allows you to have sparse filesthat is, large, mostly empty fileson disk. The empty sections of sparse files do not take up any disk space. When tar copies a sparse file out of an archive, it normally expands the file to its full size. As a result, when you restore a sparse file from a tar backup, the file takes up its full space and may no longer fit in the same disk space as the original. This option causes tar to handle sparse files efficiently so that they do not take up unnecessary space either in the archive or when they are extracted.

verbose

v

Lists each file as tar reads or writes it. When combined with the t option, v causes tar to display a more detailed listing of the files in an archive, showing their ownership, permissions, size, and other information.

interactive or confirmation

w

Asks you for confirmation before reading or writing each file. Respond with y if you want tar to take the action. Any other response causes tar not to take the action.

exclude-from=filename

 
 

X filename

  

Similar to the exclude option except that filename specifies a file that contains a list of files to exclude from processing. Each file listed in filename must appear on a separate line.

gzip or gunzip

z

Causes tar to use gzip (page 756) to compress an archive while it is being created and to use gunzip to decompress an archive when extracting files from it. This option also works to extract files from archives that have been compressed with the compress utility.

compress or uncompress

Z

Uses compress when creating an archive and uncompress when extracting files from an archive.


Notes

The help option displays all of the tar options and modifiers. The info page on tar provides extensive information, including a tutorial.

You can use ambiguous file references in file-list when you create an archive but not when you extract files from an archive.

The name of a directory file within the file-list references all files and subdirectories within that directory.

The file that tar sends its output to by default is compilation specific; typically it goes to standard output. Use the f option to specify a different filename or device to hold the archive.

When you create an archive using a simple filename in file-list, the file appears in the working directory when you extract it. If you use a relative pathname when you create an archive, the file appears with that relative pathname, starting from the working directory when you extract it. If you use the P option and an absolute pathname when you create an archive, and then use the P option when you extract files from the archive, tar extracts the file with the same pathname.

Under Mac OS X version 10.4 and later, tar archives extended attributes (page 93), including ACLs. Under version 10.3 and earlier, tar does not archive extended attributes. For a similar utility that does copy extended attributes, see ditto (page 715).

Examples

The first example makes a copy of the /Users/alex directory hierarchy in an archive file named alex.tar on a volume (filesystem) named Backups. The v modifier causes the command to list the files it writes to the archive. The message from tar explains that the default action is to store all pathnames as relative paths instead of as absolute paths, thereby allowing you to extract the files into a different directory on the disk.

$ tar -cvf /Volumes/Backups/alex.tar /Users/alex tar: Removing leading '/' from member names. Users/alex/ Users/alex/.bash_history Users/alex/.bash_profile ...


In the next example, the same directory is saved to an archive on the partition /Volumes/Firewire. Without the v modifier, tar does not display the list of files it is writing to the archive. The command runs in the background and displays any messages after the shell issues a new prompt.

$ tar -c -f /Volumes/Firewire /Users/alex & [1] 4298 $ tar: Removing leading '/' from member names.


The next command displays the table of contents of the archive file alex.tar:

$ tar -tvf /Volumes/Backups/alex.tar drwxrwxrwx alex/alex        0 Jun 30 21:39 2004 Users/alex/ -rw-r--r-- alex/alex      678 Aug  6 14:12 2005 Users/alex/.bash_history -rw-r--r-- alex/alex      571 Aug  6 14:06 2005 Users/alex/.bash_profile drwx------ alex/alex        0 Nov  6 22:34 2005 Users/alex/mail/ -rw------- alex/alex     2799 Nov  6 22:34 2005 Users/alex/mail/sent-mail ...


In the following example, Alex creates a gzipped tar archive in /tmp/alex.tgz. This approach is a popular way to bundle files that you want to transfer over a network or otherwise share with others. Ending a filename with .tgz is one convention for identifying gzipped tar archives. Another convention is to end the filename with .tar.gz.

$ tar -czf /tmp/alex.tgz literature


The final command lists the files in the compressed archive alex.tgz:

$ tar -tzvf /tmp/alex.tgz ...


tee: Copies standard input to standard output and one or more files

tee [options] file-list

The tee utility copies standard input to standard output and to one or more files.

Arguments

The file-list specifies the pathnames of one or more files that receive output from tee.

Options

Without any options, tee overwrites the output files if they exist and responds to interrupts. If a file in file-list does not exist, tee creates it.

a

(append) Appends output to existing files rather than overwriting them.

i

(ignore) Causes tee not to respond to interrupts.


Examples

In the following example, a pipe sends the output from make to tee, which copies it to standard output and the file accounts.out. The copy that goes to standard output appears on the screen. The cat utility displays the copy that was sent to the file.

$ make accounts | tee accounts.out         cc -c trans.c         cc -c reports.c ... $ cat accounts.out         cc -c trans.c         cc -c reports.c ...


Refer to page 861 for a similar example that uses tail f rather than tee.

telnet: Connects to a remote system over a network

telnet [options] [remote-system [port]]

The telnet utility implements the TELNET protocol to connect to a remote system over a network. It can use the TELNET protocol or it can connect to other ports and provide direct access to other protocols.

Security: telnet is not secure

The telnet utility is not secure. It sends your username and password over the network as cleartext, which is not a secure practice. Use ssh (page 847) when it is available.


Arguments

The remote-system is the name or IP address of the remote system that telnet connects to. When you do not specify a remote-system, telnet works interactively and prompts you to enter one of the commands described under "Discussion." The port is the port on the remote-system that telnet connects to. When you do not specify a port, telnet connects to port 23 and attempts to log in.

Options

e

c

 

(escape) Changes the escape character from CONTROL-] to the character c.

K

(no login) Prevents automatic login.

l

username

 

(login) Attempts an automatic login on the remote system using username. If the remote system understands how to handle automatic login with telnet, you are prompted for a password.


Discussion

After telnet connects to a remote system, you can put telnet in command mode by typing the escape character (usually CONTROL-]). A remote system should report the escape character it recognizes. To leave command mode, press RETURN on a line by itself.

In command mode, telnet displays the telnet> prompt. You can use the following commands in command mode:

?

(help) Displays a list of commands recognized by the telnet utility on the local system.

close

Closes the connection to the remote system. If you specified the name of a system on the command line when you started telnet, close has the same effect as quit: The telnet program terminates, and the shell displays a prompt. If you used the open command instead of specifying a remote system on the command line, close returns telnet to command mode.

logout

Logs you out of the remote system; similar to close.

open remote-system

 

If you did not specify a remote-system on the command line or if the attempt to connect to the system failed, you can specify the name of a remote-system interactively with the open command.

quit

Quits the telnet session.

z

Suspends the telnet session. When you suspend a session, you return to the login shell on the local system. To resume the suspended telnet session, type fg at a shell prompt. For more information refer to "Moving a Job from the Foreground to the Background" on page 132.


Notes

Many computers, including some non-UNIX-like systems and nearly all UNIX-like systems, support the TELNET protocol. The telnet utility is a user interface to this protocol for OS X that allows you to connect to many different types of systems. Although you typically use telnet to log in, the remote computer may offer other services through telnet, such as access to special databases. Often these services are reached by specifying a port number. See page 405 for more information.

Examples

In the first example, the user connects to the remote system named bravo. After running a few commands, the user escapes to command mode and uses the z command to suspend the telnet session so as to run a few commands on the local system. The user gives an fg command to the shell to resume using telnet. The logout command on the remote system ends the telnet session, and the local shell displays a prompt.

kudos $ telnet bravo Trying 192.168.0.55 ... Connected to bravo. Escape character is '^]'. Fedora Core Release 2 (Tettnang) Kernel 2.6.5-1.358 on an i686 login: watson Password: Last login: Wed Jul 31 10:37:16 from kudos bravo $ ... bravo $CONTROL-] telnet> z [1]+ Stopped  telnet bravo kudos $ ... kudos $ fg telnet bravo bravo $ logout Connection closed by foreign host. kudos $


In the next example, the user connects manually to the SMTP server at example.com to see why it is bouncing mail from the spammer.com domain. The first line of output indicates which IP address telnet is trying to connect to. After telnet displays the Connected to smtpserv.example.com message, the user emulates an SMTP dialog, following the standard SMTP protocol. The first line, which starts with helo, begins the session and identifies the local system. After the SMTP server responds, the user enters a line that identifies the mail sender as user@spammer.com. The SMTP server's response explains why the message is bouncing, so the user ends the session with quit.

$ telnet smtpserv 25 Trying 192.168.1.1... Connected to smtpserv.example.com. Escape character is '^]'. helo example.com 220 smtpserv.example.com ESMTP Sendmail 8.13.1/8.13.1; Wed, 11 May 2005 00:13:43 -0500 (CDT) 250 smtpserv.example.com Hello desktop.example.com [192.168.1.97], pleased to meet you mail from:user@spammer.com 571 5.0.0 Domain banned for spamming quit 221 2.0.0 smtpserv.example.com closing connection


The telnet utility allows you to use any protocol you want, as long as you know it well enough to type it manually.

test: Evaluates an expression

test expression

[ expression ]

The test utility evaluates an expression and returns a condition code indicating that the expression is either true (0) or false (not 0). You can place brackets ([]) around the expression instead of using the word test (second format).

Arguments

The expression contains one or more criteria (Table VI-27) that test evaluates. A a separating two criteria is a Boolean AND operator: Both criteria must be true for test to return a condition code of true. A o is a Boolean OR operator: one or the other (or both) of the criteria must be true for test to return a condition code of true.

Table VI-27. Criteria

Criterion

Meaning

string

True if string is not a null string.

n string

True if string has a length greater than zero.

z string

True if string has a length of zero.

string1 = string2

True if string1 is equal to string2.

string1 != string2

True if string1 is not equal to string2.

int1 relop int2

True if integer int1 has the specified algebraic relationship to integer int2. The relop is a relational operator from Table VI-28. As a special case, l string, which gives the length of string, may be used for int1 or int2.

file1ef file2

True if file1 and file2 have the same device and inode numbers.

file1 nt file2

True if file1 was modified after file2 (the modification time of file1 is newer than that of file2).

file1 ot file2

True if file1 was modified before file2 (the modification time of file1 is older than that of file2).

b filename

True if the file named filename exists and is a block special file.

c filename

True if the file named filename exists and is a character special file.

d filename

True if the file named filename exists and is a directory.

e filename

True if the file named filename exists.

f filename

True if the file named filename exists and is an ordinary file.

g filename

True if the file named filename exists and its setgid bit (page 90) is set.

G filename

True if the file named filename exists and is associated with the group that is the primary group of the user running the command (same effective group ID).

k filename

True if the file named filename exists and its sticky bit (page 955) is set.

L filename

True if the file named filename exists and is a symbolic link.

O filename

True if the file named filename exists and is owned by the user running the command (same effective user ID).

p filename

True if the file named filename exists and is a named pipe.

r filename

True if the file named filename exists and you have read permission for it.

s filename

True if the file named filename exists and contains information (has a size greater than 0 bytes).

t file-descriptor

True if file-descriptor is associated with the screen/keyboard. The file-descriptor for standard input is 0, for standard output is 1, and for standard error is 2.

u filename

True if the file named filename exists and its setuid bit (page 90) is set.

w filename

True if the file named filename exists and you have write permission for it.

x filename

True if the file named filename exists and you have execute permission for it.


Table VI-28. Relational operators

Relop

Meaning

eq

Equal to

ge

Greater than or equal to

gt

Greater than

le

Less than or equal to

lt

Less than

ne

Not equal to


You can negate a criterion by preceding it with an exclamation point (!). You can group criteria with parentheses. If there are no parentheses, a takes precedence over o, and test evaluates operators of equal precedence from left to right.

Within the expression you must quote special characters, such as parentheses, so that the shell does not interpret them but rather passes them unchanged to test.

Because each element, such as a criterion, string, or variable within the expression, is a separate argument, you must separate each element from other elements with a SPACE. Table VI-27 lists the criteria you can use within the expression. Table VI-28 lists test's relational operators.

Notes

The test command is built into the Bourne Again and TC Shells. There is also a stand-alone test utility in /bin and a hard link to the file named /bin/[.

Examples

The following examples demonstrate the use of the test utility in Bourne Again Shell scripts. Although test works from the command line, it is more commonly employed in shell scripts to test input or verify access to a file.

The first example prompts the user, reads a line of input into a variable, and uses the synonym for test, [], to see whether the user entered yes:

$ cat user_in echo -n "Input yes or no: " read user_input if [ "$user_input" = "yes" ]     then        echo You input yes. fi


The next example prompts for a filename and then uses the synonym for test, [], to see whether the user has read access permission (r) for the file and (a) whether the file contains information (s):

$ cat validate echo -n "Enter filename: " read filename if [ -r "$filename" -a -s "$filename" ]     then         echo File $filename exists and contains information.         echo You have read access permission to the file. fi


The t 1 criterion checks whether the process running test is sending standard output to the screen. If it is, the test utility returns a value of true (0). The shell stores the exit status of the last command it ran in the $? variable. The following script tests whether its output is goes to a terminal:

$ cat term test -t 1 echo "This program is (=0) or is not (=1) sending its output to a terminal:" $?


First term is run with the output going to the terminal:

$ term This program is (=0) or is not (=1) sending its output to a terminal: 0


The next example runs term and redirects the output to a file. The contents of the file temp show that test returned 1, indicating that its output did not go to a terminal.

$ term > temp $ cat temp This program is (=0) or is not (=1) sending its output to a terminal: 1


top: Dynamically displays process status

top [options]

The top utility displays information about the status of the local system, including information about the current processes. Many of the options and configuration commands work in compatibility mode only (see the X option); this section describes that mode.

Options

Although top does not require the use of hyphens with options, it is a good idea to include them for clarity and consistency with other utilities. You can cause top to run as though you had specified any of the options by giving commands to the utility while it is running. See "Discussion" for more information.

n n

 

(number) Displays n processes.

o key

 

(order) Sorts the display according to key, which may be cpu, uid, time, pid, or another key. The default sort key is pid.

ssecs

 

(sleep) Causes top to redisplay information every secs seconds. The default is 1.

X

(compatibility) Causes top to run in compatibility mode. This mode is the most useful.


Discussion

The first few lines that top displays summarize the status of the local system. The exact lines that top displays vary depending on which options you use; see the top man page for details. The display at the top of the screen provides details about the system load average and uptime, processor usage, memory usage, and overall statistics about processes and threads.

The rest of the display reports on individual processes, listing the most CPU-intensive processes first. By default top displays the number of processes that fit on the screen. Table VI-29 describes the meanings of the fields displayed for each process. Options can change which fields top displays.

Table VI-29. Fields displayed by top

Name

Meaning

PID

Process identification number

UID

User ID of the process

COMMAND

Command line that started the process or name of the program

TIME

Total CPU time used by the process

%CPU

Percentage of CPU time used by the process during the last update period

#TH

Number of threads in the process

#PRTS

Number of Mach ports

#MREGS

Number of memory regions

RPRVT

Resident private memory size

RSHRD

Resident shared memory size

RSIZE

Total resident memory size, including shared pages

VSIZE

Total address space allocated, including shared pages


While top is running, you can use the following commands to modify its behavior. Except as noted, top must be in compatibility mode (X option) for these commands to work. Commands must be terminated by pressing RETURN.

n

(number) Prompts for the number of processes to display. If you enter 0 (the default), top displays as many processes as will fit on the screen.

q

(quit) Terminates top (works from all modes).

r

Toggles the display of process memory maps (RPRVT, RSHRD, VPRVT).

s

(seconds) Prompts you for the number of seconds to delay between updates to the display (3 is the default). You may enter an integer, a fraction, or 0 (for continuous updates). This command is disabled in secure mode.

S

(signal) Sends a signal to a process. The top utility prompts for a signal (the default is TERM) and then for a PID number.

SPACE

 

Refreshes the screen (works from all modes). Any key that does not do something else may refresh the screen.


Notes

The top utility is similar to ps but updates the display periodically, enabling you to watch the behavior of the local system over time.

This utility shows only as much of the command line for each process as fits on a line. When a process is swapped out, top replaces the command line with the name of the command in parentheses.

Requesting continuous updates is almost always a mistake. The display updates too quickly and the system load increases dramatically.

By default top sorts by PID number. To display processes with the one using the most CPU time at the top, give a top o cpu command.

Examples

The following display is the result of a typical execution of top X:

Time: 2005/05/11 00:36:55. Threads: 153. Procs: 51, 2 running, 49 sleeping. LoadAvg:  0.02,  0.03,  0.00.  CPU:   0.0% user,   4.8% sys,  95.2% idle. SharedLibs: num =  148, resident = 24.9M code, 3.09M data, 5.91M linkedit. MemRegions: num =  4139, resident = 48.4M + 5.66M private, 38.8M shared. PhysMem: 65.1M wired, 65.3M active,  101M inactive,  232M used,  791M free. VirtMem: 3.83G + 88.7M,      12920 pageins,          0 pageouts. PID  UID  REG RPRVT  RSHRD  RSIZE  VPRVT   VSIZE  TH PRT    TIME  %CPU COMMAND 2971   0  22   524K   396K   976K  26.2M   26.9M   1  19   0.77s   4.6 top 2889 501  18   140K   424K   480K  26.2M   26.7M   1  13   0.02s   0.0 less 2886 501  16  76.0K   812K   364K  1.05M   27.1M   1   8   0.00s   0.0 sh 2885 501  16  72.0K   812K   560K  1.05M   27.1M   1  13   0.00s   0.0 sh 2884 501  16   168K   360K   440K  26.2M   26.6M   1  13   0.01s   0.0 man 1761 501  18   232K   844K   876K  26.2M   27.1M   1  14   0.21s   0.0 bash 1535 501  17   184K   844K   820K  26.1M   27.1M   1  14   0.06s   0.0 bash 1531 501  41   100K  1.54M   512K   100K   29.9M   1  11   0.20s   0.0 sshd 1529   0  42   132K  1.54M  1.34M   136K   30.0M   1  34   0.15s   0.0 sshd 1521 501  16   188K   844K   812K  26.1M   27.1M   1  14   0.09s   0.0 bash 1520   0  36   144K   412K   556K  26.3M   26.9M   1  16   0.01s   0.0 login 235  501  16   192K   844K   828K  26.1M   27.1M   1  14   0.30s   0.0 bash 234    0  36   144K   412K   556K  26.3M   26.9M   1  16   0.01s   0.0 login


touch: Changes a file's access and/or modification time

touch [options] file-list

The touch utility changes the access and/or modification time of a file to the current time or a time you specify. If the file does not exist, touch creates it.

Arguments

The file-list specifies the pathnames of one or more files that touch will update.

Options

Accepts the common options described on page 663. Without any options, touch changes the access and modification times to the current time. When you do not specify the c option, touch creates files that do not exist.

a

(access) Updates the access time only, leaving the modification time unchanged.

c

(no create) Does not create files that do not exist.

m

(modification) Updates the modification time only, leaving the access time unchanged.

r file

 

(reference) Updates times to the times of file.

t [[cc]yy]nnddhhmm[.ss]

 

(time) Changes times to the date specified by the argument. The nn is the number of the month (0112), dd is the day of the month (0131), hh is the hour based on a 24-hour clock (0023), and mm is the minutes (0059). You must specify at least these fields. You can specify the number of seconds past the start of the minute with .ss.

The optional cc specifies the first two digits of the year (the value of the century minus 1), and yy specifies the last two digits of the year. When you do not specify a year, touch assumes the current year. When you do not specify cc, touch assumes 20 for yy in the range 068 and 19 for yy in the range 6999.


Examples

The first three commands show touch updating an existing file. The ls utility with the l option displays the modification time of the file. The last three commands show touch creating a file.

$ ls -l program.c -rw-r--r--   1 alex alex 5860 Apr 21 09:54 program.c $ touch program.c $ls -l program.c -rw-r--r--   1 alex alex 5860 Aug 13 19:01 program.c $ ls -l read.c ls: read.c: No such file or directory $ touch read.c $ ls -l read.c -rw-rw-r--   1 alex alex 0 Aug 13 19:01 read.c


The next example demonstrates the use of the a option to change the access time only and the t option to specify a date for touch to use instead of the current date and time. The first ls command displays the file modification times; the second ls (with the u option) displays the file access times. After the touch command is executed, ls shows that the access times of the files cases and excerpts have been updated as specified.

$ ls -l -rw-rw-r--  1 alex alex 45 Nov 30  2005 cases -rw-rw-rw-  1 alex alex 14 Jan 8  2006 excerpts $ ls -l -u -rw-rw-r--  1 alex alex 45 Jul 17 19:47 cases -rw-rw-rw-  1 alex alex 14 Jul 17 19:47 excerpts $ touch -a -t 07301900 cases excerpts $ ls -l -rw-rw-r--  1 alex alex 45 Nov 30  2005 cases -rw-rw-rw-  1 alex alex 14 Jan 8  2006 excerpts $ ls -l -u -rw-rw-r--  1 alex alex 45 Jul 30 19:00 cases -rw-rw-rw-  1 alex alex 14 Jul 30 19:00 excerpts


tr: Replaces specified characters

tr [options] string1 [string2]

The tr utility reads standard input and, for each input character, maps it to an alternate character, deletes the character, or leaves the character alone. This utility reads from standard input and writes to standard output.

Arguments

The tr utility is typically used with two arguments, string1 and string2. The position of each character in the two strings is important: Each time tr finds a character from string1 in its input, it replaces that character with the corresponding character from string2.

With one argument, string1, and the d option, tr deletes the characters specified in string1. The option s replaces multiple sequential occurrences of characters in string1 with single occurrences (for example, abbc becomes abc).

Ranges

A range of characters is similar in function to a character class within a regular expression (page 899). The tr utility does not support ranges (character classes) enclosed within brackets. You can specify a range of characters by following the character that appears earlier in the collating sequence with a hyphen and then the character that comes later in the collating sequence. For example, 16 expands to 123456. Although the range AZ expands as you would expect in ASCII, this approach does not work when you use the EBCDIC collating sequence, as these characters are not sequential in EBCDIC. See "Character Classes" for a solution to this issue.

Character Classes

A TR character class is not the same as the character classes described elsewhere in this book. (GNU documentation uses the term list operator for what this book calls a character class. See "Brackets" on page 899 for more information.) You specify a character class as '[:class:]', where class is a character class from Table VI-30. You must specify a character class in string1 unless you are performing case conversion (see "Examples") or are using the d and s options together.

Table VI-30. Character classes

Class

Meaning

alnum

Letters and digits

alpha

Letters

blank

Whitespace

cntrl

CONTROL characters

digit

Digits

graph

Printable characters but not SPACEs

lower

Lowercase letters

print

Printable characters including SPACEs

punct

Punctuation characters

space

Horizontal or vertical whitespace

upper

Uppercase letters

xdigit

Hexadecimal digits


Options

c

(complement) Complements string1, causing TR to match all characters except those in string1.

d

(delete) Deletes characters that match those specified in string1. If you use this option with the s option, you must specify both string1 and string2 (see "Notes").

s

(squeeze) Replaces multiple sequential occurrences of a character in string1 with a single occurrence of the character when you call TR with only one string argument. If you use both string1 and string2, the tr utility first translates the characters in string1 to those in string2; it then reduces multiple sequential occurrences of characters in string2.


Notes

When string1 is longer than string2, the initial portion of string1 (equal in length to string2) is used in the translation. When string1 is shorter than string2, tr uses the last character of string1 to extend string1 to the length of string2. Here tr departs from the POSIX standard, which does not define a result in this situation.

If you use the d and s options together, tr deletes the characters in string1 and then reduces multiple sequential occurrences of characters in string2.

Examples

You can use a hyphen to represent a range of characters in string1 or string2. Both command lines in the following example produce the same result:

$ echo abcdef | tr  'abcdef' 'xyzabc' xyzabc $ echo abcdef | tr  'a-f' 'x-za-c' xyzabc


The next example demonstrates a popular method for disguising text, often called ROT13 (rotate 13) because it replaces the first letter of the alphabet with the thirteenth, the second with the fourteenth, and so forth.

$ echo The punchline of the joke is ... | > tr 'A-M N-Z a-m n-z' 'N-Z A-M n-z a-m' Gur chapuyvar bs gur wbxr vf ...


To make the text intelligible again, reverse the order of the arguments to tr:

$ echo Gur chapuyvar bs gur wbxr vf ... | > tr 'N-Z A-M n-z a-m' 'A-M N-Z a-m n-z' The punchline of the joke is ...


The d option causes tr to delete selected characters:

$ echo If you can read this, you can spot the missing vowels! | > tr -d 'aeiou' If y cn rd ths, y cn spt th mssng vwls!


In the following example, TR replaces characters and reduces pairs of identical characters to single characters:

$ echo tennessee | tr -s 'tnse' 'srne' serene


The next example replaces each sequence of nonalphabetic characters (the complement of all the alphabetic characters as specified by the character class alpha) in the file draft1 with a single NEWLINE character. The output is a list of words, one per line.

$ tr -c -s '[:alpha:]' '\n' < draft1


The next example uses character classes to upshift the string hi there:

$ echo hi there | tr '[:lower:]' '[:upper:]' HI THERE


tty: Displays the terminal pathname

tty [option]

The tty utility displays the pathname of standard input if it is a terminal and displays not a tty if it is not a terminal. The exit status is 0 if standard input is a terminal and 1 if it is not.

Options

s (silent) Causes tty not to print anything; sets the exit status.

Notes

The term tty is short for teletypewriter, the terminal device on which UNIX was first run. This command appears in UNIX, and OS X has retained it for the sake of consistency and tradition.

Examples

The following example illustrates the use of tty:

$ tty /dev/ttyp0 $ echo $? 0 $ tty < memo not a tty $ echo $? 1


umask: Establishes the file-creation permissions mask

umask [mask]

The umask builtin specifies a mask that the system uses to set access permissions when you create a file. This builtin works slightly differently in each of the shells.

Arguments

The mask can be a three-digit octal number (bash and tcsh) or a symbolic value (bash) such as you would use with chmod (page 676). The mask specifies the permissions that are not allowed.

When mask is an octal number, the digits correspond to the permissions for the owner of the file, members of the group the file is associated with, and everyone else. Because the mask specifies the permissions that are not allowed, the system subtracts each of these digits from 7 when you create a file. The resulting three octal numbers specify the access permissions for the file (the numbers you would use with chmod). A mask that you give as a symbolic value also specifies the permissions that are not allowed. See "Notes."

Without any arguments, umask displays the file-creation permissions mask.

Notes

Most utilities and applications do not attempt to create files with execute permissions, regardless of the value of mask; they assume that you do not want an executable file. As a result, when a utility or application such as touch creates a file, the system subtracts each of the digits in mask from 6. The exception is mkdir, which assumes that you do want the execute (access in the case of a directory) bit set. See "Examples."

The umask program is a builtin in bash and tcsh and generally goes in the initialization file for your shell (~/.bash_profile [bash] or ~/.login [tcsh]).

Under bash the argument u=rwx,go=r turns off all bits in the mask for the owner and turns on the write bit in the mask for groups and other users (the mask is 0033), causing those bits to be on in file permissions (744 or 644). Refer to chmod on page 676 for more information about symbolic permissions.

Examples

The following commands set the file-creation permissions mask and display the mask and its effect when you create a file and a directory. The mask of 022, when subtracted from 777, gives permissions of 644 (rwrr) for a file and 755 (rwxrxrx) for a directory:

$ umask 022 $ umask 0022 $ touch afile $ mkdir adirectory $ ls -ld afile adirectory drwxr-xr-x  2 max  max  4096 Jul 24 11:25 adirectory -rw-r--r--  1 max  max  0 Jul 24 11:25 afile


The next example sets the same mask value symbolically:

$ umask u=rwx,g=rx,o=rx $ umask 0022


uniq: Displays unique lines

uniq [options] [input-file] [output-file]

The uniq utility displays its input, removing all but one copy of successive repeated lines. If the file has been sorted (see sort on page 837), uniq ensures that no two lines that it displays are the same.

Arguments

When you do not specify the input-file, uniq reads from standard input. When you do not specify the output-file, uniq writes to standard output.

Options

A field is a sequence of characters bounded by SPACEs, TABs, NEWLINEs, or a combination of these characters.

c

(count) Precedes each line with the number of occurrences of the line in the input file.

d

(duplicates) Displays one copy of lines that are repeated; does not display lines that are not repeated.

f

nfield

 

(fields) Ignores the first nfield blank-separated fields of each line. The uniq utility bases its comparison on the remainder of the line, including the leading blanks of the next field on the line (see the s option).

s

nchar

 

(skip) Ignores the first nchar characters of each line. If you also use the skip-fields option, uniq ignores the first nfield fields followed by nchar characters. You can use this option to skip over leading blanks of a field.

u

(unique) Displays only lines that are not repeated.


Examples

These examples assume that the file named test in the working directory contains the following text:

$ cat test boy took bat home boy took bat home girl took bat home dog brought hat home dog brought hat home dog brought hat home


Without any options, uniq displays one copy of successive repeated lines:

$ uniq test boy took bat home girl took bat home dog brought hat home


The c option displays the number of consecutive occurrences of each line in the file:

$ uniq -c test    2 boy took bat home    1 girl took bat home    3 dog brought hat home


The d option displays only lines that are consecutively repeated in the file:

$ uniq -d test boy took bat home dog brought hat home


The u option displays only lines that are not consecutively repeated in the file:

$ uniq -u test girl took bat home


Next the f option skips the first field in each line, causing the lines that begin with boy and the line that begins with girl to appear to be consecutive repeated lines. The uniq utility displays only one occurrence of these lines:

$ uniq -f 1 test boy took bat home dog brought hat home


The next example uses the f and s options first to skip two fields and then to skip two characters. The two characters this command skips include the SPACE that separates the second and third fields and the first character of the third field. Ignoring these characters, all the lines appear to be consecutive repeated lines containing the string at home. The uniq utility displays only the first of these lines:

$ uniq -f 2 -s 2 test boy took bat home


w: Displays information about system users

w [options] [user-list]

The w utility displays the names of users who are currently logged in, together with their terminal device numbers, the times they logged in, the commands they are running, and other information.

Arguments

The user-list restricts the display to information about the specified users.

Options

h (no header) Suppresses the header line.

Discussion

The first line that w displays is the same as that displayed by uptime. This line includes the time of day, how long the system has been running (in days, hours, and minutes), how many users are logged in, and how busy the system is (load average). From left to right, the load averages indicate the number of processes that have been waiting to run in the past 1 minute, 5 minutes, and 15 minutes.

The columns of information that w displays have the following headings:

USER TTY FROM LOGIN@ IDLE WHAT


USER is the username of the user. TTY is the device name for the line that the user is on. FROM is the system name that a remote user is logged in from; it is a hyphen for a local user. LOGIN@ gives the date and time the user logged in. IDLE indicates how many minutes have elapsed since the user last used the keyboard. WHAT is the command that user is running.

Examples

The following example shows the full list produced by the w utility:

$ w 20:42  up 2 days, 3:58, 4 users, load averages: 0.04 0.02 0.00 USER    TTY      FROM              LOGIN@  IDLE WHAT zach    console  -                Sun16   2days - zach    p1       -                Sun16   26:47 /usr/bin/less -is zach    p2       -                Mon16       1 vim zach    p3       bravo.example.co Mon16       - w


wc: Displays the number of lines, words, and bytes

wc [options] [file-list]

The wc utility displays the number of lines, words, and bytes in its input. When you specify more than one file on the command line, wc displays the totals for each file as well as the totals for the group of files.

Arguments

The file-list specifies the pathnames of one or more files that wc analyzes. If you do not specify a file-list, wc takes its input from standard input.

Options

c

(characters) Displays only the number of (8-bit) bytes in the input.

l

(lines, lowercase "l") Displays only the number of lines (that is, NEWLINE characters) in the input.

m

(multibyte) Displays only the number of characters in the input.

w

(words) Displays only the number of words in the input.


Notes

A word is a sequence of characters bounded by SPACEs, TABs, NEWLINEs, or a combination of these characters.

Examples

The following command analyzes the file named memo. The numbers in the output indicate the number of lines, words, and bytes in the file:

$ wc memo       5     31     146 memo


The next command displays the number of lines and words in three files. The line at the bottom, with the word total in the right column, contains the sum of each column.

$ wc -lw memo1 memo2 memo3      10     62 memo1      12     74 memo2      12     68 memo3      34    204 total


which: Shows where in PATH a command is located

which command-list

The which utility displays the absolute pathname of commands.

Arguments

The command-list specifies one or more commands (utilities) that which searches for. For each command, which searches the directories listed in the PATH environment variable (page 285), in order, and displays the absolute pathname of the first command (executable file) it finds. If which does not locate a command, it displays an error message.

Options

The which utility does not take any options.

Notes

The TC Shell includes a which builtin (see the tcsh man page) that works slightly differently from the which utility (/usr/bin/which). The which utility does not locate functions or shell builtins because these do not appear in PATH. In contrast, the tcsh which builtin locates aliases, functions, and shell builtins.

The which utility is a csh script and uses the csh startup file (.cshrc) regardless of which shell you call it from.

Examples

The first example quotes the first letter of the command (\which) to prevent the shell from invoking an alias (page 312) for which:

$ \which vim which xxx /usr/bin/vim /usr/bin/which no xxx in /bin /sbin /usr/bin /usr/sbin .


The next example is the same as the previous one except that it is run from tcsh. The tcsh which builtin is used instead of the which utility:

tcsh $ which vim which xxx /usr/bin/vim which: shell built-in command. xxx: Command not found.


who: Displays information about logged-in users

who [options]

who am i

The who utility displays information about users who are logged in on the local system. This information includes each user's username, terminal device, and login time, and, if applicable, the corresponding remote hostname or X display.

Arguments

When given the arguments am i, who displays information about the user giving the command.

Options

Accepts the common options described on page 663.

a

(all) Displays a lot of information.

b

(boot) Displays the date and time the system was last booted.

H

(header) Displays a header.

l

(logins, lowercase "l") Lists devices waiting for a user to log in.

q

(quick) Lists usernames only, followed by the number of users logged in on the system.

T

(tty mode) Appends after each username a character indicating whether that user has messages enabled. A plus (+) means that messages are enabled, a hyphen (-) means that they are disabled, and a question mark (?) indicates that who cannot find the device. If messages are enabled, you can use write (page 63) to communicate with the user. Refer to "mesg: Denies or Accepts Messages" on page 64.

u

(user idle) Includes each user's idle time in the display. If the user has typed on her terminal in the past minute, a period (.) appears in this field. If no input has occurred for more than a day, the word old appears. In addition, this option includes the PID number and comment fields. See "Discussion."


Discussion

The line that who displays has the following syntax:

user [messages] line login-time [idle] comment


The user is the username of the user. The messages indicates whether messages are enabled or disabled (see the T option). The line is the device name associated with the line the user is logged in on. The login-time is the date and time that the user logged in. The idle is the length of time since the terminal was last used (the idle time; see the u option). The comment column is the remote system or X display that the user is logged in from (blank for local users).

Notes

The finger utility (page 734) provides information similar to that given by who.

Examples

The following examples demonstrate the use of the who utility:

$ who zach     console  May  8 16:46 zach     ttyp1    May  8 16:47 zach     ttyp2    May  9 16:11 zach     ttyp3    May  9 16:15 (bravo.example.co) $ who am i zach     ttyp3    May  9 16:15 (bravo.example.co) $ who -H -u -T NAME     S LINE     TIME         IDLE  FROM zach     - console  May  8 16:46  old zach     + ttyp1    May  8 16:47 00:02 zach     + ttyp2    May  9 16:11   . zach     + ttyp3    May  9 16:15   .  (bravo.example.co)


xargs: Converts standard input into command lines

xargs [options] [command]

The xargs utility is a convenient, efficient way to convert standard output of one command into arguments for another command. This utility reads from standard input, keeps track of the maximum allowable length of a command line, and avoids exceeding that limit by repeating command as needed. It then executes the newly constructed command line.

Arguments

The command is the command line that xargs uses as a base for the command it constructs. If you do not specify a command, xargs uses echo. The xargs utility appends to command the arguments it receives from standard input. If any arguments should precede the arguments from standard input, you must include them as part of command.

Options

0

(null, number 0) Arguments from standard input are separated by null characters instead of SPACEs or NEWLINEs. See the print0 action criterion for find (page 730).

I marker

 

(insert) Allows you to place arguments from standard input anywhere within command. A maximum of five occurrences of marker in command for xargs are replaced by the arguments generated from standard input of xargs. With this option, command is executed for each input line.

L [num]

 

(lines) Executes command once for every num lines of input (num defaults to 1).

n num

 

(number) Executes command once for every num arguments in the input line.

p

(prompt) Asks the user for confirmation of each command before running it.

R

replacements

 

(replacements) Specifies the number of times to replace marker with arguments from standard input; the default is 5. Works only with the I option.


Discussion

The xargs utility reads arguments to command from standard input, interpreting each whitespace-delimited string as a separate argument. It then constructs a command line from command and a series of arguments. When the maximum command line length would be exceeded by adding another argument, xargs runs the command line it has built. If more input is present, xargs repeats the process of building a command line and running it. This process continues until all input has been read.

Notes

The xargs utility is often employed as an efficient alternative to the exec option of find (page 729). If you call find with the exec option to run a command, it runs the command once for each file it processes. Each execution of the command creates a new process, which can drain system resources when you are processing many files. By accumulating as many arguments as possible, xargs can greatly reduce the number of processes needed. The first example in the "Examples" section shows how to use xargs with find.

Examples

To locate and remove all files whose names end in .o from the working directory and its subdirectories, you can use find with the exec option:

$ find . -name \* .o -exec rm -f {} \;


This approach calls the rm utility once for each .o file that find locates. Each invocation of rm requires a new process. If a lot of .o files exist, a significant amount of time is spent creating, starting, and then cleaning up these processes. You can reduce the number of processes by allowing xargs to accumulate as many filenames as possible before calling rm:

$ find . -name \* .o -print | xargs rm -f


In the next example, the contents of all * .txt files located by find are searched for lines containing the word login. All filenames that contain login are displayed by grep.

$ find . -name \* .txt -print | xargs grep -w -l login


The next example shows how you can use the I option to cause xargs to embed standard input within command instead of appending it to command. This option also causes command to be executed each time a NEWLINE character is encountered in standard input.

$ cat names Tom, Dick, and Harry $ xargs echo "Hello, " < names Hello, Tom, Dick, and Harry $ xargs -I X echo "Hello X.  Join me for lunch?" <names Hello Tom,. Join me for lunch? Hello Dick,. Join me for lunch? Hello and Harry. Join me for lunch?


The next example uses the same input file as the previous example as well as the n option:

$ xargs echo "Hi there" < names Hi there Tom, Dick, and Harry $ xargs -n 1 echo "Hi there" < names Hi there Tom, Hi there Dick, Hi there and Hi there Harry


The final example shows the use of the print0 criterion to find, and the 0 option to xargs:

$ ls $ cp /dev/null 'Newline > File' $ ls Newline?File $ find . -print | xargs ls ls: ./Newline: No such file or directory ls: File: No such file or directory .: Newline?File $ find . -print0 | xargs -0 ls ./Newline?File .: Newline?File $


In this example, the potential problem seems harmless. However, systems have been compromised through the use of files with names containing NEWLINEs in conjunction with carelessly written system administration scripts.

See page 849 for another example of the use of xargs.




A Practical Guide to UNIX[r] for Mac OS[r] X Users
A Practical Guide to UNIX for Mac OS X Users
ISBN: 0131863339
EAN: 2147483647
Year: 2005
Pages: 234

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net