Linux Commands (Linux in a Nutshell, 3rd Edition) Book HomeLinux in a NutshellSearch this book


Chapter 3. Linux Commands

Contents:

Alphabetical Summary of Commands

This chapter presents the Linux user, programmer, and system administration commands. Each entry is labeled with the command name on the outer edge of the page. The syntax line is followed by a brief description and a list of available options. Many commands come with examples at the end of the entry. If you need only a quick reminder or suggestion about a command, you can skip directly to the examples.

Typographic conventions for describing command syntax are listed in the Preface. For help in locating commands, see the index at the back of this book.

We've tried to be as thorough as possible in listing options. The basic command information and most options should be correct; however, there are many Linux distributions and many versions of commands. New options are added and sometimes old options are dropped. You may, therefore, find some differences between the options you find described here and the ones on your system. When there seems to be a discrepancy, check the manpage. For most commands you can also use the option --help to get a brief usage message. (Even when it isn't a valid option, it will usually result in an "invalid option" error along with the usage message.)

Traditionally, commands take single-letter options preceded by a single hyphen, like -d. A more recent convention allows long options preceded by two hyphens, like --debug. Often, a feature can be invoked through either the old style or the new style of options.

3.1. Alphabetical Summary of Commands

agetty

agetty [options] port baudrate [term]

System administration command. The Linux version of getty. Set terminal type, modes, speed, and line discipline. agetty is invoked by init. It is the second process in the series init-getty-login-shell, which ultimately connects a user with the Linux system. agetty reads the user's login name and invokes the login command with the user's name as an argument. While reading the name, agetty attempts to adapt the system to the speed and type of device being used.

You must specify a port, which agetty will search for in the /dev directory. You may use -, in which case agetty reads from standard input. You must also specify baudrate, which may be a comma-separated list of rates, through which agetty will step. Optionally, you may specify the term, which is used to override the TERM environment variable.

Options

-h

Specify hardware, not software, flow control.

-i

Suppress printing of /etc/issue before printing the login prompt.

-l program

Specify the use of program instead of /bin/login.

-m

Attempt to guess the appropriate baud rate.

-t timeout

Specify that agetty should exit if the open on the line succeeds and there is no response to the login prompt in timeout seconds.

-L

Do not require carrier detect; operate locally only. Use this when connecting terminals.

apmd

apmd [options]

System administration command. apmd handles events reported by the Advanced Power Management BIOS driver. The driver reports on battery level and requests to enter sleep or suspend mode. apmd will log any reports it gets via syslogd and take steps to make sure that basic sleep and suspend requests are handled gracefully. You can fine-tune the behavior of apmd by specifying an apmd_proxy command to run when it receives an event.

Options

-c n, --check n

Set the number of seconds to wait for an event before rechecking the power level. Default is to wait indefinitely. Setting this causes the battery levels to be checked more frequently.

-P command, --apmd_prxy command

Specify the apmd_proxy command to run when APM driver events are reported. This is generally a shell script. The command will be invoked with parameters indicating what kind of event was received. The parameters are in the next list.

-p n, --percentage n

Log information whenever the power changes by n percent. The default is 5. Values greater than 100 will disable logging of power changes.

-V, --version

Print version and exit.

-v, --version

Verbose mode; all events are logged.

-W, --wall

Use wall to alert all users of a low battery status.

-w n, --warn n

Log a warning at ALERT level when the battery charge drops below n percent. The default is 10. Negative values disable low battery level warnings.

-q, --quiet

Disable low battery level warnings.

-?, --help

Print help summary and exit.

Parameters

The apmd proxy script will be invoked with the following parameters:

start

Invoked when the daemon starts.

stop

Invoked when the daemon stops.

suspend [ system | user ]

Invoked when a suspend request has been made. The second parameter indicates whether the request was made by the system or by the user.

standby [ system | user ]

Invoked when a standby request has been made. The second parameter indicates whether the request was made by the system or by the user.

resume [ suspend | standby | critical ]

Invoked when the system resumes normal operation. The second parameter indicates the mode the system was in before resuming. (critical suspends indicate an emergency shutdown. After a critical suspend the system may be unstable and you can use the resume command to help you recover from the suspension.

change power

Invoked when system power is changed from AC to battery or from battery to AC.

change battery

Invoked when the APM BIOS driver reports that the battery is low.

change capability

Invoked when the APM BIOS driver reports some hardware that affects its capability has been added or removed.

apropos

apropos string ...

Search the short manual page descriptions in the whatis database for occurrences of each string and display the result on the standard output. Like whatis, except that it searches for strings instead of words. Equivalent to man -k.

ar

ar [-V] key [args] [posname] archive [files]

Maintain a group of files that are combined into a file archive. Used most commonly to create and update library files as used by the link editor (ld). Only one key letter may be used, but each can be combined with additional args (with no separations between). posname is the name of a file in archive. When moving or replacing files, you can specify that they be placed before or after posname. -V prints the version number of ar on standard error.

Key

d

Delete files from archive.

m

Move files to end of archive.

p

Print files in archive.

q

Append files to archive.

r

Replace files in archive.

t

List the contents of archive or list the named files.

x

Extract contents from archive or only the named files.

Arguments

a

Use with r or m key to place files in the archive after posname.

b

Same as a but before posname.

c

Create archive silently.

f

Truncate long filenames.

i

Same as b.

l

For backward compatibility; meaningless in Linux.

o

Preserve original timestamps.

s

Force regeneration of archive symbol table (useful after running strip).

S

Do not regenerate symbol table.

u

Use with r to replace only files that have changed since being put in archive.

v

Verbose; print a description of actions taken.

Example

Replace mylib.a with object files from the current directory:

ar r mylib.a `ls *.o
arch

arch

Print machine architecture type to standard output. Equivalent to uname -m.

arp

arp [options]

TCP/IP command. Clear, add to, or dump the kernel's ARP cache (/proc/net/arp).

Options

-v

Verbose mode.

-t type

Search for type entries when examining the ARP cache. type must be ether (Ethernet) or ax25 (AX.25 packet radio); ether is the default.

-a [hosts]

Display hosts' entries or, if none are specified, all entries.

-d host

Remove host's entry.

-s host hardware-address

Add the entry host hardware-address, where ether class addresses are 6 hexadecimal bytes, colon-separated.

-f file

Read entries from file and add them.

as

as [options] files

Generate an object file from each specified assembly language source file. Object files have the same root name as source files but replace the .s suffix with .o. There may be some additional system-specific options.

Options

-- [ | files]

Read input files from standard input, or from files if the pipe is used.

-a[dhlns][=file]

With only the -a option, list source code, assembler listing, and symbol table. The other options specify additional things to list or omit:

-ad

Omit debugging directives.

-ah

Include the high-level source code, if available.

-al

Include an assembly listing.

-an

Suppress forms processing.

-as

Include a symbol listing.

=file

Set the listing filename to file.

-defsym symbol=value

Define the symbol to have the value value, which must be an integer.

-f

Skip preprocessing.

--gstabs

Generate stabs debugging information.

-o objfile

Place output in object file objfile (default is file.o).

-v

Display the version number of the assembler.

-I path

Include path when searching for .include directives.

-K

Warn before altering difference tables.

-L

Do not remove local symbols, which begin with L.

-R

Combine both data and text in text section.

-W

Quiet mode.

at

at [options] time

Execute commands at a specified time and optional date. The commands are read from standard input or from a file. (See also batch.) End input with EOF. time can be formed either as a numeric hour (with optional minutes and modifiers) or as a keyword. It can contain an optional date, formed as a month and date, a day of the week, or a special keyword (today or tomorrow). An increment can also be specified.

The at command can always be issued by a privileged user. Other users must be listed in the file /etc/at.allow if it exists; otherwise, they must not be listed in /etc/at.deny. If neither file exists, only a privileged user can issue the command.

Options

-c job [job...]

Display the specified jobs on the standard output. This option does not take a time specification.

-d job [job...]

Delete the specified jobs. Same as atrm.

-f file

Read job from file, not standard input.

-l

Report all jobs that are scheduled for the invoking user. Same as atq.

-m

Mail user when job has completed, regardless of whether output was created.

-q letter

Place job in queue denoted by letter, where letter is any single letter from a-z or A-Z. Default queue is a. (The batch queue defaults to b.) Higher-lettered queues run at a lower priority.

-V

Display the version number.

Time

hh:mm [modifiers]

Hours can have one digit or two (a 24-hour clock is assumed by default); optional minutes can be given as one or two digits; the colon can be omitted if the format is h, hh, or hhmm; (e.g., valid times are 5, 5:30, 0530, 19:45). If modifier am or pm is added, time is based on a 12-hour clock. If the keyword zulu is added, times correspond to Greenwich Mean Time.

midnight | noon | teatime | now

Use any one of these keywords in place of a numeric time. teatime translates to 4:00 p.m.; now must be followed by an increment.

Date

month num[, year]

month is one of the 12 months, spelled out or abbreviated to its first three letters; num is the calendar date of the month; year is the four-digit year. If the given month occurs before the current month, at schedules that month next year.

day

One of the seven days of the week, spelled out or abbreviated to its first three letters.

today | tomorrow

Indicate the current day or the next day. If date is omitted, at schedules today when the specified time occurs later than the current time; otherwise, at schedules tomorrow.

Increment

Supply a numeric increment if you want to specify an execution time or day relative to the current time. The number should precede any of the keywords minute, hour, day, week, month, or year (or their plural forms). The keyword next can be used as a synonym of + 1.

Examples

Note that the first two commands are equivalent:

at 1945 pm December 9
at 7:45pm Dec 9
at 3 am Saturday
at now + 5 hours
at noon next day

atq

atq [options]

List the user's pending jobs, unless the user is a privileged user; in that case, everybody's jobs are listed. Same as at -l.

Options

-q queue

Query only the specified queue and ignore all other queues.

-v

Show jobs that have completed but not yet been deleted.

-V

Print the version number.

atrm

atrm [options] job [job...]

Delete jobs that have been queued for future execution. Same as at -d.

Options

-q queue

Remove job from the specified queue.

-V

Print the version number and then exit.

badblocks

badblocks [options] device block-count

System administration command. Search device for bad blocks. You must specify the number of blocks on the device (block-count).

Options

-b blocksize

Expect blocksize-byte blocks.

-o file

Direct output to file.

-v

Verbose mode.

-w

Test by writing to each block and then reading back from it.

banner

banner [option] [characters]

Print characters as a poster. If no characters are supplied, banner prompts for them and reads an input line from standard input. By default, the results go to standard output, but they are intended to be sent to a printer.

Option

-w width

Set width to width characters. Note that if your banner is in all lowercase, it will be narrower than width characters. If -w is not specified, the default width is 132. If -w is specified but width is not provided, the default is 80.

Example

/usr/games/banner -w50 Happy Birthday! |lpr
basename

basename name [suffix]

basename option

Remove leading directory components from a path. If suffix is given, remove that also. The result is printed to standard output.

Options

--help

Print help message and then exit.

--version

Print the version number and then exit.

Examples

% basename /usr/lib/libm.a
libm.a

% basename /usr/lib/libm.a .a
libm
batch

batch [options] [time]

Execute commands entered on standard input. If time is omitted, execute them when the system load permits (when the load average falls below 0.8). Very similar to at, but does not insist that the execution time be entered on the command line. See at for details.

Options

-f file

Read job from file, not standard input.

-m

Mail user when job has completed, regardless of whether output was created.

-q letter

Place job in queue denoted by letter, where letter is one letter from a-z or A-Z. The default queue is a. (The batch queue defaults to b.) Higher-lettered queues run at a lower priority.

-V

Print the version number and then exit.

-v

Display the time a job will be executed.

bash

bash [options] [file [arguments;]]

sh [options] [file [arguments]]

Standard Linux shell, a command interpreter into which all other commands are entered. For more information, see Chapter 7, "bash: The Bourne-Again Shell".

bc

bc [options] [files]

bc is a language (and compiler) whose syntax resembles that of C, but with unlimited-precision arithmetic. bc consists of identifiers, keywords, and symbols, which are briefly described in the following entries. Examples are given at the end.

Interactively perform arbitrary-precision arithmetic or convert numbers from one base to another. Input can be taken from files or read from the standard input. To exit, type quit or EOF.

Options

-l, --mathlib

Make functions from the math library available.

-s, --standard

Ignore all extensions, and process exactly as in POSIX.

-w, --warn

When extensions to POSIX bc are used, print a warning.

-q, --quiet

Do not display welcome message.

-v, --version

Print version number.

Identifiers

An identifier is a series of one or more characters. It must begin with a lowercase letter but may also contain digits and underscores. No uppercase letters are allowed. Identifiers are used as names for variables, arrays, and functions. Variables normally store arbitrary-precision numbers. Within the same program you may name a variable, an array, and a function using the same letter. The following identifiers would not conflict:

x

Variable x.

x[i]

Element i of array x. i can range from 0 to 2047 and can also be an expression.

x(y,z)

Call function x with parameters y and z.

Input-output keywords

ibase, obase, scale, and last store a value. Typing them on a line by themselves displays their current value. You can also change their values through assignment. The letters A-F are treated as digits whose values are 10-15.

ibase = n

Numbers that are input (e.g., typed) are read as base n (default is 10).

obase = n

Numbers that are displayed are in base n (default is 10). Note: Once ibase has been changed from 10, use A to restore ibase or obase to decimal.

scale = n

Display computations using n decimal places (default is 0, meaning that results are truncated to integers). scale is normally used only for base-10 computations.

last

Value of last printed number.

Statement keywords

A semicolon or a newline separates one statement from another. Curly braces are needed when grouping multiple statements.

if (rel-expr) {statements} [else {statements}]

Do one or more statements if relational expression rel-expr is true. Otherwise, do nothing, or if else (an extension) is specified, do alternative statements. For example:

     if(x==y) {i = i + 1} else {i = i - 1}
while (rel-expr) {statements}

Repeat one or more statements while rel-expr is true; for example:

     while(i>0) {p = p*n; q = a/b; i = i-1}
for (expr1;rel-expr;expr2) {statements}

Similar to while; for example, to print the first 10 multiples of 5, you could type:

     for(i=1; i<=10; i++) i*5

GNU bf does not require three arguments to for. A missing argument 1 or 3 means that those expressions will never be evaluated. A missing argument 2 evaluates to the value 1.

break

Terminate a while or for statement.

print list

GNU extension. It provides an alternate means of output. list consists of a series of comma-separated strings and expressions; print displays these entities in the order of the list. It does not print a newline when it terminates. Expressions are evaluated, printed, and assigned to the special variable last. Strings (which may contain special characters, i.e., characters beginning with \) are simply printed. Special characters can be:

a

Alert or bell

b

Backspace

f

Form feed

n

Newline

r

Carriage return

q

Double quote

t

Tab

\

Backslash

continue

GNU extension. When within a for statement, jump to the next iteration.

halt

GNU extension. Cause the bc processor to quit.

limits

GNU extension. Print the limits enforced by the local version of bc.

Function keywords

define f(args) {

Begin the definition of function f having the arguments args. The arguments are separated by commas. Statements follow on successive lines. End with a }.

auto x, y

Set up x and y as variables local to a function definition, initialized to 0 and meaningless outside the function. Must appear first.

return(expr)

Pass the value of expression expr back to the program. Return 0 if (expr) is left off. Used in function definitions.

sqrt(expr)

Compute the square root of expression expr.

length(expr)

Compute how many significant digits are in expr.

scale(expr)

Same as length, but count only digits to the right of the decimal point.

read( )

GNU extension. Read a number from standard input. Return value is the number read, converted via the value of ibase.

Math library functions

These are available when bc is invoked with -l. Library functions set scale to 20.

s(angle)

Compute the sine of angle, a constant or expression in radians.

c(angle)

Compute the cosine of angle, a constant or expression in radians.

a(n)

Compute the arctangent of n, returning an angle in radians.

e(expr)

Compute e to the power of expr.

l(expr)

Compute the natural log of expr.

j(n, x)

Compute the Bessel function of integer order n.

Operators

These consist of operators and other symbols. Operators can be arithmetic, unary, assignment, or relational:

arithmetic

+ - * / % ^

unary

- ++ --

assignment

=+ =- =* =/ =% =^ =

relational

< <= > >= == !=

Other symbols

/* */

Enclose comments.

()

Control the evaluation of expressions (change precedence). Can also be used around assignment statements to force the result to print.

{}

Use to group statements.

[]

Indicate array index.

"text"

Use as a statement to print text.

Examples

Note in these examples that when you type some quantity (a number or expression), it is evaluated and printed, but assignment statements produce no display.

ibase = 8       Octal input
20              Evaluate this octal number
16              Terminal displays decimal value
obase = 2       Display output in base 2 instead of base 10
20              Octal input
10000           Terminal now displays binary value
ibase = A       Restore base-10 input
scale = 3       Truncate results to 3 decimal places
8/7             Evaluate a division
1.001001000     Oops!  Forgot to reset output base to 10
obase=10        Input is decimal now, so A isn't needed
8/7
1.142           Terminal displays result (truncated)

The following lines show the use of functions:

define p(r,n){  Function p uses two arguments
auto v          v is a local variable
v = r^n         r raised to the n power
return(v)}      Value returned

scale=5
x=p(2.5,2)      x = 2.5 ^ 2
x               Print value of x
6.25
length(x)       Number of digits
3
scale(x)        Number of places right of decimal point
2

biff

biff [arguments]

Notify user of mail arrival and sender's name. biff operates asynchronously. Mail notification works only if your system is running the comsat(8) server. The command biff y enables notification, and the command biff n disables notification. With no arguments, biff reports biff's current status.

bison

bison [options] file

Given a file containing context-free grammar, convert into tables for subsequent parsing while sending output to file.c. This utility is both to a large extent compatible with yacc and named for it. All input files should use the suffix .y; output files will use the original prefix. All long options (those preceded by --) may instead be preceded by +.

Options

-b prefix, --file-prefix=prefix

Use prefix for all output files.

-d, --defines

Generate file.h, producing #define statements that relate bison's token codes to the token names declared by the user.

-r, --raw

Use bison token numbers, not yacc-compatible translations, in file.h.

-k, --token-table

Include token names and values of YYNTOKENS, YYNNTS, YYNRULES, and YYNSTATES in file.c.

-l, --no-lines

Exclude #line constructs from code produced in file.c. (Use after debugging is complete.)

-n, --no-parser

Suppress parser code in output, allowing only declarations. Assemble all translations into a switch statement body and print it to file.act.

-o file, --output-file=file

Output to file.

-p prefix, --name-prefix=prefix

Substitute prefix for yy in all external symbols.

-t, --debug

Compile runtime debugging code.

-v, --verbose

Verbose mode. Print diagnostics and notes about parsing tables to file.output.

-V, --version

Display version number.

-y, --yacc, --fixed-output-files

Duplicate yacc's conventions for naming output files.

bootpd

bootpd [options] [configfile [dumpfile] ]

TCP/IP command. Internet Boot Protocol server. bootpd normally is run by /etc/inetd by including the following line in the file /etc/inetd.conf:

bootps dgram udp wait root /etc/bootpd bootpd

This causes bootpd to be started only when a boot request arrives. It may also be started in standalone mode, from the command line. Upon startup, bootpd first reads its configuration file, /etc/bootptab (or the configfile listed on the command line), then begins listening for BOOTREQUEST packets.

bootpd looks in /etc/services to find the port numbers it should use. Two entries are extracted: bootps -- the bootp server listening port -- and bootpc -- the destination port used to reply to clients.

If bootpd is compiled with the -DDEBUG option, receipt of a SIGUSR1 signal causes it to dump its memory-resident database to the file /etc/bootpd.dump or the command-line specified dumpfile.

Options

-c directory

Force bootpd to work in directory.

-d level

Specify the debugging level. Omitting level will increment the level by 1.

-t timeout

Specify a timeout value in minutes. A timeout value of 0 means wait forever.

Configuration file

The bootpd configuration file has a format in which two-character, case-sensitive tag symbols are used to represent host parameters. These parameter declarations are separated by colons. The general format is:

hostname:tg=value:tg=value:tg=value

where hostname is the name of a bootp client and tg is a tag symbol. The currently recognized tags are listed next.

Tags

Tag Meaning
bf Bootfile
bs Bootfile size in 512-octet blocks
cs Cookie server address list
ds Domain name server address list
gw Gateway address list
ha Host hardware address
hd Bootfile home directory
hn Send hostname
ht Host hardware type (see Assigned Numbers RFC)
im Impress server address list
ip Host IP address
lg Log server address list
lp lpr server address list
ns IEN-116 name server address list
rl Resource location protocol server address list
sm Host subnet mask
tc Table continuation
to Time offset in seconds from UTC
ts Time server address list
vm Vendor magic cookie selector

There is also a generic tag, Tn, where n is an RFC 1048 vendor field tag number. Generic data may be represented as either a stream of hexadecimal numbers or as a quoted string of ASCII characters.

bootpgw

bootpgw [options] server

Internet Boot Protocol Gateway. Maintain a gateway that forwards bootpd requests to server. In addition to dealing with BOOTREPLY packets, also deal with BOOTREQUEST packets. bootpgw is normally run by /etc/inetd by including the following line in the file /etc/inetd.conf:

bootps dgram udp wait root /etc/bootpgw bootpgw

This causes bootpgw to be started only when a boot request arrives. bootpgw takes all the same options as bootpd, except -c.

bootptest

bootptest [options] server [template]

TCP/IP command. Test server's bootpd daemon by sending requests every second for 10 seconds or until the server responds. Read options from the template file, if provided.

Options

-f file

Read the boot filename from file.

-h

Identify client by hardware, not IP, address.

-m magic-number

Provide magic-number as the first word of the vendor options field.

bzip2

bzip2 [options] filenames

bunzip2 [options] filenames

bzcat [option] filenames

bzip2recover filenames

File compression and decompression utility similar to gzip, but uses a different algorithm and encoding method to get better compression. bzip2 replaces each file in filenames with a compressed version of the file and with a .bz2 extension appended. bunzip2 decompresses each file compressed by bzip2 (ignoring other files, except to print a warning). bzcat decompresses all specified files to standard output, and bzip2recover is used to try to recover data from damaged files.

Options

--

End of options; treat all subsequent arguments as filenames.

-dig

Set block size to dig × 100KB when compressing, where dig is a single digit from 1 to 9.

-c, --stdout

Compress or decompress to standard output.

-d, --decompress

Force decompression.

-f, --force

Force overwrite of output files. Default is not to overwrite. Also forces breaking of hard links to files.

-k, --keep

Keep input files; don't delete them.

-L, --license, -V, --version

Print license and version information and exit.

-q, --quiet

Quiet. Print only critical messages.

-s, --small

Use less memory, at the expense of speed.

-t, --test

Check the integrity of the files, but don't actually compress them.

-v, --verbose

Verbose. Show the compression ratio for each file processed. Add more -v's to increase the verbosity.

-z, --compress

Forces compression, even if invoked as bunzip2 or bzcat.

--repetitive-fast, --repetitive-best

Sometimes useful in versions earlier than 0.9.5 (which has an improved sorting algorithm) for providing some control over the algorithm.

c++

c++ [options] files

See g++.

cal

cal [-jy] [[month] year]

Print a 12-month calendar (beginning with January) for the given year or a one-month calendar of the given month and year. month ranges from 1 to 12. year ranges from 1 to 9999. With no arguments, print a calendar for the current month.

Options

-j

Display Julian dates (days numbered 1 to 365, starting from January 1).

-m

Display Monday as the first day of the week.

-y

Display entire year.

Examples

cal 12 1995
cal 1994 > year_file
cardctl

cardctl [options] command

System administration command. Control PCMCIA sockets or select the current scheme. The current scheme is sent along with the address of any inserted cards to configuration scripts (by default located in /etc/pcmcia). The scheme command displays or changes the scheme. The other commands operate on a named card socket number or, if no number is given, all sockets.

Commands

config [socket]

Display current socket configuration.

eject [socket]

Prepare the system for the card(s) to be ejected.

ident [socket]

Display card identification information.

insert [socket]

Notify system that a card has been inserted.

reset [socket]

Send reset signal to card.

resume [socket]

Restore power to socket and reconfigure for use.

scheme [name]

Display current scheme or change to specified scheme name.

status [socket]

Display current socket status.

suspend [socket]

Shut down device and cut power to socket.

Options

-c directory

Look for card configuration information in directory instead of /etc/pcmcia.

-f file

Use file to keep track of the current scheme instead of /var/run/pcmcia-scheme.

-s file

Look for current socket information in file instead of /var/run/stab.

cardmgr

cardmgr [options]

System administration command. The PCMCIA card daemon. cardmgr monitors PCMCIA sockets for devices that have been added or removed. When a card is detected, it attempts to get the card's ID and configure it according to the card configuration database (usually stored in /etc/pcmcia/config). By default, cardmgr both creates a system log entry when it detects cards and beeps. Two high beeps mean it successfully identified and configured a device. One high beep followed by one low beep means it identified the device, but was unable to configure it successfully. One low beep means it could not identify the inserted card. Information on the currently configured cards can be found in /var/run/stab.

Options

-cdirectory

Look in directory for the card configuration database instead of /etc/pcmcia.

-d

use modprobe instead of insmod to load the PCMCIA device driver.

-f

Run in the foreground to process the current cards, then run as a daemon.

-mdirectory

Look in directory for card device modules instead of /lib/modules/ `uname -r`.

-o

Configure the cards present in one pass, then exit.

-pfile

Write cardmgr's process ID to file instead of /var/run/cardmgr.pid.

-q

Run in quiet mode. No beeps.

-sfile

Write current socket information to file instead of /var/run/stab.

-v

Verbose mode.

-V

Print version number and exit.

cat

cat [options] [files]

Read (concatenates) one or more files and print them on standard output. Read standard input if no files are specified or if - is specified as one of the files; input ends with EOF. You can use the > operator to combine several files into a new file or >> to append files to an existing file.

Options

-A, --show-all

Same as -vET.

-b, --number-nonblank

Number all nonblank output lines, starting with 1.

-e

Same as -vE.

-E, --show-ends

Print $ at the end of each line.

-n, --number

Number all output lines, starting with 1.

-s, --squeeze-blank

Squeeze down multiple blank lines to one blank line.

-t

Same as -vT.

-T, --show-tabs

Print TAB characters as ^I.

-u

Ignored; retained for Unix compatibility.

-v, --show-nonprinting

Display control and nonprinting characters, with the exception of LINEFEED and TAB.

Examples

cat ch1               Display a file
cat ch1 ch2 ch3 > all Combine files
cat note5 >> notes    Append to a file
cat > temp1           Create file at terminal; end with EOF
cat > temp2 << STOP   Create file at terminal; end with STOP
cc

cc [options] files

See gcc.

cpp

cpp [options] [ ifile [ ofile ] ]

GNU C language preprocessor. cpp is invoked as the first pass of any C compilation by the gcc command. The output of cpp is a form acceptable as input to the next pass of the C compiler, and cpp normally invokes gcc after it finishes processing. ifile and ofile are, respectively, the input and output for the preprocessor; they default to standard input and standard output.

Options

-$

Do not allow $ in identifiers.

-dM

Suppress normal output. Print series of #defines that create the macros used in the source file.

-dD

Similar to -dM but exclude predefined macros and include results of preprocessing.

-idirafter dir

Search dir for header files when a header file is not found in any of the included directories.

-imacros file

Process macros in file before processing main files.

-include file

Process file before main file.

-iprefix prefix

When adding directories with -iwithprefix, prepend prefix to the directory's name.

-iwithprefix dir

Append dir to the list of directories to be searched when a header file cannot be found in the main include path. If -iprefix has been set, prepend that prefix to the directory's name.

-lang-c, -lang-c++, -lang-objc, -lang-objc++

Expect the source to be in C, C++, Objective C, or Objective C++, respectively.

-lint

Display all lint commands in comments as #pragma lint command.

-nostdinc

Search only specified, not standard, directories for header files.

-nostdinc++

Suppress searching of directories believed to contain C++-specific header files.

-pedantic

Warn verbosely.

-pedantic-errors

Produce a fatal error in every case in which -pedantic would have produced a warning.

-traditional

Behave like traditional C, not ANSI.

-undef

Suppress definition of all nonstandard macros.

-Aname[=def]

Assert name with value def as if defined by a #assert.

-C

Pass along all comments (except those found on cpp directive lines). By default, cpp strips C-style comments.

-Dname[=def]

Define name with value def as if by a #define. If no =def is given, name is defined with value 1. -D has lower precedence than -U.

-H

Print pathnames of included files, one per line, on standard error.

-Idir

Search in directory dir for #include files whose names do not begin with / before looking in directories on standard list. #include files whose names are enclosed in double quotes and do not begin with / will be searched for first in the current directory, then in directories named on -I options, and last in directories on the standard list.

-M [-MG]

Suppress normal output. Print a rule for make that describes the main source file's dependencies. If -MG is specified, assume that missing header files are actually generated files, and look for them in the source file's directory.

-MD file

Similar to -M, but output to file; also compile the source.

-MM

Similar to -M. Describe only those files included as a result of #include "file".

-MMD file

Similar to -MD, but describe only the user's header files.

-P

Preprocess input without producing line-control information used by next pass of C compiler.

-Uname

Remove any initial definition of name, where name is a reserved symbol predefined by the preprocessor or a name defined on a -D option. Names predefined by cpp are unix and i386 (for Intel systems).

-Wcomment, -Wcomments

Warn when encountering the beginning of a nested comment.

-Wtraditional

Warn when encountering constructs that are interpreted differently in ANSI from traditional C.

Special names

cpp understands various special names, some of which are:

__DATE__

Current date (e.g., Oct 10 1999)

__FILE__

Current filename (as a C string)

__LINE__

Current source line number (as a decimal integer)

__TIME__

Current time (e.g., 12:00:00)

These special names can be used anywhere, including macros, just like any other defined names. cpp's understanding of the line number and filename may be changed using a #line directive.

Directives

All cpp directive lines start with # in column 1. Any number of blanks and tabs is allowed between the # and the directive. The directives are:

#assert name (string)

Define a question called name, with an answer of string. Assertions can be tested with #if directives. The predefined assertions for #system, #cpu, and #machine can be used for architecture-dependent changes.

#unassert name

Remove assertion for question name.

#define name token-string

Define a macro called name, with a value of token-string. Subsequent instances of name are replaced with token-string.

#define name( arg, ... , arg ) token-string

This allows substitution of a macro with arguments. token-string will be substituted for name in the input file. Each call to name in the source file includes arguments that are plugged into the corresponding args in token-string.

#undef name

Remove definition of the macro name. No additional tokens are permitted on the directive line after name.

#ident string

Put string into the comment section of an object file.

#include "filename", #include<filename>

Include contents of filename at this point in the program. No additional tokens are permitted on the directive line after the final " or >.

#line integer-constant "filename"

Cause cpp to generate line-control information for the next pass of the C compiler. The compiler behaves as if integer-constant is the line number of the next line of source code and filename (if present) is the name of the input file. No additional tokens are permitted on the directive line after the optional filename.

#endif

End a section of lines begun by a test directive (#if, #ifdef, or #ifndef). No additional tokens are permitted on the directive line.

#ifdef name

Lines following this directive and up to matching #endif or next #else or #elif will appear in the output if name is currently defined. No additional tokens are permitted on the directive line after name.

#ifndef name

Lines following this directive and up to matching #endif or next #else or #elif will appear in the output if name is not currently defined. No additional tokens are permitted on the directive line after name.

#if constant-expression

Lines following this directive and up to matching #endif or next #else or #elif will appear in the output if constant-expression evaluates to nonzero.

#elif constant-expression

An arbitrary number of #elif directives are allowed between an #if, #ifdef, or #ifndef directive and an #else or #endif directive. The lines following the #elif and up to the next #else, #elif, or #endif directive will appear in the output if the preceding test directive and all intervening #elif directives evaluate to zero, and the constant-expression evaluates to nonzero. If constant-expression evaluates to nonzero, all succeeding #elif and #else directives will be ignored.

#else

Lines following this directive and up to the matching #endif will appear in the output if the preceding test directive evaluates to 0, and all intervening #elif directives evaluate to 0. No additional tokens are permitted on the directive line.

#error

Report fatal errors.

#warning

Report warnings, but then continue processing.

cfdisk

cfdisk [options] [device]

System administration command. Partition a hard disk. device may be /dev/hda (default), /dev/hdb, /dev/sda, /dev/sdb, /dev/sdc, or /dev/sdd. See also fdisk.

Options

-a

Highlight the current partition with a cursor, not reverse video.

-c cylinders

Specify the number of cylinders.

-h heads

Specify the number of heads.

-s sectors

Specify the number of sectors per track.

-z

Do not read the partition table; partition from scratch.

-P format

Display the partition table in format, which must be r (raw data), s (sector order), or t (raw format).

Commands

up arrow, down arrow

Move among partitions.

b

Toggle partition's bootable flag.

d

Delete partition (allow other partitions to use its space).

g

Alter the disk's geometry. Prompt for what to change: cylinders, heads, or sectors (c, h, or s, respectively).

h

Help.

m

Attempt to ensure maximum usage of disk space in the partition.

n

Create a new partition. Prompt for more information.

p

Display the partition table.

q

Quit without saving information.

t

Prompt for a new filesystem type, and change to that type.

u

Change the partition size units, rotating from megabytes to sectors to cylinders and back.

W

Save information. Note that this letter must be uppercase.

chattr

chattr [options] mode files

Modify file attributes. Specific to Linux Second Extended Filesystem. Behaves similarly to symbolic chmod, using +, -, and =. mode is in the form opcode attribute. See also lsattr.

Options

-R

Modify directories and their contents recursively.

-V

Print modes of attributes after changing them.

-v version

Set the file's version.

Opcodes

+

Add attribute.

-

Remove attribute.

=

Assign attributes (removing unspecified attributes).

Attributes

A

Don't update access time on modify.

a

Append only for writing. Can be set or cleared only by a privileged user.

c

Compressed.

d

No dump.

i

Immutable. Can be set or cleared only by a privileged user.

s

Secure deletion; the contents are zeroed on deletion.

u

Undeletable.

S

Synchronous updates.

Examples

chattr +a myfile     As superuser
chfn

chfn [options] [username]

Change the information that is stored in /etc/passwd and displayed when a user is fingered. Without options, chfn enters interactive mode and prompts for changes. To make a field blank, enter the keyword none. Only a privileged user can change information for another user. For regular users, chfn prompts for the user's password before making the change.

Options

-f, --full-name

Specify new full name.

-h, --home-phone

Specify new home phone number.

-o, --office

Specify new office number.

-p, --office-phone

Specify new office phone number.

-u, --help

Print help message and then exit.

-v, --version

Print version information and then exit.

Example

chfn -f "Ellen Siever" ellen
chgrp

chgrp [options] newgroup files

chgrp [options]

Change the group of one or more files to newgroup. newgroup is either a group ID number or a group name located in /etc/group. Only the owner of a file or a privileged user may change its group.

Options

-c, --changes

Print information about those files that are changed.

-f, --silent, --quiet

Do not print error messages about files that cannot be changed.

--help

Print help message and then exit.

-R, --recursive

Traverse subdirectories recursively, applying changes.

--reference=filename

Change the group to that associated with filename. In this case, newgroup is not specified.

-v, --verbose

Verbosely describe ownership changes.

--version

Print version information and then exit.

chmod

chmod [options] mode files

chmod [options] --reference=filename files

Change the access mode (permissions) of one or more files. Only the owner of a file or a privileged user may change its mode. mode can be numeric or an expression in the form of who opcode permission. who is optional (if omitted, default is a); choose only one opcode. Multiple modes may be specified, separated by commas.

Options

-c, --changes

Print information about files that are changed.

-f, --silent, --quiet

Do not notify user of files that chmod cannot change.

--help

Print help message and then exit.

-R, --recursive

Traverse subdirectories recursively, applying changes.

--reference=filename

Change permissions to those associated with filename.

-v, --verbose

Print information about each file, whether changed or not.

--version

Print version information and then exit.

Who

u

User

g

Group

o

Other

a

All (default)

Opcode

+

Add permission.

-

Remove permission.

=

Assign permission (and remove permission of the unspecified fields).

Permissions

r

Read.

w

Write.

x

Execute.

s

Set user (or group) ID.

t

Sticky bit; save text (file) mode or prevent removal of files by nonowners (directory).

u

User's present permission.

g

Group's present permission.

o

Other's present permission.

Alternatively, specify permissions by a three-digit octal number. The first digit designates owner permission; the second, group permission; and the third, other's permission. Permissions are calculated by adding the following octal values:

4

Read.

2

Write.

1

Execute.

Note: A fourth digit may precede this sequence. This digit assigns the following modes:

4

Set user ID on execution to grant permissions to process based on file's owner, not on permissions of user who created the process.

2

Set group ID on execution to grant permissions to process based on the file's group, not on permissions of user who created the process.

1

Set sticky bit.

Examples

Add execute-by-user permission to file:

chmod u+x file

Either of the following will assign read/write/execute permission by owner (7), read/execute permission by group (5), and execute-only permission by others (1) to file:

chmod 751 file
chmod u=rwx,g=rx,o=x file

Any one of the following will assign read-only permission to file for everyone:

chmod =r file
chmod 444 file
chmod a-wx,a+r file

Set the user ID, assign read/write/execute permission by owner, and assign read/execute permission by group and others:

chmod 4755 file
chown

chown [options] newowner files

chown [options] --reference=filename files

Change the ownership of one or more files to newowner. newowner is either a user ID number or a login name located in /etc/passwd. chown also accepts users in the form newowner:newgroup or newowner.newgroup. The last two forms change the group ownership as well. If no owner is specified, the owner is unchanged. With a period or colon but no group, the group is changed to that of the new owner. Only the current owner of a file or a privileged user may change its owner.

Options

-c, --changes

Print information about those files that are changed.

--dereference

Follow symbolic links.

-f, --silent, --quiet

Do not print error messages about files that cannot be changed.

-h, --no-dereference

Change the ownership of each symbolic link (on systems that allow it), rather than the referenced file.

-v, --verbose

Print information about all files that chown attempts to change, whether or not they are actually changed.

-R, --recursive

Traverse subdirectories recursively, applying changes.

--reference=filename

Change owner to the owner of filename instead of specifying a new owner explicitly.

--help

Print help message and then exit.

--version

Print version information and then exit.

chpasswd

chpasswd [option]

System administration command. Change user passwords in a batch. chpasswd accepts input in the form of one username:password pair per line. If the -e option is not specified, password will be encrypted before being stored.

Option

-e

Passwords given are already encrypted.

chroot

chroot newroot [command]

System administration command. Change root directory for command or, if none is specified, for a new copy of the user's shell. This command or shell is executed relative to the new root. The meaning of any initial / in pathnames is changed to newroot for a command and any of its children. In addition, the initial working directory is newroot. This command is restricted to privileged users.

chsh

chsh [options] [username]

Change your login shell, interactively or on the command line. Warn if shell does not exist in /etc/shells. Specify the full path to the shell. chsh prompts for your password. Only a privileged user can change another user's shell.

Options

-l, --list-shells

Print valid shells, as listed in /etc/shells, and then exit.

-s shell, --shell shell

Specify new login shell.

-u, --help

Print help message and then exit.

-v, --version

Print version information and then exit.

Example

chsh -s /bin/tcsh
cksum

cksum [files]

Compute a cyclic redundancy check (CRC) checksum for all files; used to ensure that a file was not corrupted during transfer. Read from standard input if the character - or no files are given. Display the resulting checksum, the number of bytes in the file, and (unless reading from standard input) the filename.

clear

clear

Clear the terminal display.

cmp

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

Compare file1 with file2. Use standard input if file1 is - or missing. See also comm and diff. Files can be of any type. skip1 and skip2 are optional offsets in the files at which the comparison is to start.

Options

-c, --print-chars

Print differing bytes as characters.

-i num, --ignore-initial=num

Ignore the first num bytes of input.

-l, --verbose

Print offsets and codes of all differing bytes.

-s, --quiet, --silent

Work silently; print nothing, but return exit codes:

0

Files are identical.

1

Files are different.

2

Files are inaccessible.

Example

Print a message if two files are the same (exit code is 0):

cmp -s old new && echo 'no changes'
col

col [options]

A postprocessing filter that handles reverse linefeeds and escape characters, allowing output from tbl or nroff to appear in reasonable form on a terminal.

Options

-b

Ignore backspace characters; helpful when printing manpages.

-f

Process half-line vertical motions, but not reverse line motion. (Normally, half-line input motion is displayed on the next full line.)

-l n

Buffer at least n lines in memory. The default buffer size is 128 lines.

-x

Normally, col saves printing time by converting sequences of spaces to tabs. Use -x to suppress this conversion.

Examples

Run myfile through tbl and nroff, then capture output on screen by filtering through col and more:

tbl myfile | nroff | col | more

Save manpage output for the ls command in out.print, stripping out backspaces (which would otherwise appear as ^H):

man ls | col -b > out.print
colcrt

colcrt [options] [files]

A postprocessing filter that handles reverse linefeeds and escape characters, allowing output from tbl or nroff to appear in reasonable form on a terminal. Put half-line characters (e.g., subscripts or superscripts) and underlining (changed to dashes) on a new line between output lines.

Options

-

Do not underline.

-2

Double space by printing all half-lines.

colrm

colrm [start [stop]]

Remove specified columns from a file, where a column is a single character in a line. Read from standard input and write to standard output. Columns are numbered starting with 1; begin deleting columns at (including) the start column, and stop at (including) the stop column. Entering a tab increments the column count to the next multiple of either the start or stop column; entering a backspace decrements it by 1.

Example

colrm 3 5 < test1 > test2
column

column [options] [files]

Format input from one or more files into columns, filling rows first. Read from standard input if no files are specified.

Options

-c num

Format output into num columns.

-s char

Delimit table columns with char. Meaningful only with -t.

-t

Format input into a table. Delimit with whitespace, unless an alternate delimiter has been provided with -s.

-x

Fill columns before filling rows.

comm

comm [options] file1 file2

Compare lines common to the sorted files file1 and file2. Three-column output is produced: lines unique to file1, lines unique to file2, and lines common to both files. comm is similar to diff in that both commands compare two files. But comm can also be used like uniq; that is, comm selects duplicate or unique lines between two sorted files, whereas uniq selects duplicate or unique lines within the same sorted file.

Options

-

Read the standard input.

-num

Suppress printing of column num. Multiple columns may be specified and should not be space-separated.

--help

Print help message and exit.

--version

Print version information and exit.

Example

Compare two lists of top-10 movies, and display items that appear in both lists:

comm -12 siskel_top10 ebert_top10

compress

compress [options] files

Compress one or more files, replacing each with the compressed file of the same name with .Z appended. If no file is specified, compress standard input. Each file specified is compressed separately. compress ignores files that are symbolic links. See also gzip.

Options

-b maxbits

Limit the maximum number of bits.

-c

Write output to standard output, not to a .Z file.

-d

Decompress instead of compressing. Same as uncompress.

-f

Force generation of an output file even if one already exists.

-r

If any of the specified files is a directory, compress recursively.

-v

Print compression statistics.

-V

Print version and compilation information and then exit.

cp

cp [options] file1 file2

cp [options] files directory

Copy file1 to file2, or copy one or more files to the same names under directory. If the destination is an existing file, the file is overwritten; if the destination is an existing directory, the file is copied into the directory (the directory is not overwritten).

Options

-a, --archive

Preserve attributes of original files where possible. Same as -dpR.

-b, --backup

Back up files that would otherwise be overwritten.

-d, --no-dereference

Do not dereference symbolic links; preserve hard link relationships between source and copy.

-f, --force

Remove existing files in the destination.

-i, --interactive

Prompt before overwriting destination files.

-l, --link

Make hard links, not copies, of nondirectories.

-p, --preserve

Preserve all information, including owner, group, permissions, and timestamps.

-P, --parents

Preserve intermediate directories in source. The last argument must be the name of an existing directory. For example, the command:

 
cp --parents jphekman/book/ch1 newdir
copies the file jphekman/book/ch1 to the file newdir/jphekman/book/ch1, creating intermediate directories as necessary.

-r, -R, --recursive

Copy directories recursively.

-S backup-suffix, --suffix=backup-suffix

Set suffix to be appended to backup files. This may also be set with the SIMPLE_BACKUP_SUFFIX environment variable. The default is ~. You need to explicitly include a period if you want one before the suffix (e.g., specify .bak, not bak).

-s, --symbolic-link

Make symbolic links instead of copying. Source filenames must be absolute.

-u, --update

Do not copy a file to an existing destination with the same or newer modification time.

-v, --verbose

Before copying, print the name of each file.

-V type, --version-control=type

Set the type of backups made. You may also use the VERSION_CONTROL environment variable. The default is existing. Valid arguments are:

t, numbered

Always make numbered backups.

nil, existing

Make numbered backups of files that already have them; otherwise, make simple backups.

never, simple

Always make simple backups.

-x, --one-file-system

Ignore subdirectories on other filesystems.

cpio

cpio flags [options]

Copy file archives in from or out to tape or disk, or to another location on the local machine. Each of the three flags -i, -o, or -p accepts different options.

Flags

-i, --extract [options] [patterns]

Copy in (extract) from an archive files whose names match selected patterns. Each pattern can include Bourne shell filename metacharacters. (Patterns should be quoted or escaped so they are interpreted by cpio, not by the shell.) If pattern is omitted, all files are copied in. Existing files are not overwritten by older versions from the archive unless -u is specified.

-o, --create [options]

Copy out to an archive a list of files whose names are given on the standard input.

-p, --pass-through [options] directory

Copy (pass) files to another directory on the same system. Destination pathnames are interpreted relative to the named directory.

Comparison of valid options

Options available to the -i, -o, and -p flags are shown here. (The - is omitted for clarity):

i:   bcdf mnrtsuv B SVCEHMR IF
o: 0a c         vABL VC HM O F
p: 0a  d lm    uv  L V    R

Options

-0, --null

Expect list of filenames to be terminated with null, not newline. This allows files with a newline in their names to be included.

-a, --reset-access-time

Reset access times of input files after reading them.

-A, --append

Append files to an existing archive, which must be a disk file. Specify this archive with -O or -F.

-b, --swap

Swap bytes and half-words to convert between big-endian and little-endian 32-bit integers.

-B

Block input or output using 5120 bytes per record (default is 512 bytes per record).

--blocksize=size

Set input or output blocksize to size × 512 bytes.

-c

Read or write header information as ASCII characters; useful when source and destination machines are different types.

-C n, --io-size=n

Like -B, but blocksize can be any positive integer n.

-d, --make-directories

Create directories as needed.

-E file, --pattern-file=file

Extract filenames from the archives that match patterns in file.

-f, --nonmatching

Reverse the sense of copying; copy all files except those that match patterns.

-F file, --file=file

Use file as the archive, not stdin or stdout. file can reside on another machine, if given in the form user@hostname:file (where user@ is optional).

--force-local

Assume that file (provided by -F, -I, or -O) is a local file, even if it contains a colon (:) indicating a remote file.

-H type, --format=type

Use type format. Default for copy-out is bin; for copy-in the default is autodetection of the format. Valid formats (all caps also accepted) are:

bin

Binary

odc

Old (POSIX.1) portable format

newc

New (SVR4) portable format

crc

New (SVR4) portable format with checksum added

tar

Tar

ustar

POSIX.1 tar (also recognizes GNU tar archives)

hpbin

HP-UX's binary (obsolete)

hpodc

HP-UX's portable format

-I file

Read file as an input archive. May be on a remote machine (see -F).

-k

Ignored. For backward compatibility.

-l, --link

Link files instead of copying.

-L, --dereference

Follow symbolic links.

-m, --preserve-modification-time

Retain previous file modification time.

-M msg, --message=msg

Print msg when switching media, as a prompt before switching to new media. Use variable %d in the message as a numeric ID for the next medium. -M is valid only with -I or -O.

-n, --numeric-uid-gid

When verbosely listing contents, show user ID and group ID numerically.

--no-absolute-filenames

Create all copied-in files relative to the current directory.

--no-preserve-owner

Make all copied files owned by yourself, instead of the owner of the original. Useful only if you are a privileged user.

-O file

Archive the output to file, which may be a file on another machine (see -F).

--only-verify-crc

For a CRC-format archive, verify the CRC of each file; don't actually copy the files in.

--quiet

Don't print the number of blocks copied.

-r

Rename files interactively.

-R [user][:group], --owner [user][:group]

Reassign file ownership and group information to the user's login ID (privileged users only).

-s, --swap-bytes

Swap bytes of each two-byte half-word.

-S, --swap-half-words

Swap half-words of each four-byte word.

--sparse

For copy-out and copy-pass, write files that have large blocks of zeros as sparse files.

-t, --list

Print a table of contents of the input (create no files). When used with the -v option, resembles output of ls -l.

-u, --unconditional

Unconditional copy; old files can overwrite new ones.

-v, --verbose

Print a list of filenames processed.

-V, --dot

Print a dot for each file read or written (this shows cpio at work without cluttering the screen).

--version

Print version number and then exit.

Examples

Generate a list of files whose names end in .old using find; use list as input to cpio:

find . -name "*.old" -print | cpio -ocBv > /dev/rst8

Restore from a tape drive all files whose names contain save (subdirectories are created if needed):

cpio -icdv "*save*" < /dev/rst8

Move a directory tree:

find . -depth -print | cpio -padm /mydir

cron

cron

System administration command. Normally started in a system startup file. Execute commands at scheduled times, as specified in users' files in /var/cron/tabs. Each file shares its name with the user who owns it. The files are controlled via the command crontab.

crontab

crontab [options] [file]

View, install, or uninstall your current crontab file. A privileged user can run crontab for another user by supplying -u user. A crontab file is a list of commands, one per line, that will execute automatically at a given time. Numbers are supplied before each command to specify the execution time. The numbers appear in five fields, as follows:

Minute       0-59

Hour         0-23

Day of month 1-31

Month        1-12
              Jan, Feb, Mar, ...

Day of week   0-6, with 0 = Sunday
             Sun, Mon, Tue, ...

Use a comma between multiple values, a hyphen to indicate a range, and an asterisk to indicate all possible values. For example, assuming these crontab entries:

59 3 * * 5     find / -print | backup_program
0 0 1,15 * *   echo "Timesheets due" | mail user

The first command backs up the system files every Friday at 3:59 a.m., and the second command mails a reminder on the 1st and 15th of each month.

The superuser can always issue the crontab command. Other users must be listed in the file /etc/cron.allow if it exists; otherwise, they must not be listed in /etc/cron.deny. If neither file exists, only the superuser can issue the command.

Options

The -e, -l, and -r options are not valid if any files are specified.

-e

Edit the user's current crontab file (or create one).

-l

Display the user's crontab file on standard output.

-r

Delete the user's crontab file.

-u user

Indicates which user's crontab file will be acted upon.

csh

csh [options] [file [arguments]]

C shell, a command interpreter into which all other commands are entered. For more information, see Chapter 8, "csh and tcsh".

csplit

csplit [options] file arguments

Separate file into context-based sections and place sections in files named xx00 through xxn (n < 100), breaking file at each pattern specified in arguments. See also split.

Options

-

Read from standard input.

-b suffix, --suffix-format=suffix

Append suffix to output filename. This option causes -n to be ignored. suffix must specify how to convert the binary integer to readable form by including exactly one of the following: %d, %i, %u, %o, %x, or %X. The value of suffix determines the format for numbers as follows:

%d

Signed decimal

%i

Same as %d

%u

Unsigned decimal

%o

Octal

%x

Hexadecimal

%X

Same as %x.

-f prefix, --prefix=prefix

Name new files prefix00 through prefixn (default is xx00 through xxn).

-k, --keep-files

Keep newly created files, even when an error occurs (which would normally remove these files). This is useful when you need to specify an arbitrarily large repeat argument, {n}, and you don't want an out-of-range error to cause removal of the new files.

-n num, --digits=num

Use output filenames with numbers num digits long. The default is 2.

-s, -q, --silent, --quiet

Suppress all character counts.

-z, --elide-empty-files

Do not create empty output files. However, number as if those files had been created.

Arguments

Any one or a combination of the following expressions may be specified as arguments. Arguments containing blanks or other special characters should be surrounded by single quotes.

/expr/[offset]

Create file from the current line up to the line containing the regular expression expr. offset should be of the form +n or -n, where n is the number of lines below or above expr.

%expr%[offset]

Same as /expr/ except no file is created for lines previous to line containing expr.

num

Create file from current line up to (but not including) line number num. When followed by a repeat count (number inside {}), put the next num lines of input into another output file.

{n}

Repeat argument n times. May follow any of the preceding arguments. Files will split at instances of expr or in blocks of num lines. If * is given instead of n, repeat argument until input is exhausted.

Examples

Create up to 20 chapter files from the file novel:

csplit -k -f chap. novel '/CHAPTER/' '{20}'

Create up to 100 address files (xx00 through xx99), each four lines long, from a database named address_list:

csplit -k address_list 4 {99}
ctags

ctags [options] files

Create a list of function and macro names that are defined in the specified C, C++, FORTRAN, Java, Perl, yacc, or other source files. The output list (named tags by default) contains lines of the form:

name     file     context

where name is the function or macro name, file is the source file in which name is defined, and context is a search pattern that shows the line of code containing name. After the list of tags is created, you can invoke vi on any file and type:

:set tags=tagsfile
:tag name

This switches the vi editor to the source file associated with the name listed in tagsfile (which you specify with -t).

etags produces an equivalent file for tags to be used with Emacs.

Options

-a, --append

Append tag output to existing list of tags.

-d, --defines

Include tag entries for C preprocessor definitions.

-i file, --include=file

Add a note to the tags file that file should be consulted in addition to the normal input file.

-l language, --language=language

Consider the files that follow this option to be written in language. Use the -h option for a list of languages and their default filename extensions.

-o file, --output=file

Write to file.

-rregexp, --regex=regexp

Include a tag for each line that matches regexp in the files following this option.

-R, --no-regex

Don't include tags based on regular-expression matching for the files that follow this option.

-t, --typedefs

Include tag entries for typedefs.

-u, --update

Update tags file to reflect new locations of functions (e.g., when functions are moved to a different source file). Old tags are deleted; new tags are appended.

-v, --vgrind

Print to standard output a listing (index) of each function, source file, and page number (1 page = 64 lines).

-w, --no-warn

Suppress warning messages.

-x, --cxref

Produce a listing of each function, and its line number, source file, and context.

-B, --backward-search

Search for tags backward through files.

-C, --c++

Expect .c and .h files to contain C++, not C, code.

-H, -h, --help

Print usage information and exit.

-S, --ignore-indentation

Normally ctags uses indentation to parse the tag file; this option tells it to rely on it less.

-T, --typedefs-and-c++

Include tag entries for typedefs, structs, enums, unions, and C++ member functions.

-V, --version

Print the version number and exit.

cut

cut options [files]

Cut out selected columns or fields from one or more files. In the following options, list is a sequence of integers. Use a comma between separate values and a hyphen to specify a range (e.g., 1-10,15,20 or 50-). See also paste and join.

Options

-b list, --bytes list

Specify list of positions; only bytes in these positions will be printed.

-c list, --characters list

Cut the column positions identified in list.

-d c, --delimiter c

Use with -f to specify field delimiter as character c (default is tab); special characters (e.g., a space) must be quoted.

-f list, --fields list

Cut the fields identified in list.

-n

Don't split multibyte characters.

-s, --only-delimited

Use with -f to suppress lines without delimiters.

--output-delimiter=string

Use string as the output delimiter. By default, the output delimiter is the same as the input delimiter.

--help

Print help message and then exit.

--version

Print version information and then exit.

Examples

Extract usernames and real names from /etc/passwd:

cut -d: -f1,5 /etc/passwd

Find out who is logged on, but list only login names:

who | cut -d"" -f1

Cut characters in the fourth column of file, and paste them back as the first column in the same file:

cut -c4 file | paste - file
date

date [options] [+format] [date]

Print the current date and time. You may specify a display format. format can consist of literal text strings (blanks must be quoted) as well as field descriptors, whose values will appear as described in the following entries (the listing shows some logical groupings). A privileged user can change the system's date and time.

Options

+format

Display current date in a nonstandard format. For example:

% date +"%A %j %n%k %p"
Tuesday 248 
15 PM

The default is %a %b %e %T %Z %Y -- e.g., Tue Sep 5 14:59:37 EDT 2000.

-d date, --date date

Display date, which should be in quotes and may be in the format d days or m months d days to print a date in the future. Specify ago to print a date in the past. You may include formatting (see the "Format" section that follows).

-f datefile, --file=datefile

Like -d but printed once for each line of datefile.

-I [timespec], --iso-8601[=timespec]

Display in ISO-8601 format. If specified, timespec can have one of the values date (for date only), hours, minutes, or seconds to get the indicated precision.

-r file, --reference=file

Display the time file was last modified.

-R, --rfc-822

Display the date in RFC 822 format.

--help

Print help message and exit.

--version

Print version information and exit.

-s date, --set date

Set the date.

-u, --universal

Set the date to Greenwich Mean Time, not local time.

Format

%

Literal %.

-

Do not pad fields (default: pad fields with zeros).

_

Pad fields with space (default: zeros).

%a

Abbreviated weekday.

%b

Abbreviated month name.

%c

Country-specific date and time format.

%d

Day of month (01-31).

%h

Same as %b.

%j

Julian day of year (001-366).

%k

Hour in 24-hour format, without leading zeros (0-23).

%l

Hour in 12-hour format, without leading zeros (1-12).

%m

Month of year (01-12).

%n

Insert a new line.

%p

String to indicate AM or PM.

%r

Time in %I:%M:%S %p (12-hour) format.

%s

Seconds since "The Epoch," 1970-01-01 00:00:00 UTC (a nonstandard extension).

%t

Insert a tab.

%w

Day of week (Sunday = 0).

%x

Country-specific date format.

%y

Last two digits of year (00-99).

%z

RFC 822-style numeric time zone.

%A

Full weekday.

%B

Full month name.

%D

Date in %m/%d/%y format.

%H

Hour in 24-hour format (00-23).

%I

Hour in 12-hour format (01-12).

%M

Minutes (00-59).

%S

Seconds (00-59).

%T

Time in %H:%M:%S format.

%U

Week number in year (00-53); start week on Sunday.

%V

Week number in year (01-52); start week on Monday.

%W

Week number in year (00-53); start week on Monday.

%X

Country-specific time format.

%Y

Four-digit year (e.g., 1996).

%Z

Time zone name.

Strings for setting date

Strings for setting the date may be numeric or nonnumeric. Numeric strings consist of time, day, and year in the format MMDDhhmm[[CC]YY][.ss]. Nonnumeric strings may include month strings, time zones, a.m., and p.m.

time

A two-digit hour and two-digit minute (hhmm); hh uses 24-hour format.

day

A two-digit month and two-digit day of month (MMDD); default is current day and month.

year

The year specified as either the full four-digit century and year or just the two-digit year; the default is the current year.

Examples

Set the date to July 1 (0701), 4 a.m. (0400), 1995 (95):

date 0701040095

The command:

date +"Hello%t Date is %D %n%t Time is %T"

produces a formatted date as follows:


Hello     Date is 05/09/93
     Time is 17:53:39
dd

dd options

Make a copy of an input file (if) using the specified conditions, and send the results to the output file (or standard output if of is not specified). Any number of options can be supplied, although if and of are the most common and are usually specified first. Because dd can handle arbitrary blocksizes, it is useful when converting between raw physical devices.

Options

bs=n

Set input and output blocksize to n bytes; this option overrides ibs and obs.

cbs=n

Set the size of the conversion buffer (logical record length) to n bytes. Use only if the conversion flag is ascii, ebcdic, ibm, block, or unblock.

conv=flags

Convert the input according to one or more (comma-separated) flags listed next. The first five flags are mutually exclusive.

ascii

EBCDIC to ASCII.

ebcdic

ASCII to EBCDIC.

ibm

ASCII to EBCDIC with IBM conventions.

block

Variable-length records (i.e., those terminated by a newline) to fixed-length records.

unblock

Fixed-length records to variable-length.

lcase

Uppercase to lowercase.

ucase

Lowercase to uppercase.

noerror

Continue processing after read errors.

notrunc

Don't truncate output file.

swab

Swap each pair of input bytes.

sync

Pad input blocks to ibs with trailing zeros.

count=n

Copy only n input blocks.

ibs=n

Set input blocksize to n bytes (default is 512).

if=file

Read input from file (default is standard input).

obs=n

Set output blocksize to n bytes (default is 512).

of=file

Write output to file (default is standard output).

seek=n

Skip n output-sized blocks from start of output file.

skip=n

Skip n input-sized blocks from start of input file.

--help

Print help message and then exit.

--version

Print the version number and then exit.

You can multiply size values (n) by a factor of 1024, 512, or 2 by appending the letter k, b, or w, respectively. You can use the letter x as a multiplication operator between two numbers.

Examples

Convert an input file to all lowercase:

dd if=caps_file of=small_file conv=lcase

Retrieve variable-length data; write it as fixed-length to out:

data_retrieval_cmd | dd of=out conv=sync,block

debugfs

debugfs [[option] device]

System administration command. Debug an ext2 filesystem. device is the special file corresponding to the device containing the ext2 filesystem (e.g., /dev/hda3).

Option

-w

Open the filesystem read-write.

Commands

cat file

Dump the contents of an inode to standard output.

cd directory

Change the current working directory to directory.

chroot directory

Change the root directory to be the specified inode.

close

Close the currently open filesystem.

clri file

Clear the contents of the inode corresponding to file.

dump file out_file

Dump the contents of an inode to out_file.

expand_dir directory

Expand directory.

find_free_block [goal]

Find first free block starting from goal (if specified) and allocate it.

find_free_inode [dir [mode]]

Find a free inode and allocate it.

freeb block

Mark block as not allocated.

freei file

Free the inode corresponding to file.

help

Print a list of commands understood by debugfs.

icheck block

Do block-to-inode translation.

initialize device blocksize

Create an ext2 filesystem on device.

kill_file file

Remove file and deallocate its blocks.

ln source_file dest_file

Create a link.

ls [pathname]

Emulate the ls command.

modify_inode file

Modify the contents of the inode corresponding to file.

mkdir directory

Make directory.

mknod file [p|[[c|b] major minor]]

Create a special device file.

ncheck inode

Do inode-to-name translation.

open [-w] device

Open a filesystem.

pwd

Print the current working directory.

quit

Quit debugfs.

rm file

Remove file.

rmdir directory

Remove directory.

setb block

Mark block as allocated.

seti file

Mark in use the inode corresponding to file.

show_super_stats

List the contents of the super block.

stat file

Dump the contents of the inode corresponding to file.

testb block

Test whether block is marked as allocated.

testi file

Test whether the inode corresponding to file is marked as allocated.

unlink file

Remove a link.

write source_file file

Create a file in the filesystem named file, and copy the contents of source_file into the destination file.

depmod

depmod [options] modules

System administration command. Create a dependency file for the modules given on the command line. This dependency file can be used by modprobe to automatically load the relevant modules. The normal use of depmod is to include the line /sbin/depmod -a in one of the files in /etc/rc.d so the correct module dependencies will be available after booting the system.

Options

-a

Create dependencies for all modules listed in /etc/conf.modules.

-d

Debug mode. Show all commands being issued.

-e

Print a list of all unresolved symbols.

-v

Print a list of all processed modules.

Files

/etc/conf.modules

Information about modules: which ones depend on others, and which directories correspond to particular types of modules.

/sbin/insmod, /sbin/rmmod

Programs that depmod relies on.

df

df [options] [name]

Report the amount of free disk space available on all mounted filesystems or on the given name. (df cannot report on unmounted filesystems.) Disk space is shown in 1KB blocks (default) or 512-byte blocks (if the environment variable POSIXLY_CORRECT is set). name can be a device name (e.g., /dev/hd*), the directory name of a mounting point (e.g., /usr), or a directory name (in which case df reports on the entire filesystem in which that directory is mounted).

Options

-a, --all

Include empty filesystems (those with 0 blocks).

--block-size=n

Show space as n-byte blocks.

-h, --human-readable

Print sizes in a format friendly to human readers (e.g., 1.9G instead of 1967156).

-H, --si

Like -h, but show as power of 1000 rather than 1024.

-i, --inodes

Report free, used, and percent-used inodes.

-k, --kilobytes

Print sizes in kilobytes.

-l, --local

Show local filesystems only.

-m, --megabytes

Print sizes in megabytes.

--no-sync

Show results without invoking sync first (i.e., without flushing the buffers). This is the default.

-P, --portability

Use POSIX output format (i.e., print information about each filesystem on exactly one line).

--sync

Invoke sync (flush buffers) before getting and showing sizes.

-t type, --type=type

Show only type filesystems.

-T, --print-type

Print the type of each filesystem in addition to the sizes.

-x type, --exclude-type=type

Show only filesystems that are not of type type.

--help

Print help message and then exit.

--version

Print the version and then exit.

diff

diff [options] [diroptions] file1 file2

Compare two text files. diff reports lines that differ between file1 and file2. Output consists of lines of context from each file, with file1 text flagged by a < symbol and file2 text by a > symbol. Context lines are preceded by the ed command (a, c, or d) that would be used to convert file1 to file2. If one of the files is -, standard input is read. If one of the files is a directory, diff locates the filename in that directory corresponding to the other argument (e.g., diff my_dir junk is the same as diff my_dir/junk junk). If both arguments are directories, diff reports lines that differ between all pairs of files having equivalent names (e.g., olddir/program and newdir/program); in addition, diff lists filenames unique to one directory, as well as subdirectories common to both. See also cmp.

Options

-a, --text

Treat all files as text files. Useful for checking to see if binary files are identical.

-b, --ignore-space-change

Ignore repeating blanks and end-of-line blanks; treat successive blanks as one.

-B, --ignore-blank-lines

Ignore blank lines in files.

-c

Context diff: print 3 lines surrounding each changed line.

-C n, --context[=n]

Context diff: print n lines surrounding each changed line. The default context is 3 lines.

-d, --minimal

To speed up comparison, ignore segments of numerous changes and output a smaller set of changes.

-Dsymbol, --ifdef=symbol

When handling C files, create an output file that contains all the contents of both input files, including #ifdef and #ifndef directives that reflect the directives in both files.

-e, --ed

Produce a script of commands (a, c, d) to re-create file2 from file1 using the ed editor.

-F regexp, --show-function-line[=regexp]

For context and unified diff, show the most recent line containing regexp before each block of changed lines.

-H

Speed output of large files by scanning for scattered small changes; long stretches with many changes may not show up.

--help

Print brief usage message.

--horizon-lines=n

In an attempt to find a more compact listing, keep n lines on both sides of the changed lines when performing the comparison.

-i, --ignore-case

Ignore case in text comparison. Uppercase and lowercase are considered the same.

-I regexp, --ignore-matching-lines=regexp

Ignore lines in files that match the regular expression regexp.

-l, --paginate

Paginate output by passing it to pr.

-L label, --label label, --label=label

For context and unified diff, print label in place of the filename being compared. The first such option applies to the first filename and the second option to the second filename.

--left-column

For two-column output (-y), show only left column of common lines.

-n, --rcs

Produce output in RCS diff format.

-N, --new-file

Treat nonexistent files as empty.

-p, --show-c-function

When handling files in C or C-like languages such as Java, show the function containing each block of changed lines. Assumes -c but can also be used with a unified diff.

-P, --unidirectional-new-file

If two directories are being compared and the first lacks a file that is in the second, pretend that an empty file of that name exists in the first directory.

-q, --brief

Output only whether files differ.

-r, --recursive

Compare subdirectories recursively.

-s, --report-identical-files

Indicate when files do not differ.

-S filename, --starting-file=filename

For directory comparisons, begin with the file filename, skipping files that come earlier in the standard list order.

--suppress-common-lines

For two-column output (-y), do not show common lines.

-t, --expand-tabs

Produce output with tabs expanded to spaces.

-T, --initial-tab

Insert initial tabs into output to line up tabs properly.

-u

Unified diff: print old and new versions of lines in a single block, with 3 lines surrounding each block of changed lines.

-U n, --unified[=n]

Unified diff: print old and new versions of lines in a single block, with n lines surrounding each block of changed lines. The default context is 3 lines.

-v, --version

Print version number of this version of diff.

-w, --ignore-all-space

Ignore all whitespace in files for comparisons.

-W n, --width=n

For two-column output (-y), produce columns with a maximum width of n characters. Default is 130.

-x regexp, --exclude=regexp

Do not compare files in a directory whose names match regexp.

-X filename, --exclude-from=filename

Do not compare files in a directory whose names match patterns described in the file filename.

-y, --side-by-side

Produce two-column output.

-n

For context and unified diff, print n lines of context. Same as specifying a number with -C or -U.

diff3

diff3 [options] file1 file2 file3

Compare 3 files and report the differences. No more than one of the files may be given as - (indicating that it is to be read from standard input). The output is displayed with the following codes:

====

All three files differ.

====1

file1 is different.

====2

file2 is different.

====3

file3 is different.

diff3 is also designed to merge changes in two differing files based on a common ancestor file (i.e., when two people have made their own set of changes to the same file). diff3 can find changes between the ancestor and one of the newer files and generate output that adds those differences to the other new file. Unmerged changes are places where both of the newer files differ from each other and at least one of them from the ancestor. Changes from the ancestor that are the same in both of the newer files are called merged changes. If all three files differ in the same place, it is called an overlapping change.

This scheme is used on the command line with the ancestor being file2, the second filename. Comparison is made between file2 and file3, with those differences then applied to file1.

Options

-3, --easy-only

Create an ed script to incorporate into file1 unmerged, nonoverlapping differences between file1 and file3.

-a, --text

Treat files as text.

-A, --show-all

Create an ed script to incorporate all changes, showing conflicts in bracketed format.

-e, --ed

Create an ed script to incorporate into file1 all unmerged differences between file2 and file3.

-E, --show-overlap

Create an ed script to incorporate unmerged changes, showing conflicts in bracketed format.

-x, --overlap-only

Create an ed script to incorporate into file1 all differences where all three files differ (overlapping changes).

-X

Same as -x, but show only overlapping changes, in bracketed format.

-m, --merge

Create file with changes merged (not an ed script).

-L label, --label=label

Use label to replace filename in output.

-i

Append the w (save) and q (quit) commands to ed script output.

-T, --initial-tab

Begin lines with a tab instead of two spaces in output to line tabs up properly.

-v, --version

Print version information and then exit.

dip

dip [options] [chat scriptfile]

System administration command. Set up or initiate dial-up Internet connections. dip can be used to establish connections for users dialing out or dialing in. Commands can be used in interactive mode or placed in a script file for use in dial-out connections. To establish dial-in connections, dip is often is used as a shell and may be executed using the commands diplogin or diplogini.

Options

-a

In dial-in mode, prompt for username and password. Same as the diplogini command.

-i

Initiate a login shell for a dial-in connection. Same as the diplogin command.

-k

Kill the most recent dip process or the process running on the device specified by the -l option.

-l device

Used with the -k option. Specifies a tty device.

-m mtu

Maximum Transfer Unit. The default is 296.

-p protocol

The protocol to use: SLIP, CSLIP, PPP, or TERM.

-t

Command mode. This is usually done for testing.

-v

Verbose mode.

Commands

Most of these commands can be used either in interactive mode or in a script file.

beep times

Beep the terminal the specified number of times.

bootp

Retrieve local and remote IP addresses using the BOOTP protocol.

break

Send a BREAK.

chatkey keyword code

Map a modem response keyword to a numeric code.

config [interface|routing] [pre|up|down|post] arguments

Modify interface characteristics or the routing table, before the link comes up, when it is up, when it goes down, or after it is down. The syntax for arguments is the same as arguments for the ifconfig or route commands.

databits 7|8

Set the number of data bits.

dec $variable [value]

Decrement $variable by value. The default is 1.

default

Set default route to the IP address of the host connected to.

dial phonenumber [timeout]

Dial phonenumber. Abort if remote modem doesn't answer within timeout seconds. Set $errlvl according to the modem response.

echo on|off

Enable or disable the display of modem commands.

exit [n]

Exit the script. Optionally return the number n as the exit status.

flush

Clear the input buffer.

get $variable [ask|remote [timeout]] value

Set $variable to value. If ask is specified, prompt the user for a value. If remote is specified, retrieve the value from the remote system. Abort after timeout seconds.

goto label

Jump to the section identified by label.

help

List available commands.

if expr goto label

Jump to the section identified by label if the expression evaluates to true. An expression compares a variable to a constant using one of these operators: =, !=, <, >, <=, or >=.

inc $variable [value]

Increment $variable by value. The default is 1.

init string

Set the string used to initialize the modem. The default is ATE0 Q0 V1 X1.

mode protocol

Set the connection protocol. Valid values are SLIP, CSLIP, PPP, and TERM. The default is SLIP.

netmask mask

Set the subnet mask.

parity E|O|N

Set the line parity to even, odd, or none.

password

Prompt user for password.

proxyarp

Install a proxy ARP entry in the local ARP table.

print $variable

Display the content of $variable.

psend command

Execute command in a shell, and send output to the serial device. Commands are executed using the user's real UID.

port device

Specify the serial device the modem is attached to.

quit

Exit with a nonzero exit status. Abort the connection.

reset

Reset the modem.

securid

Prompt user for the variable part of an ACE System SecureID password and send it together with the stored prefix to the remote system.

securidf prefix

Store the fixed part of an ACE System SecureID password.

send string

Send string to the serial device.

shell command

Execute command in a shell using the user's real UID.

skey [timeout]

Wait for an S/Key challenge, then prompt user for the secret key. Generate and send the response. Abort if challenge is not received within timeout seconds. S/Key support must be compiled into dip.

sleep time

Wait time seconds.

speed bits-per-second

Set the port speed. Default is 38400.

stopbits 1|2

Set the number of stop bits.

term

Enable terminal mode. Pass keyboard input directly to the serial device.

timeout time

Set the number of seconds the line can be inactive before the link is closed.

wait text [timeout]

Wait timeout seconds for text to arrive from the remote system. If timeout is not specified, wait forever.

dirname

dirname pathname

Print pathname excluding the last level. Useful for stripping the actual filename from a pathname. If there are no slashes (no directory levels) in pathname, dirname prints . to indicate the current directory. See also basename.

dmesg

dmesg [options]

System administration command. Display the system control messages from the kernel ring buffer. This buffer stores all messages since the last system boot or the most recent ones, if the buffer has been filled.

Options

-c

Clear buffer after printing messages.

-n level

Set the level of system message that will display on console.

dnsdomainname

dnsdomainname

TCP/IP command. Print the system's DNS domain name. See also hostname.

domainname

domainname [name]

NFS/NIS command. Set or display name of current NIS domain. With no argument, domainname displays the name of the current NIS domain. Only a privileged user can set the domain name by giving an argument; this is usually done in a startup script.

dosfsck

dosfsck [options] device

fsck.ext2 [options] device

System administration command. Similar to fsck, but specifically intended for MS-DOS filesystems. When checking an MS-DOS filesystem, fsck calls this command. Normally dosfsck stores all changes in memory, then writes them when checks are complete.

Options

-a

Automatically repair the system; do not prompt the user.

-A

Use the Atari version of the MS-DOS filesystem.

-d file

Drop the named file from the file allocation table. Force checking, even if kernel has already marked the filesystem as valid. dosfsck will normally exit without checking if the system appears to be clean.

-l file

Consult file for a list of bad blocks, in addition to checking for others.

-n

Ensure that no changes are made to the filesystem. When queried, answer "no."

-p

"Preen." Repair all bad blocks noninteractively.

-t

Display timing statistics.

-v

Verbose.

-y

When queried, answer "yes."

-B size

Expect to find the superblock at size; if it's not there, exit.

-F

Flush buffer caches before checking.

-L file

Consult file for list of bad blocks instead of checking filesystem for them.

du

du [options] [directories]

Print disk usage (as the number of 1KB blocks used by each named directory and its subdirectories; default is current directory).

Options

-a, --all

Print usage for all files, not just subdirectories.

-b, --bytes

Print sizes in bytes.

-c, --total

In addition to normal output, print grand total of all arguments.

-D, --dereference-args

Follow symbolic links, but only if they are command-line arguments.

-h, --human-readable

Print sizes in human-reader-friendly format.

-H, --si

Like -h, but show as power of 1000 rather than 1024.

-k, --kilobytes

Print sizes in kilobytes (this is the default).

-l, --count-links

Count the size of all files, whether or not they have already appeared (i.e., via a hard link).

-L, --dereference

Follow symbolic links.

--exclude=pattern

Exclude files that match pattern.

--max-depth=num

Report sizes for directories only down to num levels below the starting point (which is level 0).

-m, --megabytes

Print sizes in megabytes.

-s, --summarize

Print only the grand total for each named directory.

-S, --separate-dirs

Do not include the sizes of subdirectories when totaling the size of parent directories.

-x, --one-file-system

Display usage of files in current filesystem only.

-X, --exclude-from=file

Exclude files that match any pattern in file.

--help

Print help message and then exit.

--version

Print the version and then exit.

dumpe2fs

dumpe2fs device

System administration command. Print information about device's superblock and blocks group.

dumpkeys

dumpkeys [options]

Print information about the keyboard driver's translation tables to standard output. Further information is available in the manual pages under keytables.

Options

-1, --separate-lines

Print one line for each modifier/keycode pair and prefix plain to each unmodified keycode.

-ccharset, --charset=charset

Specify character set with which to interpret character code values. The default character set is iso-8859-1. The full list of valid character sets is available with the --help option.

--compose-only

Print compose key combinations only. Requires compose key support in the kernel.

-f, --full-table

Output in canonical, not short, form: for each key, print a row with modifier combinations divided into columns.

--funcs-only

Print function key string definitions only; do not print key bindings or string definitions.

-h, --help

Print help message and the version.

-i, --short-info

Print in short-info format, including information about acceptable keycode keywords in the keytable files; the number of actions that can be bound to a key; a list of the ranges of action codes (the values to the right of a key definition); and the number of function keys that the kernel supports.

--keys-only

Print key bindings only; do not print string definitions.

-l, --long-info

Print the same information as in --short-info, plus a list of the supported action symbols and their numeric values.

-n, --numeric

Print action code values in hexadecimal notation; do not attempt to convert them to symbolic notation.

-S num, --shape=num

Print using num to determine table shape. Values of num are:

0

Default

1

Same as --full-table

2

Same as --separate-lines

3

One line for each keycode up to the first hole, then one line per modifier/keycode pair

e2fsck

e2fsck [options] device

fsck.ext2 [options] device

System administration command. Similar to fsck, but specifically intended for Linux Second Extended Filesystems. When checking a second extended filesystem, fsck calls this command.

Options

-b superblock

Use superblock instead of default superblock.

-d

Debugging mode.

-f

Force checking, even if kernel has already marked the filesystem as valid. e2fsck will normally exit without checking if the system appears to be clean.

-l file

Consult file for a list of bad blocks, in addition to checking for others.

-n

Ensure that no changes are made to the filesystem. When queried, answer "no."

-p

"Preen." Repair all bad blocks noninteractively.

-t

Display timing statistics.

-v

Verbose.

-y

When queried, answer "yes."

-B size

Expect to find the superblock at size; if it's not there, exit.

-F

Flush buffer caches before checking.

-L file

Consult file for list of bad blocks instead of checking filesystem for them.

echo

echo [-n] [string]

This is the /bin/echo command. echo also exists as a command built into the C shell and bash. The following character sequences have special meanings:

\a

Alert (bell)

\b

Backspace

\c

Suppress trailing newline

\f

Form feed

\n

Newline

\r

Carriage return

\t

Horizontal tab

\v

Vertical tab

\\

Literal backslash

\nnn

The octal character whose ASCII code is nnn.

Options

-e

Enable character sequences with special meaning. (In some versions, this option is not required in order to make the sequences work.)

-E

Disable character sequences with special meaning.

-n

Suppress printing of newline after text.

--help

Print help message and then exit.

--version

Print version information and then exit.

Examples

/bin/echo "testing printer" | lp
/bin/echo "TITLE\nTITLE" > file ; cat doc1 doc2 >> file
/bin/echo "Warning: ringing bell \a"
egrep

egrep [options] [regexp] [files]

Search one or more files for lines that match an extended regular expression regexp. egrep doesn't support the regular expressions \(, \), \n, \<, \>, \{, or \} but does support the other expressions, as well as the extended set +, ?, |, and ( ). Remember to enclose these characters in quotes. Regular expressions are described in Chapter 9, "Pattern Matching". Exit status is 0 if any lines match, 1 if none match, and 2 for errors.

See grep for the list of available options. Also see fgrep. egrep typically runs faster than those commands.

Examples

Search for occurrences of Victor or Victoria in file:

egrep 'Victor(ia)*' file
egrep '(Victor|Victoria)' file

Find and print strings such as old.doc1 or new.doc2 in files, and include their line numbers:

egrep -n '(old|new)\.doc?' files
emacs

emacs [options] [files]

A text editor and all-purpose work environment. For more information, see Chapter 10, "The Emacs Editor".

env

env [option] [variable=value ... ] [command]

Display the current environment or, if an environment variable is specified, set it to a new value and display the modified environment. If command is specified, execute it under the modified environment.

Options

-, -i, --ignore-environment

Ignore current environment entirely.

-u name, --unset name

Unset the specified variable.

--help

Print help message and then exit.

--version

Print version information and then exit.

etags

etags [options] files

Create a list of function and macro names that are defined in the specified C, Pascal, FORTRAN, yacc, or flex source files. The output list (named tags by default) contains lines of the form:

name     file     context

where name is the function or macro name, file is the source file in which name is defined, and context is a search pattern that shows the line of code containing name. After the list of tags is created, you can invoke Emacs on any file and type:

ESC-x visit-tags-table

You will be prompted for the name of the tag table; the default is TAGS. To switch to the source file associated with the name listed in tagsfile, type:

ESC-x find-tag

You will be prompted for the tag you would like Emacs to search for. ctags produces an equivalent tags file for use with vi.

Options

-a, --append

Append tag output to existing list of tags.

-d, --defines

Include tag entries for C preprocessor definitions.

-i file, --include=file

Add a note to the tags file that file should be consulted in addition to the normal input file.

-l language, --language=language

Consider the files that follow this option to be written in language. Use the -h option for a list of languages and their default filename extensions.

-o file, --output=file

Write to file.

-r regexp, --regex=regexp

Include a tag for each line that matches regexp in the files following this option.

-C, --c++

Expect .c and .h files to contain C++, not C, code.

-D, --no-defines

Do not include tag entries for C preprocessor definitions.

-H, -h, --help

Print usage information.

-R, --noregex

Don't include tags based on regular-expression matching for the files that follow this option.

-S, --ignore-indentation

Normally etags uses indentation to parse the tag file; this option tells it to rely on it less.

-V, --version

Print the version number.

ex

ex [options] file

An interactive command-based editor. For more information, see Chapter 11, "The vi Editor".

expand

expand [options] files

Convert tabs in given files (or standard input, if the file is named -) to appropriate number of spaces; write results to standard output.

Options

-tabs, -t, --tabs tabs

tabs is a comma-separated list of integers that specify the placement of tab stops. If exactly one integer is provided, the tab stops are set to every integer spaces. By default, tab stops are 8 spaces apart. With -t and --tabs, the list may be separated by whitespace instead of commas.

-i, --initial

Convert tabs only at the beginning of lines.

--help

Print help message and then exit.

--version

Print version information and then exit.

expr

expr arg1 operator arg2 [ operator arg3 ... ]

Evaluate arguments as expressions and print the result. Arguments and operators must be separated by spaces. In most cases, an argument is an integer, typed literally or represented by a shell variable. There are three types of operators: arithmetic, relational, and logical, as well as keyword expressions. Exit status for expr is 0 (expression is nonzero and nonnull), 1 (expression is 0 or null), or 2 (expression is invalid).

Arithmetic operators

Use these to produce mathematical expressions whose results are printed:

+

Add arg2 to arg1.

-

Subtract arg2 from arg1.

*

Multiply the arguments.

/

Divide arg1 by arg2.

%

Take the remainder when arg1 is divided by arg2.

Addition and subtraction are evaluated last, unless they are grouped inside parentheses. The symbols *, (, and ) have meaning to the shell, so they must be escaped (preceded by a backslash or enclosed in single quotes).

Relational operators

Use these to compare two arguments. Arguments can also be words, in which case comparisons are defined by the locale. If the comparison statement is true, the result is 1; if false, the result is 0. Symbols > and < must be escaped.

=, ==

Are the arguments equal?

!=

Are the arguments different?

>

Is arg1 greater than arg2?

>=

Is arg1 greater than or equal to arg2?

<

Is arg1 less than arg2?

<=

Is arg1 less than or equal to arg2?

Logical operators

Use these to compare two arguments. Depending on the values, the result can be arg1 (or some portion of it), arg2, or 0. Symbols | and & must be escaped.

|

Logical OR; if arg1 has a nonzero (and nonnull) value, the result is arg1; otherwise, the result is arg2.

&

Logical AND; if both arg1 and arg2 have a nonzero (and nonnull) value, the result is arg1; otherwise, the result is 0.

:

Like grep; arg2 is a pattern to search for in arg1. arg2 must be a regular expression. If part of the arg2 pattern is enclosed in \( \), the result is the portion of arg1 that matches; otherwise, the result is simply the number of characters that match. By default, a pattern match always applies to the beginning of the first argument (the search string implicitly begins with a ^). Start the search string with .* to match other parts of the string.

Keywords

index string character-list

Return the first position in string that matches the first possible character in character-list. Continue through character-list until a match is found, or return 0.

length string

Return the length of string.

match string regex

Same as string : regex.

quote token

Treat token as a string, even if it would normally be a keyword or an operator.

substr string start length

Return a section of string, beginning with start, with a maximum length of length characters. Return null when given a negative or nonnumeric start or length.

Examples

Division happens first; result is 10:

expr 5 + 10 / 2

Addition happens first; result is 7 (truncated from 7.5):

expr \( 5 + 10 \) / 2

Add 1 to variable i. This is how variables are incremented in shell scripts:

i=`expr $i + 1

Print 1 (true) if variable a is the string "hello":

expr $a = hello

Print 1 (true) if b plus 5 equals 10 or more:

expr $b + 5 \>= 10

Find the 5th, 6th, and 7th letters of the word character:

expr substr character 5 3

In the examples that follow, variable p is the string "version.100". This command prints the number of characters in p:

expr $p : '.*'           Result is 11

Match all characters and print them:

expr $p : '\(.*\)'       Result is "version.100"

Print the number of lowercase letters at the beginning of p:

expr $p : '[a-z]*'       Result is 7

Match the lowercase letters at the beginning of p:

expr $p : '\([a-z]*\)'   Result is "version"

Truncate $x if it contains five or more characters; if not, just print $x. (Logical OR uses the second argument when the first one is 0 or null; i.e., when the match fails.)

expr $x : '\(.....\)' \| $x

In a shell script, rename files to their first five letters:

mv $x `expr $x : '\(.....\)' \| $x

(To avoid overwriting files with similar names, use mv -i.)

false

false

A null command that returns an unsuccessful (nonzero) exit status. Normally used in bash scripts. See also true.

fdformat

fdformat [options] device

Low-level format of a floppy disk. The device for a standard format is usually /dev/fd0 or /dev/fd1.

Option

-n

Do not verify format after completion.

fdisk

fdisk [options] [device]

System administration command. Maintain disk partitions via a menu. fdisk displays information about disk partitions, creates and deletes disk partitions, and changes the active partition. It is possible to assign a different operating system to each of the four partitions, though only one partition is active at any given time. You can also divide a physical partition into several logical partitions. The minimum recommended size for a Linux system partition is 40MB. Normally, device will be /dev/hda, /dev/hdb, /dev/sda, /dev/sdb, /dev/hdc, /dev/hdd, and so on. See also cfdisk.

Options

-l

List partition tables and exit.

-spartition

Display the size of partition, unless it is a DOS partition.

Commands

a

Toggle a bootable flag on current partition.

d

Delete current partition.

l

List all partition types.

m

Main menu.

n

Create a new partition; prompt for more information.

p

Print a list of all partitions and information about each.

q

Quit; do not save.

t

Replace the type of the current partition.

u

Modify the display/entry units, which must be cylinders or sectors.

v

Verify: check for errors; display a summary of the number of unallocated sectors.

w

Save changes; exit.

fetchmail

fetchmail [options] [servers...]

System administration command. Retrieve mail from mail servers and forward it to the local mail delivery system. fetchmail retrieves mail from servers that support the common mail protocols POP2, POP3, IMAP2bis, and IMAP4. Messages are delivered via SMTP through port 25 on the local host and through your system's mail delivery agent (such as sendmail), where they can be read through the user's mail client. fetchmail settings are stored in the ~/.fetchmailrc file. Parameters and servers can also be set on the command line, which will override settings in the .fetchmailrc file. fetchmail is compatible with the popclient program, and users can use both without having to adjust file settings.

Options

-a, --all

Retrieve all messages from server, even ones that have already been seen but left on the server. The default is to only retrieve new messages.

-A type, --auth type

Specify the type of authentication. type may be: password, kerberos_v5, or kerberos. Authentication type is usually established by fetchmail by default, so this option isn't very useful.

-B n, --fetchlimit n

Set the maximum number of messages (n) accepted from a server per query.

-b n, --batchlimit n

Set the maximum number of messages sent to an SMTP listener per connection. When this limit is reached, the connection will be broken and reestablished. The default of 0 means no limit.

-c, --check

Check for mail on a single server without retrieving or deleting messages. Works with IMAP but not well with other protocols, if at all.

-D [domain], --smtpaddress [domain]

Specify the domain name placed in RCPT TO lines sent to SMTP. The default is the local host.

-E header, --envelope header

Change the header assumed to contain the mail's envelope address (usually "X-Envelope-to:") to header.

-e n, --expunge n

Tell an IMAP server to EXPUNGE (i.e., purge messages marked for deletion) after n deletes. A setting of 0 indicates expunging only at the end of the session. Normally, an expunge occurs after each delete.

-F, --flush

For POP3 and IMAP servers, remove previously retrieved messages from the server before retrieving new ones.

-f file, --fetchmailrc file

Specify a nondefault name for the fetchmail configuration file.

-I specification, --interface specification

Require that the mail server machine is up and running at a specified IP address (or range) before polling. The specification is given as interface/ipaddress/mask. The first part indicates the type of TCP connection expected (sl0, ppp0, etc.), the second is the IP address, and the third is the bit mask for the IP, assumed to be 255.255.255.255.

-K, --nokeep

Delete all retrieved messages from the mail server.

-k, --keep

Keep copies of all retrieved messages on the mail server.

-l size, --limit size

Set the maximum message size that will be retrieved from a server. Messages larger than this size will be left on the server and marked unread.

-M interface, --monitor interface

In daemon mode, monitor the specified TCP/IP interface for any activity besides itself, and skip the poll if there is no other activity. Useful for PPP connections that automatically time out with no activity.

-m command, --mda command

Pass mail directly to mail delivery agent, rather than send to port 25. The command is the path and options for the mailer, such as /usr/lib/sendmail -oem. A %T in the command will be replaced with the local delivery address, and an %F will be replaced with the message's From address.

-n, --norewrite

Do not expand local mail IDs to full addresses. This option will disable expected addressing and should only be used to find problems.

-P n, --port n

Specify a port to connect to on the mail server. The default port numbers for supported protocols are usually sufficient.

-p proto, --protocol proto

Specify the protocol to use when polling a mail server. proto can be:

POP2

Post Office Protocol 2.

POP3

Post Office Protocol 3.

APOP

POP3 with MD5 authentication.

RPOP

POP3 with RPOP authentication.

KPOP

POP3 with Kerberos v4 authentication on port 1109.

IMAP

IMAP2bis, IMAP4, or IMAP4rev1. fetchmail autodetects their capabilities.

IMAP-K4

IMAP4 or IMAP4rev1 with Kerberos v4 authentication.

IMAP-GSS

IMAP4 or IMAP4rev1 with GSSAPI authentication.

ETRN

ESMTP.

-Q string, --qvirtual string

Remove the prefix string, which is the local user's hostid, from the address in the envelope header (such as "Delivered-To:").

-r folder, --folder folder

Retrieve the specified mail folder from the mail server.

-s, --silent

Suppress status messages during a fetch.

-U, --uidl

For POP3, track the age of kept messages via unique ID listing.

-u name, --username name

Specify the user name to use when logging into the mail server.

-V, --version

Print the version information for fetchmail and display the options set for each mail server. Performs no fetch.

-v, --verbose

Display all status messages during a fetch.

-Z nnn, --antispam nnn

Specify the SMTP error nnn to signal a spam block from the client. If nnn is -1, this option is disabled.

fgrep

fgrep [options] pattern [files]

Search one or more files for lines that match a literal text string pattern. Exit status is 0 if any lines match, 1 if not, and 2 for errors.

See grep for the list of available options. Also see egrep.

Examples

Print lines in file that don't contain any spaces:

fgrep -v '' file

Print lines in file that contain the words in spell_list:

fgrep -f spell_list file
file

file [options] files

Classify the named files according to the type of data they contain. file checks the magic file (usually /usr/share/magic) to identify some file types.

Options

-b

Brief mode; do not prepend filenames to output lines.

-c

Check the format of the magic file (files argument is invalid with -c). Usually used with -m.

-f file

Read the names of files to be checked from file.

-L

Follow symbolic links. By default, symbolic links are not followed.

-m file

Search for file types in file instead of /usr/share/magic.

-n

Flush standard output after checking a file.

-s

Check files that are block or character special files in addition to checking ordinary files.

-v

Print the version.

-z

Attempt checking of compressed files.

Many file types are understood. Output lists each filename, followed by a brief classification such as:

ascii text
c program text
c-shell commands
data
empty
iAPX 386 executable
directory
[nt]roff, tbl, or eqn input text
shell commands
symbolic link to ../usr/etc/arp

Example

List all files that are deemed to be troff/nroff input:

file * | grep roff
find

find [pathnames] [conditions]

An extremely useful command for finding particular groups of files (numerous examples follow this description). find descends the directory tree beginning at each pathname and locates files that meet the specified conditions. The default pathname is the current directory. The most useful conditions include -print (which is the default if no other expression is given), -name and -type (for general use), -exec and -size (for advanced users), and -mtime and -user (for administrators).

Conditions may be grouped by enclosing them in \( \) (escaped parentheses), negated with ! (use \! in the C shell), given as alternatives by separating them with -o, or repeated (adding restrictions to the match; usually only for -name, -type, -perm). Modification refers to editing of a file's contents. Change refers to modification, permission or ownership changes, and so on; therefore, for example, -ctime is more inclusive than -atime or -mtime.

Conditions and actions

-atime +n | -n | n

Find files that were last accessed more than n (+n), less than n (-n), or exactly n days ago. Note that find changes the access time of directories supplied as pathnames.

-ctime +n | -n | n

Find files that were changed more than n (+n), less than n (-n), or exactly n days ago. A change is anything that changes the directory entry for the file, such as a chmod.

-depth

Descend the directory tree, skipping directories and working on actual files first (and then the parent directories). Useful when files reside in unwritable directories (e.g., when using find with cpio).

-exec command { } \;

Run the Linux command, from the starting directory on each file matched by find (provided command executes successfully on that file; i.e., returns a 0 exit status). When command runs, the argument { } substitutes the current file. Follow the entire sequence with an escaped semicolon (\;).

-follow

Follow symbolic links and track the directories visited (don't use this with -type l).

-group gname

Find files belonging to group gname. gname can be a group name or a group ID number.

-inum n

Find files whose inode number is n.

-links n

Find files having n links.

-mount, -xdev

Search for files that reside only on the same filesystem as pathname.

-mtime +n | -n | n

Find files that were last modified more than n (+n), less than n (-n), or exactly n days ago. A modification is a change to a file's data.

-name pattern

Find files whose names match pattern. Filename metacharacters may be used but should be escaped or quoted.

-newer file

Find files that have been modified more recently than file; similar to -mtime. Affected by -follow only if it occurs after -follow on the command line.

-ok command { }\;

Same as -exec but prompts user to respond with y before command is executed.

-perm nnn

Find files whose permission flags (e.g., rwx) match octal number nnn exactly (e.g., 664 matches -rw-rw-r--). Use a minus sign before nnn to make a "wildcard" match of any unspecified octal digit (e.g., -perm -600 matches -rw-******, where * can be any mode).

-print

Print the matching files and directories, using their full pathnames. Return true.

-regex pattern

Like -path but uses grep-style regular expressions instead of the shell-like globbing used in -name and -path.

-size n[c]

Find files containing n blocks, or if c is specified, n characters long.

-type c

Find files whose type is c. c can be b (block special file), c (character special file), d (directory), p (fifo or named pipe), l (symbolic link), s (socket), or f (plain file).

-user user

Find files belonging to user (name or ID).

-daystart

Calculate times from the start of the day today, not 24 hours ago.

-maxdepth num

Do not descend more than num levels of directories.

-mindepth num

Begin applying tests and actions only at levels deeper than num levels.

-noleaf

Normally, find assumes that each directory has at least two hard links that should be ignored (a hard link for its name and one for "."; i.e., two fewer "real" directories than its hard link count indicates). -noleaf turns off this assumption, a useful practice when find runs on non-Unix-style filesystems. This forces find to examine all entries, assuming that some might prove to be directories into which it must descend (a time-waster on Unix).

-amin +n | -n | n

Find files last accessed more than n (+n), less than n (-n), or exactly n minutes ago.

-anewer file

Find files that were accessed after file was last modified. Affected by -follow when after -follow on the command line.

-cmin +n | -n | n

Find files last changed more than n (+n), less than n (-n), or exactly n minutes ago.

-cnewer file

Find files that were changed after they were last modified. Affected by -follow when after -follow on the command line.

-empty

Continue if file is empty. Applies to regular files and directories.

-false

Return false value for each file encountered.

-fstype type

Match files only on type filesystems. Acceptable types include minix, ext, ext2, xia, msdos, umsdos, vfat, proc, nfs, iso9660, hpfs, sysv, smb, and ncpfs.

-gid num

Find files with numeric group ID of num.

-ilname pattern

A case-insensitive version of -lname.

-iname pattern

A case-insensitive version of -name.

-ipath pattern

A case-insensitive version of -path.

-iregex pattern

A case-insensitive version of -regex.

-lname pattern

Search for files that are symbolic links, pointing to files named pattern. pattern can include shell metacharacters and does not treat / or . specially. The match is case-insensitive.

-mmin +n | -n | n

Find files last modified more than n (+n), less than n (-n), or exactly n minutes ago.

-nouser

The file's user ID does not correspond to any user.

-nogroup

The file's group ID does not correspond to any group.

-path pattern

Find files whose names match pattern. Expect full pathnames relative to the starting pathname (i.e., do not treat / or . specially).

Examples

List all files (and subdirectories) in your home directory:

find $HOME -print

List all files named chapter1 in the /work directory:

find /work -name chapter1 -print

List all files beginning with memo owned by ann:

find /work -name 'memo*' -user ann -print

Search the filesystem (begin at root) for manpage directories:

find / -type d -name 'man*' -print

Search the current directory, look for filenames that don't begin with a capital letter, and send them to the printer:

find . \! -name '[A-Z]*' -exec lpr {}\;

Find and compress files whose names don't end with .gz:

gzip `find . \! -name '*.gz' -print

Remove all empty files on the system (prompting first):

find / -size 0 -ok rm {} \;

Search the system for files that were modified within the last two days (good candidates for backing up):

find / -mtime -2 -print

Recursively grep for a pattern down a directory tree:

find /book -print | xargs grep '[Nn]utshell'

If the files kt1 and kt2 exist in the current directory, their names can be printed with the command:

$ find . -name 'kt[0-9]'
./kt1
./kt2

Since the command prints these names with an initial ./ path, you need to specify the ./ when using the -path option:

$ find . -path './kt[0-9]'
./kt1
./kt2

The -regex option uses a complete pathname, like -path, but treats the following argument as a regular expression rather than a glob pattern (although in this case the result is the same):

$ find . -regex './kt[0-9]'
./kt1
./kt2

finger

finger [options] users

Display data about one or more users, including information listed in the files .plan and .project in each user's home directory. You can specify each user either as a login name (exact match) or as a first or last name (display information on all matching names). Networked environments recognize arguments of the form user@host and @host.

Options

-l

Force long format (default): everything included by the -s option and home directory, home phone, login shell, mail status, .plan, .project, and .forward.

-m

Suppress matching of users' "real" names.

-p

Omit .plan and .project files from display.

-s

Show short format: login name, real name, terminal name, write status, idle time, office location, and office phone number.

fingerd

in.fingerd [option]

TCP/IP command. Remote user information server. fingerd provides a network interface to the finger program. It listens for TCP connections on the finger port and, for each connection, reads a single input line, passes the line to finger, and copies the output of finger to the user on the client machine. fingerd is started by inetd and must have an entry in inetd's configuration file, /etc/inetd.conf.

Option

-w

Include additional information, such as uptime and the name of the operating system.

flex

flex [options] [file]

flex (Fast Lexical Analyzer Generator) is a faster variant of lex. It generates a lexical analysis program (named lex.yy.c) based on the regular expressions and C statements contained in one or more input files. See also bison, yacc, and the O'Reilly book lex & yacc by John Levine, Tony Mason, and Doug Brown.

Options

-b

Generate backup information to lex.backup.

-d

Debug mode.

-f

Use faster compilation (limited to small programs).

-h

Help summary.

-i

Scan case-insensitively.

-l

Maximum lex compatibility.

-o file

Write output to file instead of lex.yy.c.

-p

Print performance report.

-s

Exit if the scanner encounters input that does not match any of its rules.

-t

Print to standard out. (By default, flex prints to lex.yy.c.)

-v

Print a summary of statistics.

-w

Suppress warning messages.

-B

Generate batch (noninteractive) scanner.

-F

Use the fast scanner table representation.

-I

Generate an interactive scanner (default).

-L

Suppress #line directives in lex.yy.c.

-P prefix

Change default yy prefix to prefix for all globally visible variable and function names.

-V

Print version number.

-7

Generate a 7-bit scanner.

-8

Generate an 8-bit scanner (default).

-+

Generate a C++ scanner class.

-C

Compress scanner tables but do not use equivalence classes.

-Ca

Align tables for memory access and computation. This creates larger tables but gives faster performance.

-Ce

Construct equivalence classes. This creates smaller tables and sacrifices little performance (default).

-Cf

Generate full scanner tables, not compressed.

-CF

Generate faster scanner tables, like -F.

-Cm

Construct metaequivalence classes (default).

-Cr

Bypass use of the standard I/O library. Instead use read() system calls.

fmt

fmt [options] [files]

Convert text to specified width by filling lines and removing newlines. Concatenate files on the command line, or read text from standard input if - (or no file) is specified. By default, preserve blank lines, spacing, and indentation. fmt attempts to break lines at the end of sentences and to avoid breaking lines after a sentence's first word or before its last.

Options

-c, --crown-margin

Crown margin mode. Do not change each paragraph's first two lines' indentation. Use the second line's indentation as the default for subsequent lines.

-p prefix, --prefix=prefix

Format only lines beginning with prefix.

-s, --split-only

Suppress line-joining.

-t, --tagged-paragraph

Tagged paragraph mode. Same as crown mode when the indentation of the first and second lines differs. If the indentation is the same, treat the first line as its own separate paragraph.

-u, --uniform-spacing

Print exactly one space between words and two between sentences.

-w width, --width=width

Set output width to width. The default is 75.

--help

Print help message and then exit.

--version

Print version information and then exit.

fold

fold [option] [files]

Break the lines of the named files so that they are no wider than the specified width (default is 80). fold breaks lines exactly at the specified width, even in the middle of a word. Reads from standard input when given - as a file.

Options

-b, --bytes

Count bytes, not columns (i.e., consider tabs, backspaces, and carriage returns to be one column).

-s, --spaces

Break at spaces only, if possible.

-w, --width width

Set the maximum line width to width. Default is 80.

formail

formail [options]

Filter standard input into mailbox format. If no sender is apparent, provide the sender foo@bar. By default, escape bogus From lines with >.

Options

+skip

Do not split first skip messages.

-total

Stop after splitting total messages.

-a headerfield

Append headerfield to header, unless it already exists. If headerfield is Message-ID or Resent-Message-ID with no contents, generate a unique message ID.

-b

Do not escape bogus From lines.

-c

When header fields are more than one line long, concatenate the lines.

-d

Do not assume that input must be in strict mailbox format.

-e

Allow messages to begin one immediately after the other; do not require empty space between them.

-f

Do not edit non-mailbox-format lines. By default, formail prepends From to such lines.

-i headerfield

Append headerfield whether or not it already exists. Rename each existing headerfield to Old-headerfield, unless they are empty.

-k

For use only with -r. Keep the body as well as the fields specified by -r.

-m minfields

Require at least minfields before recognizing the beginning of a new message. Default is 2.

-n

Allow simultaneous formail processes to run.

-p prefix

Escape lines with prefix instead of >.

-q

Do not display write errors, duplicate messages, and mismatched Content-Length fields. This is the default; use -q- to turn it off.

-r

Throw away all existing fields, retaining only X-Loop, and generate autoreply header instead. You can preserve particular fields with the -i option.

-s

Must be the last option; everything following it will be assumed to be its arguments. Divide input to separate mail messages, and pipe them to the program specified or concatenate them to standard output (by default).

-t

Assume sender's return address to be valid. (By default, formail favors machine-generated addresses.)

-u headerfield

Delete all but the first occurrence of headerfield.

-x headerfield

Display the contents of headerfield on a single line.

-z

When necessary, add a space between field names and contents. Remove ("zap") empty fields.

-A headerfield

Append headerfield whether or not it already exists.

-B

Assume that input is in BABYL rmail format.

-D maxlen idcache

Remember old message IDs (in idcache, which will grow no larger than approximately maxlen). When splitting, refuse to output duplicate messages. Otherwise, return true on discovering a duplicate. With -r, look at the sender's mail address instead of the message ID.

-I headerfield

Append headerfield whether or not it already exists. Remove existing fields.

-R oldfield newfield

Change all fields named oldfield to newfield.

-U headerfield

Delete all but the last occurrence of headerfield.

-Y

Format in traditional Berkeley style (i.e., ignore Content-Length fields).

-X headerfield

Display the field name and contents of headerfield on a single line.

free

free [options]

Display statistics about memory usage: total free, used, physical, swap, shared, and buffers used by the kernel.

Options

-b

Calculate memory in bytes.

-k

Default. Calculate memory in kilobytes.

-m

Calculate memory in megabytes.

-o

Do not display "buffer adjusted" line. The -o switch disables the display "-/+ buffers" line.

-s time

Check memory usage every time seconds.

-t

Display all totals on one line at the bottom of output.

-V

Display version information.

fsck

fsck [options] [filesystem] ...

System administration command. Call the filesystem checker for the appropriate system type, to check and repair filesystems. If a filesystem is consistent, the number of files, number of blocks used, and number of blocks free are reported. If a filesystem is inconsistent, fsck prompts before each correction is attempted. fsck's exit code can be interpreted as the sum of all of those conditions that apply:

1

Errors were found and corrected.

2

Reboot suggested.

4

Errors were found but not corrected.

8

fsck encountered an operational error.

16

fsck was called incorrectly.

128

A shared library error was detected.

Options

--

Pass all subsequent options to filesystem-specific checker. All options that fsck doesn't recognize will also be passed.

-r

Interactive mode; prompt before making any repairs.

-s

Serial mode.

-t fstype

Specify the filesystem type. Do not check filesystems of any other type.

-A

Check all filesystems listed in /etc/fstab.

-N

Suppress normal execution; just display what would be done.

-R

Meaningful only with -A: check all filesystems listed in /etc/fstab except the root filesystem.

-T

Suppress printing of title.

-V

Verbose mode.

fsck.minix

fsck.minix [options] device

System administration command. Similar to fsck, but specifically intended for Linux MINIX filesystems.

Options

-a

Automatic mode; repair without prompting.

-f

Force checking, even if kernel has already marked the filesystem. fsck.minix will normally exit without checking if the system appears to be clean.

-l

List filesystems.

-m

Enable MINIX-like "mode not cleared" warnings.

-r

Interactive mode; prompt before making any repairs.

-s

Display information about superblocks.

-v

Verbose mode.

ftp

ftp [options] [hostname]

Transfer files to and from remote network site hostname. ftp prompts the user for a command. The commands are listed after the options. Some of the commands are toggles, meaning they turn on a feature when it is off and vice versa.

Options

-d

Enable debugging.

-g

Disable filename globbing.

-i

Turn off interactive prompting.

-n

No autologin upon initial connection.

-v

Verbose. Show all responses from remote server.

Commands

![command [args]]

Invoke an interactive shell on the local machine. If arguments are given, the first is taken as a command to execute directly, with the rest of the arguments as that command's arguments.

$ macro-name [args]

Execute the macro macro-name that was defined with the macdef command. Arguments are passed to the macro unglobbed.

account [passwd]

Supply a supplemental password that will be required by a remote system for access to resources once a login has been successfully completed. If no argument is given, the user will be prompted for an account password in a nonechoing mode.

append local-file [remote-file]

Append a local file to a file on the remote machine. If remote-file is not given, the local filename is used after being altered by any ntrans or nmap setting. File transfer uses the current settings for type, format, mode, and structure.

ascii

Set the file transfer type to network ASCII (default).

bell

Sound a bell after each file transfer command is completed.

binary

Set file transfer type to support binary image transfer.

bye

Terminate FTP session and then exit ftp.

case

Toggle remote computer filename case mapping during mget. The default is off. When case is on, files on the remote machine with all-uppercase names will be copied to the local machine with all-lowercase names.

cd remote-directory

Change working directory on remote machine to remote-directory.

cdup

Change working directory of remote machine to its parent directory.

chmod [mode] [remote-file]

Change file permissions of remote-file. If options are omitted, the command prompts for them.

close

Terminate FTP session and return to command interpreter.

cr

Toggle carriage return stripping during ASCII-type file retrieval.

delete remote-file

Delete file remote-file on remote machine.

debug [debug-value]

Toggle debugging mode. If debug-value is specified, it is used to set the debugging level.

dir [remote-directory] [local-file]

Print a listing of the contents in the directory remote-directory, and, optionally, place the output in local-file. If no directory is specified, the current working directory on the remote machine is used. If no local file is specified or - is given instead of the filename, output comes to the terminal.

disconnect

Synonym for close.

form format

Set the file transfer form to format. Default format is file.

get remote-file [local-file]

Retrieve the remote-file and store it on the local machine. If the local filename is not specified, it is given the same name it has on the remote machine, subject to alteration by the current case, ntrans, and nmap settings. If local file is -, output comes to the terminal.

glob

Toggle filename expansion for mdelete, mget, and mput. If globbing is turned off, the filename arguments are taken literally and not expanded.

hash

Toggle hash-sign (#) printing for each data block transferred.

help [command]

Print help information for command. With no argument, ftp prints a list of commands.

idle [seconds]

Get/set idle timer on remote machine. seconds specifies the length of the idle timer; if omitted, the current idle timer is displayed.

image

Same as binary.

lcd [directory]

Change working directory on local machine. If directory is not specified, the user's home directory is used.

ls [remote-directory] [local-file]

Print listing of contents of directory on remote machine, in a format chosen by the remote machine. If remote-directory is not specified, current working directory is used.

macdef macro-name

Define a macro. Subsequent lines are stored as the macro macro-name; a null line terminates macro input mode. When $i is included in the macro, loop through arguments, substituting the current argument for $i on each pass. Escape $ with \.

mdelete remote-files

Delete the remote-files on the remote machine.

mdir remote-files local-file

Like dir, except multiple remote files may be specified.

mget remote-files

Expand the wildcard expression remote-files on the remote machine and do a get for each filename thus produced.

mkdir directory-name

Make a directory on the remote machine.

mls remote-files local-file

Like nlist, except multiple remote files may be specified, and the local file must be specified.

mode [mode-name]

Set file transfer mode to mode-name. Default mode is stream mode.

modtime [file-name]

Show last modification time of the file on the remote machine.

mput [local-files]

Expand wildcards in local-files given as arguments and do a put for each file in the resulting list.

newer remote-file [local-file]

Get file if remote file is newer than local file.

nlist [remote-directory] [local-file]

Print list of files of a directory on the remote machine to local-file (or the screen if local-file is not specified). If remote-directory is unspecified, the current working directory is used.

nmap [inpattern outpattern]

Set or unset the filename mapping mechanism. The mapping follows the pattern set by inpattern, a template for incoming filenames, and outpattern, which determines the resulting mapped filename. The sequences $1 through $9 are treated as variables, for example, the inpattern $1.$2, along with the input file readme.txt, would set $1 to readme and $2 to txt. An outpattern of $1.data would result in an output file of readme.data. $0 corresponds to the complete filename. [string1, string2] is replaced by string1, unless that string is null, in which case it's replaced by string2.

ntrans [inchars [outchars ]]

Set or unset the filename character translation mechanism. Characters in a filename matching a character in inchars are replaced with the corresponding character in outchars. If no arguments are specified, the filename mapping mechanism is unset. If arguments are specified:

  • Characters in remote filenames are translated during mput and put commands issued without a specified remote target filename.

  • Characters in local filenames are translated during mget and get commands issued without a specified local target filename.

open host [port]

Establish a connection to the specified host FTP server. An optional port number may be supplied, in which case ftp will attempt to contact an FTP server at that port.

prompt

Toggle interactive prompting.

proxy ftp-command

Execute an FTP command on a secondary control connection (i.e., send commands to two separate remote hosts simultaneously).

put local-file [remote-file]

Store a local file on the remote machine. If remote-file is left unspecified, the local filename is used after processing according to any ntrans or nmap settings in naming the remote file. File transfer uses the current settings for type, file, structure, and transfer mode.

pwd

Print name of the current working directory on the remote machine.

quit

Synonym for bye.

quote arg1 arg2...

Send the arguments specified, verbatim, to the remote FTP server.

recv remote-file [local-file]

Synonym for get.

reget remote-file [local-file]

Retrieve a file (like get), but restart at the end of local-file. Useful for restarting a dropped transfer.

remotehelp [command-name]

Request help from the remote FTP server. If command-name is specified, remote help for that command is returned.

remotestatus [filename]

Show status of the remote machine, or, if filename is specified, filename on remote machine.

rename [from] [to]

Rename file from on remote machine to to.

reset

Clear reply queue.

restart marker

Restart the transfer of a file from a particular byte count.

rmdir [directory-name]

Delete a directory on the remote machine.

runique

Toggle storing of files on the local system with unique filenames. When this option is on, rename files as .1 or .2, and soon, as appropriate, to preserve unique filenames, and report each such action. Default value is off.

send local-file [remote-file]

Synonym for put.

sendport

Toggle the use of PORT commands.

site [command]

Get/set site-specific information from/on remote machine.

size filename

Return size of filename on remote machine.

status

Show current status of ftp.

struct [struct-name]

Set the file transfer structure to struct-name. By default, stream structure is used.

sunique

Toggle storing of files on remote machine under unique filenames.

system

Show type of operating system running on remote machine.

tenex

Set file transfer type to that needed to talk to TENEX machines.

trace

Toggle packet tracing.

type [type-name]

Set file transfer type to type-name. If no type is specified, the current type is printed. The default type is network ASCII.

umask [mask]

Set user file-creation mode mask on the remote site. If mask is omitted, the current value of the mask is printed.

user username [password] [account]

Identify yourself to the remote FTP server. ftp will prompt the user for the password, if not specified and the server requires it, and the account field.

verbose

Toggle verbose mode.

? [command]

Same as help.

ftpd

in.ftpd [options]

TCP/IP command. Internet File Transfer Protocol server. The server uses the TCP protocol and listens at the port specified in the ftp service specification. ftpd is started by inetd and must have an entry in inetd's configuration file, /etc/inetd.conf.

Options

-d

Write debugging information to the syslog.

-l

Log each FTP session in the syslog.

-Tmaxtimeout

Set maximum timeout period in seconds. Default limit is 15 minutes.

-ttimeout

Set timeout period to timeout seconds.

fuser

fuser [options] [files | filesystems]

Identify processes that are using a file or filesystem. fuser outputs the process IDs of the processes that are using the files or local filesystems. Each process ID is followed by a letter code: c if process is using file as current directory, e if executable, f if an open file, m if a shared library, and r if the root directory. Any user with permission to read /dev/kmem and /dev/mem can use fuser, but only a privileged user can terminate another user's process. fuser does not work on remote (NFS) files.

If more than one group of files is specified, the options may be respecified for each additional group of files. A lone dash (-) cancels the options currently in force, and the new set of options applies to the next group of files.

Options

-

Return all options to defaults.

-signal

Send signal instead of SIGKILL.

-a

Display information on all specified files, even if they are not being accessed by any processes.

-i

Request user confirmation to kill a process. Ignored if -k is not also specified.

-k

Send SIGKILL signal to each process.

-l

List signal names.

-m

Expect files to exist on a mounted filesystem; include all files accessing that filesystem.

-s

Silent.

-u

User login name, in parentheses, also follows process ID.

-v

Verbose.

-V

Display version information.

g++

g++ [options] files

Invoke gcc with the options necessary to make it recognize C++. g++ recognizes all the file extensions gcc does, in addition to C++ source files (.C, .cc, or .cxx files) and C++ preprocessed files (.ii files). See also gcc.

gated

gated [options]

TCP/IP command. Gateway routing daemon. gated handles multiple routing protocols and replaces routed and any routing daemons that speak the Hello, EGP, or BGP routing protocols. gated currently handles the RIP, BGP, EGP, Hello, and OSPF routing protocols and can be configured to perform all or any combination of the five.

Options

-c

Parse configuration file for syntax errors, then exit gated, leaving a dump file in /usr/tmp/gated_dump.

-f config_file

Use alternate configuration file, config_file. Default is /etc/gated.conf.

-n

Do not modify kernel's routing table.

-t [trace_options]

Start gated with the specified tracing options enabled. If no flags are specified, assume general. The trace flags are:

adv

Management of policy blocks.

all

Includes normal, policy, route, state, task, and timer.

general

Includes normal and route.

iflist

The kernel interface list.

normal

Normal protocols instances.

parse

Lexical analyzer and parser.

policy

Instances in which policy is applied to imported and exported routes.

route

Any changes to routing table.

state

State machine transitions.

symbols

Symbols read from kernel -- note that they are read before the configuration file is parsed, so this option must be specified on the command line.

task

System tasks and interfaces.

timer

Timer usage.

-C

Parse configuration file for errors and set exit code to indicate if there were any (1) or not (0), then exit.

-N

Do not daemonize.

gawk

gawk [options] `script' [var=value...] [files]

gawk [options] -f scriptfile [var=value...] [files]

The GNU version of awk, a program that does pattern matching, record processing, and other forms of text manipulation. For more information, see Chapter 13, "The gawk Scripting Language".

gcc

gcc [options] files

Compile one or more C source files (file.c), assembler source files (file.s), or preprocessed C source files (file.i). If the file suffix is not recognizable, assume that the file is an object file or library. gcc automatically invokes the link editor ld (unless -c, -S, or -E is supplied). In some cases, gcc generates an object file having a .o suffix and a corresponding root name. By default, output is placed in a.out. gcc accepts many system-specific options not covered here.

Note: gcc is the GNU form of cc; on most Linux systems, the command cc will invoke gcc. The command g++ will invoke gcc with the appropriate options for interpreting C++.

Options

-a

Provide profile information for basic blocks.

-ansi

Enforce full ANSI conformance.

-b machine

Compile for use on machine type.

-c

Create linkable object file for each source file, but do not call linker.

-dD

Print #defines.

-dM

Suppress normal output. Print series of #defines that are in effect at the end of preprocessing.

-dN

Print #defines with macro names only, not arguments or values.

-fno-asm

Do not recognize asm, inline, or typeof as keywords. Implied by -ansi.

-fno-builtin

Do not recognize built-in functions unless they begin with two underscores.

-fno-gnu-keywords

Do not recognize classof, headof, signature, sigof, or typeof as keywords.

-fno-ident

Do not respond to #ident commands.

-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields

Set default control of bitfields to signed or unsigned if not explicitly declared.

-fsigned-char

Cause the type char to be signed.

-fsyntax-only

Check for syntax errors. Do not attempt to actually compile.

-funsigned-char

Cause the type char to be unsigned.

-g

Include debugging information for use with gdb.

-glevel

Provide level amount of debugging information. level must be 1, 2, or 3, with 1 providing the least amount of information. The default is 2.

-idirafter dir

Include dir in the list of directories to search when an include file is not found in the normal include path.

-include file

Process file before proceeding to the normal input file.

-imacros file

Process the macros in file before proceeding to the normal input file.

-iprefix prefix

When adding directories with -iwithprefix, prepend prefix to the directory's name.

-isystem dir

Add dir to the list of directories to be searched when a system file cannot be found in the main include path.

-iwithprefix dir

Append dir to the list of directories to be searched when a header file cannot be found in the main include path. If -iprefix has been set, prepend that prefix to the directory's name.

-llib

Link to lib.

-nostartfiles

Force linker to ignore standard system startup files.

-nostdinc

Search only specified, not standard, directories for header files.

-nostdinc++

Suppress searching of directories believed to contain C++-specific header files.

-nostdlib

Suppress linking to standard library files.

-o file

Specify output file as file. Default is a.out.

-p

Provide profile information for use with prof.

-pedantic

Warn verbosely.

-pedantic-errors

Err in every case in which -pedantic would have produced a warning.

-pg

Provide profile information for use with gprof.

-pipe

Transfer information between stages of compiler by pipes instead of temporary files.

-s

Remove all symbol table and relocation information from the executable.

-save-temps

Save temporary files in the current directory when compiling.

-static

Suppress linking to shared libraries.

-traditional

Attempt to behave like a traditional C compiler.

-traditional-cpp

Cause the preprocessor to attempt to behave like a traditional C preprocessor.

-trigraphs

Include trigraph support.

-u symbol

Force the linker to search libraries for a definition of symbol and to link to them, if found.

-undef

Define only those constants required by the language standard, not system-specific constants like unix.

-v

Verbose mode. Display commands as they are executed, gcc version number, and preprocessor version number.

-w

Suppress warnings.

-x language

Expect input file to be written in language, which may be c, objective-c, c-header, c++, cpp-output, assembler, or assembler-with-cpp. If none is specified as language, guess the language by filename extension.

-Aquestion(answer)

If the preprocessor encounters a conditional such as #if question, assert answer in response. To turn off standard assertions, use -A-.

-Bpath

Specify the path directory in which the compiler files are located.

-C

Retain comments during preprocessing. Meaningful only with -E.

-Dname[=def]

Define name with value def as if by a #define. If no =def is given, name is defined with value 1. -D has lower precedence than -U.

-E

Preprocess the source files, but do not compile. Print result to standard output.

-Idir

Include dir in list of directories to search for include files. If dir is -, search those directories that were specified by -I before the -I- only when #include "file" is specified, not #include <file>.

-Ldir

Search dir in addition to standard directories.

-M

Instead of compiling, print a rule suitable for inclusion in a makefile that describes dependencies of the source file based on its #include directives. Implies -E.

-MD

Similar to -M, but sends dependency information to files ending in .d in addition to ordinary compilation.

-MG

Used with -M or -MM. Suppress error messages if an included file does not exist; useful if the included file is automatically generated by a build.

-MMD

Similar to -MD, but record only user header file information, not system header file information.

-MM

Similar to -M, but limit the rule to non-standard #include files; that is, only files declared through #include "file" and not those declared through #include <file>.

-H

Print pathnames of included files, one per line, on standard error.

-O[level]

Optimize. level should be 1, 2, 3, or 0. The default is 1. 0 turns off optimization; 3 optimizes the most.

-P

Preprocess input without producing line-control information used by next pass of C compiler. Meaningful only with -E.

-S

Compile source files into assembler code, but do not assemble.

-Uname

Remove any initial definition of name, where name is a reserved symbol predefined by the preprocessor or a name defined on a -D option. Names predefined by cpp are unix and i386.

-V version

Attempt to run gcc version version.

-W

Warn more verbosely than normal.

-Wl,option

Invoke linker with option, which may be a comma-separated list.

-Wa,option

Call assembler with option, which may be a comma-separated list.

-Waggregate-return

Warn if any functions return structures or unions are defined or called.

-Wall

Enable -W, -Wchar-subscripts, -Wcomment, -Wformat, -Wimplicit, -Wparentheses, -Wreturn-type, -Wswitch, -Wtemplate-debugging, -Wtrigraphs, -Wuninitialized, and -Wunused.

-Wcast-align

Warn when encountering instances in which pointers are cast to types that increase the required alignment of the target from its original definition.

-Wcast-qual

Warn when encountering instances in which pointers are cast to types that lack the type qualifier with which the pointer was originally defined.

-Wchar-subscripts

Warn when encountering arrays with subscripts of type char.

-Wcomment

Warn when encountering the beginning of a nested comment.

-Wconversion

Warn in particular cases of type conversions.

-Werror

Exit at the first error.

-Wformat

Warn about inappropriately formatted printfs and scanfs.

-Wimplicit

Warn when encountering implicit function or parameter declarations.

-Winline

Warn about illegal inline functions.

-Wmissing-declarations

Warn if a global function is defined without a previous declaration.

-Wmissing-prototypes

Warn when encountering global function definitions without previous prototype declarations.

-Wnested-externs

Warn if an extern declaration is encountered within a function.

-Wno-import

Don't warn about use of #import.

-Wp,options

Pass options to the preprocessor. Multiple options are separated by commas. Not a warning parameter.

-Wparentheses

Enable more verbose warnings about omitted parentheses.

-Wpointer-arith

Warn when encountering code that attempts to determine the size of a function or void.

-Wredundant-decls

Warn if anything is declared more than once in the same scope.

-Wreturn-type

Warn about functions defined without return types or with improper return types.

-Wshadow

Warn when a local variable shadows another local variable.

-Wstrict-prototypes

Insist that argument types be specified in function declarations and definitions.

-Wswitch

Warn about switches that skip the index for one of their enumerated types.

-Wtemplate-debugging

Warn if debugging is not available for C++ templates.

-Wtraditional

Warn when encountering code that produces different results in ANSI C and traditional C.

-Wtrigraphs

Warn when encountering trigraphs.

-Wuninitialized

Warn when encountering uninitialized automatic variables.

-Wunused

Warn about unused variables and functions.

-Xlinker option

Pass an option to the linker. A linker option with an argument requires two -Xs, the first specifying the option and the second specifying the argument.

Pragma directives

#pragma interface [header-file]

Used in header files to force object files to provide definition information via references, instead of including it locally in each file. C++-specific.

#pragma implementation [header-file]

Used in main input files to force generation of full output from header-file (or, if it is not specified, from the header file with the same base name as the file containing the pragma directive). This information will be globally visible. Normally the specified header file contains a #pragma interface directive.

gdb

gdb [options] [program [core|pid]]

GDB (GNU DeBugger) allows you to step through C, C++, and Modula-2 programs in order to find the point at which they break. The program to be debugged is normally specified on the command line; you can also specify a core or, if you want to investigate a running program, a process ID.

Options

-s file, -symbols=file

Consult file for symbol table. With -e, also uses file as the executable.

-e file, -exec=file

Use file as executable, to be read in conjunction with source code. May be used in conjunction with -s to read symbol table from the executable.

-c file, -core=file

Consult file for information provided by a core dump.

-x file, -command=file

Read gdb commands from file.

-d directory, -directory=directory

Include directory in path that is searched for source files.

-n, -nx

Ignore .gdbinit file.

-q, -quiet

Suppress introductory and copyright messages.

-batch

Exit after executing all the commands specified in .gdbinit and -x files. Print no startup messages.

-cd=directory

Use directory as gdb's working directory.

-f, -fullname

Show full filename and line number for each stack frame.

-b bps

Set line speed of serial device used by GDB to bps.

-tty=device

Set standard in and standard out to device.

Common commands

These are just some of the more common gdb commands; there are too many commands to list all of them here:

bt

Print the current location within the program and a stack trace showing how the current location was reached. (where does the same thing.)

break

Set a breakpoint in the program.

cd

Change the current working directory.

clear

Delete the breakpoint where you just stopped.

commands

List commands to be executed when breakpoint is hit.

c

Continue execution from a breakpoint.

delete

Delete a breakpoint or a watchpoint; also used in conjunction with other commands.

display

Cause variables or expressions to be displayed when program stops.

down

Move down one stack frame to make another function the current one.

frame

Select a frame for the next continue command.

info

Show a variety of information about the program. For instance, info breakpoints shows all outstanding breakpoints and watchpoints.

jump

Start execution at another point in the source file.

kill

Abort the process running under gdb's control.

list

List the contents of the source file corresponding to the program being executed.

next

Execute the next source line, executing a function in its entirety.

print

Print the value of a variable or expression.

pwd

Show the current working directory.

ptype

Show the contents of a datatype, such as a structure or C++ class.

quit

Exit gdb.

reverse-search

Search backward for a regular expression in the source file.

run

Execute the program.

search

Search for a regular expression in the source file.

set variable

Assign a value to a variable.

signal

Send a signal to the running process.

step

Execute the next source line, stepping into a function if necessary.

undisplay

Reverse the effect of the display command; keep expressions from being displayed.

until

Finish the current loop.

up

Move up one stack frame to make another function the current one.

watch

Set a watchpoint (i.e., a data breakpoint) in the program.

whatis

Print the type of a variable or function.

gdc

gdc [options] command

TCP/IP command. Administer gated. Various commands start and stop the daemon, send signals to it, maintain the configuration files, and manage state and core dumps.

Options

-c size

Specify maximum core dump size.

-f size

Specify maximum file dump size.

-m size

Specify maximum data segment size.

-n

Suppress editing of the kernel forwarding table.

-q

Quiet mode: suppress warnings and log errors to syslogd instead of standard error.

-s size

Specify maximum stack size.

-t seconds

Wait seconds seconds (default is 10) for gated to complete specified operations at start and stop time.

Commands

BACKOUT

Restore /etc/gated.conf from /etc/gated.conf-, whether or not the latter exists.

backout

Restore /etc/gated.conf from /etc/gated.conf-, assuming the latter exists.

checkconf

Report any syntax errors in /etc/gated.conf.

checknew

Report any syntax errors in /etc/gated.conf+.

COREDUMP

Force gated to core dump and exit.

createconf

Create an empty /etc/gated.conf+ if one does not already exist, and set it to mode 664, owner root, group gdmaint.

dump

Force gated to dump to /usr/tmp/gated_dump and then continue normal operation.

interface

Reload interface configuration.

KILL

Terminate immediately (ungracefully).

modeconf

Set all configuration files to mode 664, owner root, group gdmaint.

newconf

Make sure that /etc/gated.conf+ exists and move it to /etc/gated.conf. Save the old /etc/gated.conf as /etc/gated.conf-.

reconfig

Reload configuration file.

restart

Stop and restart gated.

rmcore

Remove any gated core files.

rmdmp

Remove any gated state dump files.

rmparse

Remove any gated files that report on parse errors. These are generated by the checkconf and checknew commands.

running

Exit with zero status if gated is running and nonzero if it is not.

start

Start gated, unless it is already running, in which case return an error.

stop

Stop gated as gracefully as possible.

term

Terminate gracefully.

toggletrace

Toggle tracing.

Files

/etc/gcd.conf+

The test configuration file. Once you're satisfied that it works, you should run gated newconf to install it as /etc/gated.conf.

/etc/gated.conf-

A backup of the old configuration file.

/etc/gated.conf--

A backup of the backup of the old configuration file.

/etc/gated.conf

The actual configuration file.

/etc/gated.pid

gated's process ID.

/usr/tmp/gated_dump

The state dump file.

/usr/tmp/gated_parse

A list of the parse errors generated by reading the configuration file.

getkeycodes

getkeycodes

Print the kernel's scancode-to-keycode mapping table.

getty

getty [options] port [speed [term [lined]]]

System administration command. Set terminal type, modes, speed, and line discipline. Linux systems may use agetty instead, which uses a different syntax. getty is invoked by init. It is the second process in the series init-getty-login-shell, which ultimately connects a user with the Linux system. getty reads the user's login name and invokes the login command with the user's name as an argument. While reading the name, getty attempts to adapt the system to the speed and type of device being used.

You must specify a port argument, which getty will use to attach itself to the device /dev/port. getty will then scan the defaults file, usually /etc/default/getty, for runtime values and parameters. These may also be specified, for the most part, on the command line, but the values in the defaults file take precedence. The speed argument is used to point to an entry in the file /etc/gettydefs, which contains the initial baud rate, tty settings, and login prompt and final speed and settings for the connection. The first entry is the default in /etc/gettydefs. term specifies the type of terminal, with lined the optional line discipline to use.

Options

-c file

Check the gettydefs file. file is the name of the gettydefs file. Produces the files' values and reports parsing errors to standard output.

-d file

Use a different default file.

-h

Do not force a hangup on the port when initializing.

-r delay

Wait for single character from port, then wait delay seconds before proceeding.

-t timeout

If no username is accepted within timeout seconds, close connection.

-w string

Wait for string characters from port before proceeding.

gprof

gprof [options] [object_file]

Display the profile data for an object file. The file's symbol table is compared with the call graph profile file gmon.out (previously created by compiling with gcc -pg).

Options

-a

Do not display statically declared functions. Since their information might still be relevant, append it to the information about the functions loaded immediately before.

-b

Do not display information about each field in the profile.

-c

Consult the object file's text area to attempt to determine the program's static call graph. Display static-only parents and children with call counts of 0.

-e routine

Do not display entries for routine and its descendants.

-f routine

Print only routine, but include time spent in all routines.

-k from to

Remove arcs between the routines from and to.

-s

Summarize profile information in the file gmon.sum.

-v

Print version and exit.

-z

Include zero-usage calls.

-E routine

Do not display entries for routine and its descendants or include time spent on them in calculations for total time.

-F routine

Print only information about routine. Do not include time spent in other routines.

grep

grep [options] pattern [files]

Search one or more files for lines that match a regular expression pattern. Regular expressions are described in Chapter 9, "Pattern Matching". Exit status is 0 if any lines match, 1 if none match, and 2 for errors. See also egrep and fgrep.

Options

-a, --text

Don't suppress output lines with binary data; treat as text.

-b, --byte-offset

Print the byte offset within the input file before each line of output.

-b, --byte-offset

Print the byte offset within the input file before each line of output.

-c, --count

Print only a count of matched lines. With -v or --revert-match option, count nonmatching lines.

-d action, --directories=action

Define an action for processing directories. Possible actions are:

read

Read directories like ordinary files (default).

skip

Skip directories.

recurse

Recursively read all files under each directory. Same as -r.

-e pattern, --regexp=pattern

Search for pattern. Same as specifying a pattern as an argument, but useful in protecting patterns beginning with -.

-f file, --file=file

Take a list of patterns from file, one per line.

-h, --no-filename

Print matched lines but not filenames (inverse of -l).

-i, --ignore-case

Ignore uppercase and lowercase distinctions.

-l, --files-with-matches

List the names of files with matches but not individual matched lines; scanning per file stops on the first match.

-n, --line-number

Print lines and their line numbers.

-q, --quiet, --silent

Suppress normal output in favor of quiet mode; the scanning stops on the first match.

-r, --recursive

Recursively read all files under each directory. Same as -d recurse.

-s, --no-messages

Suppress error messages about nonexistent or unreadable files.

-v, --revert-match

Print all lines that don't match pattern.

-w, --word-regexp

Match on whole words only. Words are divided by characters that are not letters, digits, or underscores.

-x, --line-regexp

Print lines only if pattern matches the entire line.

-A num, --after-context=num

Print num lines of text that occur after the matching line.

-B num, --before-context=num

Print num lines of text that occur before the matching line.

-C[num], --context=[num], -num

Print num lines of leading and trailing context. Default context is 2 lines.

-L, --files-without-match

List files that contain no matching lines.

-V, --version

Print the version number and then exit.

Examples

List the number of users who use tcsh:

grep -c /bin/tcsh /etc/passwd

List header files that have at least one #include directive:

grep -l '^#include' /usr/include/*

List files that don't contain pattern:

grep -c pattern files | grep :0
groff

groff [options] [files]

troff [options] [files]

Frontend to the groff document-formatting system, which normally runs troff along with a postprocessor appropriate for the selected output device. Options without arguments can be grouped after a single dash (-). A filename of - denotes standard input.

Options

-a

Generate an ASCII approximation of the typeset output.

-b

Print a backtrace.

-C

Enable compatibility mode.

-dcs, -dname=s

Define the character c or string name to be the string s.

-e

Preprocess with eqn.

-E

Don't print any error messages.

-ffam

Use fam as the default font family.

-Fdir

Search dir for subdirectories with DESC and font files before the default /usr/lib/groff/font.

-h

Print a help message.

-i

Read standard input after all files have been processed.

-l

Send the output to a printer (as specified by the print command in the device description file).

-Larg

Pass arg to the spooler. Each argument should be passed with a separate -L option.

-mname

Read the macro file tmac.name.

-Mdir

Search directory dir for macro files before the default directory /usr/lib/groff/tmac.

-nnum

Set the first page number to num.

-N

Don't allow newlines with eqn delimiters; equivalent to eqn's -N option.

-olist

Output only pages specified in list, which is a comma-separated list of page ranges.

-p

Preprocess with pic.

-Parg

Pass arg to the postprocessor. Each argument should be passed with a separate -P option.

-rcn, -name=n

Set the number register c or name to n. c is a single character and n is any troff numeric expression.

-R

Preprocess with refer.

-s

Preprocess with soelim.

-S

Use safer mode (i.e., pass the -S option to pic and use the -msafer macros with troff).

-t

Preprocess with tbl.

-Tdev

Prepare output for device dev; the default is ps.

-v

Make programs run by groff print out their version number.

-V

Print the pipeline on stdout instead of executing it.

-wname

Enable warning name. You can specify multiple -w options. See the troff manpage for a list of warnings.

-Wname

Disable warning name. You can specify multiple -W options. See the troff manpage for a list of warnings.

-z

Suppress troff output (except error messages).

-Z

Do not postprocess troff output. Normally groff automatically runs the appropriate postprocessor.

Devices

ascii

Typewriter-like device

dvi

TeX dvi format

latin1

Typewriter-like devices using the ISO Latin-1 character set

ps

PostScript

X75

75-dpi X11 previewer

X100

100-dpi X11 previewer

lj4

HP LaserJet4-compatible (or other PCL5-compatible) printer

Environment variables

GROFF_COMMAND_PREFIX

If set to be X, groff will run Xtroff instead of troff.

GROFF_FONT_PATH

Colon-separated list of directories in which to search for the devname directory.

GROFF_TMAC_PATH

Colon-separated list of directories in which to search for the macro files.

GROFF_TMPDIR

If set, temporary files will be created in this directory; otherwise, they will be created in TMPDIR (if set) or /tmp (if TMPDIR is not set).

GROFF_TYPESETTER

Default device.

PATH

Search path for commands that groff executes.

groupadd

groupadd [options] group

System administration command. Create new group account group.

Options

-ggid

Assign numerical group ID. (By default, the first available number above 500 is used.) The value must be unique unless the -o option is used.

-o

Accept a nonunique gid with the -g option.

groupdel

groupdel group

System administration command. Remove group from system account files. You may still need to find and change permissions on files that belong to the removed group.

groupmod

groupmod [options] group

System administration command. Modify group information for group.

Options

-g gid

Change the numerical value of the group ID. Any files that have the old gid will have to be changed manually. The new gid must be unique unless the -o option is used.

-n name

Change the group name to name.

-o

Override. Accept a nonunique gid.

groups

groups [options] [users]

Show the groups that each user belongs to (default user is the owner of the current group). Groups are listed in /etc/passwd and /etc/group.

Options

--help

Print help message.

--version

Print version information.

grpck

grpck [option] [files]

System administration command. Remove corrupt or duplicate entries in the /etc/group and /etc/gshadow files. Generate warnings for other errors found. grpck will prompt for a "yes" or "no" before deleting entries. If the user replies "no," the program will exit. If run in a noninteractive mode, the reply to all prompts is "no." Alternate group and gshadow files can be checked. If other errors are found, the user will be encouraged to run the groupmod command.

Option

-n

Noninteractive mode.

Exit codes

0

Success.

1

Syntax error.

2

One or more bad group entries found.

3

Could not open group files.

4

Could not lock group files.

5

Could not write group files.

grpconv

grpconv

grpunconv

System administration command. Like pwconv, the grpconv command creates a shadowed group file to keep your encrypted group passwords safe from password cracking programs. grpconv creates the /etc/gshadow file based on your existing /etc/groups file and replaces your encrypted password entries with x. If you add new entries to the /etc/groups file, you can run grpconv again to transfer the new information to /etc/gshadow. It will ignore entries that already have a password of x and convert those that do not. grpunconv restores the encrypted passwords to your /etc/groups file and removes the /etc/gshadow file.

gs

gs [options] [files]

An interpreter for Adobe Systems' PostScript and PDF (Portable Document Format) languages; used for document processing. With - in place of files, standard input is used.

Options

-- filename arg1 ...

Take the next argument as a filename, but use all remaining arguments to define ARGUMENTS in userdict (not systemdict) as an array of those strings, before running the file.

-gnumber1xnumber2

Specify width and height of device; intended for systems like the X Window System.

-q

Quiet startup.

-rnumber, -rnumber1xnumber2

Specify X and Y resolutions (for the benefit of devices, such as printers, that support multiple X and Y resolutions). If only one number is given, it is used for both X and Y resolutions.

-Dname=token, -dname=token

Define a name in systemdict with the given definition. The token must be exactly one token (as defined by the token operator) and must not contain any whitespace.

-Dname, -dname

Define a name in systemdict with a null value.

-Idirectories

Adds the designated list of directories at the head of the search path for library files.

-Sname=string, -sname=string

Define a name in systemdict with a given string as value.

Special names

-dDISKFONTS

Causes individual character outlines to be loaded from the disk the first time they are encountered.

-dNOBIND

Disables the bind operator. Useful only for debugging.

-dNOCACHE

Disables character caching. Useful only for debugging.

-dNODISPLAY

Suppresses the normal initialization of the output device. May be useful when debugging.

-dNOPAUSE

Disables the prompt and pause at the end of each page.

-dNOPLATFONTS

Disables the use of fonts supplied by the underlying platform (e.g., the X Window System).

-dSAFER

Disables the deletefile and renamefile operators and the ability to open files in any mode other than read-only.

-dWRITESYSTEMDICT

Leaves systemdict writable.

-sDEVICE=device

Selects an alternate initial output device.

-sOUTPUTFILE=filename

Selects an alternate output file (or pipe) for the initial output device.

gunzip

gunzip [options] [files]

Uncompress files compressed by gzip. See gzip for a list of options.

gzexe

gzexe [option] [files]

Compress executables. When run, these files automatically uncompress, thus trading time for space. gzexe creates backup files (filename~), which should be removed after testing the original.

Option

-d

Decompress files.

gzip

gzip [options] [files]

gunzip [options] [files]

zcat [options] [files]

Compress specified files (or read from standard input) with Lempel-Ziv coding (LZ77). Rename compressed file to filename.gz; keep ownership modes and access/modification times. Ignore symbolic links. Uncompress with gunzip, which takes all of gzip's options, except those specified. zcat is identical to gunzip -c and takes the options -fhLV, described here. Files compressed with the compress command can be decompressed using these commands.

Options

-n, --fast, --best

Regulate the speed of compression using the specified digit n, where -1 or --fast indicates the fastest compression method (less compression) and -9 or --best indicates the slowest compression method (most compression). The default compression level is -6.

-a, --ascii

ASCII text mode: convert end-of-lines using local conventions. This option is supported only on some non-Unix systems.

-c, --stdout, --to-stdout

Print output to standard output, and do not change input files.

-d, --decompress, --uncompress

Same as gunzip.

-f, --force

Force compression. gzip would normally prompt for permission to continue when the file has multiple links, its .gz version already exists, or it is reading compressed data to or from a terminal.

-h --help

Display a help screen and then exit.

-l, --list

Expects to be given compressed files as arguments. Files may be compressed by any of the following methods: gzip, deflate, compress, lzh, and pack. For each file, list uncompressed and compressed sizes (the latter being always -1 for files compressed by programs other than gzip), compression ratio, and uncompressed name. With -v, also print compression method, the 32-bit CRC of the uncompressed data, and the timestamp. With -N, look inside the file for the uncompressed name and timestamp.

-L, --license

Display the gzip license and quit.

-n, --no-name

When compressing, do not save the original filename and timestamp by default. When decompressing, do not restore the original filename if present, and do not restore the original timestamp if present. This option is the default when decompressing.

-N, --name

Default. Save original name and timestamp. When decompressing, restore original name and timestamp.

-q, --quiet

Print no warnings.

-r, --recursive

When given a directory as an argument, recursively compress or decompress files within it.

-S suffix, --suffix suffix

Append .suffix. Default is gz. A null suffix while decompressing causes gunzip to attempt to decompress all specified files, regardless of suffix.

-t, --test

Test compressed file integrity.

-v, --verbose

Print name and percent size reduction for each file.

-V, --version

Display the version number and compilation options.

halt

halt [options]

System administration command. Insert a note in the file /var/log/wtmp; if the system is in runlevel 0 or 6, stop all processes; otherwise, call shutdown -nf.

Options

-d

Suppress writing to /var/log/wtmp.

-f

Call halt even when shutdown -nf would normally be called (i.e., force a call to halt, even when not in runlevel 0 or 6).

-n

Suppress normal call to sync.

-w

Suppress normal execution; simply write to /var/log/wtmp.

head

head [options] [files]

Print the first few lines (default is 10) of one or more files. If files is missing or -, read from standard input. With more than one file, print a header for each file.

Options

-c num[bkm], --bytes num

Print first num bytes or, if num is followed by b, k, or m, first num 512-byte blocks, 1-kilobyte blocks, or 1-megabyte blocks.

--help

Display help and then exit.

-n num, --lines num, -num

Print first num lines. Default is 10.

-q, --quiet, --silent

Quiet mode; never print headers giving filenames.

-v, --verbose

Print filename headers, even for only one file.

--version

Output version information and then exit.

Examples

Display the first 20 lines of phone_list:

head -20 phone_list

Display the first 10 phone numbers having a 202 area code:

grep '(202)' phone_list | head
host

host [options] host [server]

host [options] zone [server]

System administration command. Print information about specified hosts or zones in DNS. Hosts may be IP addresses or hostnames; host converts IP addresses to hostnames by default and appends the local domain to hosts without a trailing dot. Default servers are determined in /etc/resolv.conf. For more information about hosts and zones, try Chapters 1 and 2 of DNS and BIND by Paul Albitz and Cricket Liu, published by O'Reilly & Associates.

Options

-a

Same as -t ANY.

-c class

Search for specified resource record class (IN, INTERNET, CS, CSNET, CH, CHAOS, HS, HESIOD, ANY, or *). Default is IN.

-d

Debugging mode. -dd is a more verbose version.

-e

Do not print information about domains outside of specified zone. For hostname queries, do not print "additional information" or "authoritative nameserver."

-f file

Output to file as well as standard out.

-i

Given an IP address, return the corresponding in-addr.arpa address, class (always PTR), and hostname.

-l zone

List all machines in zone.

-m

Print only MR, MG, and MB records; recursively expand MR (renamed mail box) and MG (mail group) records to MB (mail box) records.

-o

Do not print output to standard out.

-p [server]

For use with -l. Query only the zone's primary nameserver (or server) for zone transfers, instead of those authoritative servers that respond. Useful for testing unregistered zones.

-q

Quiet. Suppress warning, but not error, messages.

-r

Do not ask contacted server to query other servers, but require only the information that it has cached.

-t type

Look for type entries in the resource record. type may be A, NS, PTR, ANY, or * (all).

-u

Use TCP, not UDP.

-v

Verbose. Include all fields from resource record, even time-to-live and class, as well as "additional information" and "authoritative nameservers" (provided by the remote nameserver).

-vv

Very verbose. Include information about host's defaults.

-w

Never give up on queried server.

-x

Allow multiple hosts or zones to be specified. If a server is also specified, the argument must be preceded by -X.

-A

For hostnames, look up the associated IP address, and then reverse look up the hostname, to see if a match occurs. For IP addresses, look up the associated hostname, and determine whether the host recognizes that address as its own. For zones, check IP addresses for all hosts. Exit silently if no incongruities are discovered.

-C

Similar to -l, but also check to see if the zone's name servers are really authoritative. The zone's SOA (start of authority) records specify authoritative name servers (in NS fields). Those servers are queried; if they do not have SOA records, host reports a lame delegation. Other checks are made as well.

-D

Similar to -H but include the names of hosts with more than one address per defined name.

-E

Similar to -H but do not treat extra-zone hosts as errors. Extra-zone hosts are hosts in an undefined subdomain.

-F file

Redirect standard out to file, and print extra resource record output only on standard out.

-G zone

Similar to -H but include the names of gateway hosts.

-H zone

Print the number of unique hosts within zone. Do not include aliases. Also list all errors found (extra-zone names, duplicate hosts).

-I chars

Do not print warnings about domain names containing illegal characters chars, such as _.

-L level

For use with -l. List all delegated zones within this zone, up to level deep, recursively.

-P servers

For use with -l. servers should be a comma-separated list. Specify preferred hosts for secondary servers to use when copying over zone data. Highest priority is given to those servers that match the most domain components in a given part of servers.

-R

Treat non-fully-qualified hostnames as BIND does, searching each component of the local domain.

-S

For use with -l. Print all hosts within the zone to standard out. Do not print hosts within subzones. Include class and IP address. Print warning messages (illegal names, lame delegations, missing records, etc.) to standard error.

-T

Print time-to-live values (how long information about each host will remain cached before the nameserver refreshes it).

-X server

Specify a server to query, and allow multiple hosts or zones to be specified.

-Z

When printing recource records, include trailing dot in domain names, and print time-to-live value and class name.

hostid

hostid

Print the ID number in hexadecimal of the current host.

hostname

hostname [option] [nameofhost]

Set or print name of current host system. A privileged user can set the hostname with the nameofhost argument.

Option

-a, --alias

Display the alias name of the host (if used).

-d, --domain

Print DNS domain name.

-f, --fqdn, --long

Print fully qualified domain name.

-F file, --file file

Consult file for hostname.

-h, --help

Print a help message and then exit.

-i, --ip-address

Display the IP address(es) of the host.

-s, --short

Trim domain information from the printed name.

-v, --verbose

Verbose mode.

-V, --version

Print version information and then exit.

-y, --yp, --nis

Display the NIS domain name. A privileged user can set a new NIS domain name with nameofhost.

hwclock

hwclock [options]

System administration command. Read or set the hardware clock. This command maintains change information in /etc/adjtime, which can be used to adjust the clock based on how much it drifts over time. hwclock replaces the clock command. The single-letter options are included for compatibility with the older command.

Options

You may specify only one of the following options:

-a

Adjust the hardware clock based on information in /etc/adjtime and set the system clock to the new time.

--adjust

Adjust the hardware clock based on information in /etc/adjtime.

--date date

Meaningful only with the --set option. date is a string appropriate for use with the date command.

--debug

Print information about what hwclock is doing.

-r, --show

Print the current time stored in the hardware clock.

-s, --hctosys

Set the system time in accordance with the hardware clock.

--set

Set the hardware clock according to the time given in the --date parameter.

--test

Do not actually change anything. This is good for checking syntax.

-u, --utc

The hardware clock is stored in Universal Coordinated Time.

--version

Print version and exit.

-w, --systohc

Set the hardware clock in accordance with the system time.

icmpinfo

icmpinfo [options]

TCP/IP command. Intercept and interpret ICMP packets. Print the address and name of the message's sender, the source port, the destination port, the sequence, and the packet size. By default, provide information only about packets that are behaving oddly.

Options

-k

Kill the syslogd process begun by -l.

-l

Record via syslogd. Only a privileged user may use this option.

-n

Use IP addresses instead of hostnames.

-p

Suppress decoding of port number: do not attempt to guess the name of the service that is listening at that port.

-s

Include IP address of interface that received the packet, in case there are several interfaces on the host machine.

-v

Verbose. Include information about normal ICMP packets. You may also specify -vv and -vvv for extra verbosity.

id

id [options] [username]

Display information about yourself or another user: user ID, group ID, effective user ID and group ID if relevant, and additional group IDs.

Options

-g, --group

Print group ID only.

-G, --groups

Print supplementary groups only.

-n, --name

With -u, -g, or -G, print user or group name, not number.

-r, --real

With -u, -g, or -G, print real, not effective, user ID or group ID.

-u, --user

Print user ID only.

--help

Print help message and then exit.

--version

Print version information.

identd

in.identd [options] [kernelfile [kmemfile]]

TCP/IP command. Provide the name of the user whose process is running a specified TCP/IP connection. You may specify the kernel and its memory space.

Options

-a ip_address

Bind to ip_address. Useful only with -b. By default, bind to the INADDR_ANY address.

-b

Run standalone; not for use with inetd.

-d

Allow debugging requests.

-ggid

Attempt to run in the group gid. Useful only with -b.

-i

Run as a daemon, one process per request.

-l

Log via syslogd.

-m

Allow multiple requests per session.

-n

Return user IDs instead of usernames.

-N

Do not provide a user's name or user ID if the file .noident exists in the user's home directory.

-o

When queried for the type of operating system, always return OTHER.

-pport

Listen at port instead of the default, port 113.

-tseconds

Exit if no new requests have been received before seconds seconds have passed. Note that, with -i or -w, the next new request will result in identd being restarted. Default is infinity (never exit).

-uuid

Attempt to run as uid. Useful only with -b.

-V

Print version and exit.

-w

Run as a daemon, one process for all requests.

ifconfig

ifconfig [interface]

ifconfig [interface address_family parameters addresses]

TCP/IP command. Assign an address to a network interface and/or configure network interface parameters. ifconfig is typically used at boot time to define the network address of each interface on a machine. It may be used at a later time to redefine an interface's address or other parameters. Without arguments, ifconfig displays the current configuration for a network interface. Used with a single interface argument, ifconfig displays that particular interface's current configuration.

Arguments

interface

String of the form name unit, for example, en0.

address_family

Since an interface may receive transmissions in differing protocols, each of which may require separate naming schemes, you can specify the address_family to change the interpretation of the remaining parameters. You may specify inet (the default; for TCP/IP), ax25 (AX.25 Packet Radio), ddp (Appletalk Phase 2), or ipx (Novell).

Parameters

The following parameters may be set with ifconfig:

allmulti/-allmulti

Enable/disable sending of incoming frames to the kernel's network layer.

arp/-arp

Enable/disable use of the Address Resolution Protocol in mapping between network-level addresses and link-level addresses.

broadcast

(inet only.) Specify address to use to represent broadcasts to the network. Default is the address with a host part of all 1s (i.e., x.y.z.255 for a class C network).

debug/-debug

Enable/disable driver-dependent debugging code.

dest_address

Specify the address of the correspondent on the other end of a point-to-point link.

down

Mark an interface "down" (unresponsive).

hw class address

Set the interface's hardware class and address. class may be ether (Ethernet), ax25 (AX.25 Packet Radio), or ARCnet.

irq addr

Set the device's interrupt line.

metric n

Set routing metric of the interface to n. Default is 0.

mtu num

Set the interface's Maximum Transfer Unit (MTU).

multicast

Set the multicast flag.

netmask mask

(inet only.) Specify how much of the address to reserve for subdividing networks into subnetworks. mask can be specified as a single hexadecimal number with a leading 0x, with a dot notation Internet address, or with a pseudonetwork name listed in the network table /etc/networks.

pointopoint/-pointopoint [address]

Enable/disable point-to-point interfacing, so that the connection between the two machines is dedicated.

up

Mark an interface "up" (ready to send and receive).

trailers/-trailers

Request/disable use of a "trailer" link-level encapsulation when sending.

address

Either a hostname present in the hostname database (/etc/hosts), or an Internet address expressed in the Internet standard dot notation.

imake

imake options

C preprocessor (cpp) interface to the make utility. imake (for include make) solves the portability problem of make by allowing machine dependencies to be kept in a central set of configuration files, separate from the descriptions of the various items to be built. The targets are contained in the Imakefile, a machine-independent description of the targets to be built, written as cpp macros. imake uses cpp to process the configuration files and the Imakefile, and to generate machine-specific Makefiles, which can then be used by make.

One of the configuration files is a template file, a master file for imake. This template file (default is Imake.tmpl) #includes the other configuration files that contain machine dependencies such as variable assignments, site definitions, and cpp macros, and directs the order in which the files are processed. Each file affects the interpretation of later files and sections of Imake.tmpl. Comments may be included in imake configuration files, but the initial # needs to be preceded with an empty C comment:

/**/#

For more information, see cpp and make. Also check out the Nutshell Handbook Software Portability with imake, by Paul DuBois.

Options

-Ddefine

Set directory-specific variables. This option is passed directly to cpp.

-e

Execute the generated Makefile. Default is to leave this to the user.

-f filename

Name of per-directory input file. Default is Imakefile.

-Idirectory

Directory in which imake template and configuration files may be found. This option is passed directly to cpp.

-s filename

Name of make description file to be generated. If filename is a -- , the output is written to stdout. The default is to generate, but not execute, a Makefile.

-Ttemplate

Name of master template file used by cpp. This file is usually located in the directory specified with the -I option. The default file is Imake.tmpl.

-v

Print the cpp command line used to generate the Makefile.

Tools

Following is a list of tools used with imake:

makedepend [options] files

Create header file dependencies in Makefiles. make- depend reads the named input source files in sequence and parses them to process #include, #define, #undef, #ifdef, #ifndef, #endif, #if, and #else directives so it can tell which #include directives would be used in a compilation. makedepend determines the dependencies and writes them to the Makefile. make then knows which object files must be recompiled when a dependency has changed. makedepend has the following options:

-- options --

Ignore any unrecognized options following a double hyphen. A second double hyphen terminates this action. Recognized options between the hyphens are processed normally.

-a

Append dependencies to any existing ones instead of replacing existing ones.

-ffilename

Write dependencies to filename instead of to Makefile.

-m

Print a warning when encountering a multiple inclusion.

-sstring

Use string as delimiter in file, instead of # DO NOT DELETE THIS LINE -- make depend depends on it.

-v

Verbose. List all files included by main source file.

-Dname

Define name with the given value (first form) or with value 1 (second form).

-Idir

Add directory dir to the list of directories searched.

-Ydir

Search only dir for include files. Ignore standard include directories.

mkdirhier dir...

Create directory dir and all missing parent directories during file installation operations.

xmkmf [option] [topdir] [curdir]

Bootstrap a Makefile from an Imakefile. topdir specifies the location of the project root directory. curdir (usually omitted) is specified as a relative pathname from the top of the build tree to the current directory. The -a option is equivalent to the following command sequence:

     % xmkmf
     % make Makefiles
     % make includes
     % make depend

Configuration files

Following is a list of the imake configuration files:

Imake.tmpl

Master template for imake. Imake.tmpl includes all the other configuration files, plus the Imakefile in the current directory.

Imake.params

Contains definitions that apply across sites and vendors.

Imake.rules

Contains cpp macro definitions that are configured for the current platform. The macro definitions are fed into imake, which runs cpp to process the macros. Newlines (line continuations) are indicated by the string @@\ (double at sign, backslash).

site.def

Contains site-specific (as opposed to vendor-specific) information, such as installation directories, what set of programs to build, and any special versions of programs to use during the build. The site.def file changes from machine to machine.

Project.tmpl

File containing X-specific variables.

Library.tmpl

File containing library rules.

Server.tmpl

File containing server-specific rules.

.cf

The .cf files are the vendor-specific VendorFiles that live in Imake.vb. A .cf file contains platform-specific definitions, such as version numbers of the operating system and the compiler and workarounds for missing commands. The definitions in .cf files override the defaults, defined in Imake.params.

The Imakefile

The Imakefile is a per-directory file that indicates targets to be built and installed and rules to be applied. imake reads the Imakefile and expands the rules into Makefile target entries. An Imakefile may also include definitions of make variables and list the dependencies of the targets. The dependencies are expressed as cpp macros, defined in Imake.rules. Whenever you change an Imakefile, you need to rebuild the Makefile and regenerate header file dependencies. For more information on imake, see Software Portability with imake by Paul DuBois.

imapd

imapd

TCP/IP command. The Interactive Mail Access Protocol (IMAP) server daemon. imapd is invoked by inetd and listens on port 143 for requests from IMAP clients. IMAP allows mail programs to access remote mailboxes as if they were local. IMAP is a richer protocol than POP because it allows a client to retrieve message-level information from a server mailbox instead of the entire mailbox. IMAP can be used for online and offline reading. The popular Pine mail client contains support for IMAP.

inetd

inetd [option] [configuration_file]

TCP/IP command. Internet services daemon. inetd listens on multiple ports for incoming connection requests. When it receives one, it spawns the appropriate server. When started, inetd reads its configuration information from either configuration_file, or from the default configuration file /etc/inetd.conf. It then issues a call to getservbyname, creates a socket for each server, and binds each socket to the port for that server. It does a listen on all connection-based sockets, then waits, using select for a connection or datagram.

When a connection request is received on a listening socket, inetd does an accept, creating a new socket. It then forks, dups, and execs the appropriate server. The invoked server has I/O to stdin, stdout, and stderr done to the new socket, connecting the server to the client process.

When there is data waiting on a datagram socket, inetd forks, dups, and execs the appropriate server, passing it any server program arguments. A datagram server has I/O to stdin, stdout, and stderr done to the original socket. If the datagram socket is marked as wait, the invoked server must process the message before inetd considers the socket available for new connections. If the socket is marked nowait, inetd continues to process incoming messages on that port.

The following servers may be started by inetd: bootpd, bootpgw, fingerd, ftpd, imapd, popd, rexecd, rlogind, rshd, talkd, telnetd, and tftpd. Do not arrange for inetd to start named, routed, rwhod, sendmail, listen, or any NFS server.

inetd rereads its configuration file when it receives a hangup signal, SIGHUP. Services may be added, deleted, or modified when the configuration file is reread.

Option

-d

Turn on socket-level debugging and print debugging information to stdout.

Files

/etc/inetd.conf

Default configuration file.

/var/run/inetd.pid

inetd's process ID.

info

info [options] [topics]

GNU hypertext reader: display online documentation previously built from Texinfo input. Info files are arranged in a hierarchy and can contain menus for subtopics. When entered without options, the command displays the top-level info file (usually /usr/local/info/dir). When topics are specified, find a subtopic by choosing the first topic from the menu in the top-level info file, the next topic from the new menu specified by the first topic, and so on. The initial display can also be controlled by the -f and -n options.

Options

-d directories, --directory directories

Search directories, a colon-separated list, for info files. If this option is not specified, use the INFOPATH environment variable or the default directory (usually /usr/local/info).

--dribble file

Store each keystroke in file, which can be used in a future session with the --restore option to return to this place in info.

-f file, --file file

Display specified info file.

-n node, --node node

Display specified node in the info file.

-o file, --output file

Copy output to file instead of displaying it at the screen.

--help

Display brief help.

--restore file

When starting, execute keystrokes in file.

--subnodes

Display subtopics.

--version

Display version.

--vi-keys

Use vi-like key bindings.

init

init [option] [runlevel]

System administration command.

Option

-t seconds

When changing runlevels, send SIGKILL seconds after SIGTERM. Default is 20.

Files

init is the first process run by any Unix machine at boot time. It verifies the integrity of all filesystems and then creates other processes, using fork and exec, as specified by /etc/inittab. Which processes may be run are controlled by runlevel. All process terminations are recorded in /var/run/utmp and /var/log/wtmp. When the runlevel changes, init sends SIGTERM and then, after 20 seconds, SIGKILL to all processes that cannot be run in the new runlevel.

Runlevels

The current runlevel may be changed by telinit, which is often just a link to init. The default runlevels vary from distribution to distribution, but these are standard:

0

Halt the system.

1, s, S

Single-user mode.

6

Reboot the system.

q, Q

Reread /etc/inittab.

Check the /etc/inittab file for runlevels on your system.

insmod

insmod [options] file [symbol=value ...]

System administration command. Load the module file into the kernel, changing any symbols that are defined on the command line. If the module file is named file.o or file.mod, the module will be named file.

Options

-f

Force loading of module, even if some problems are encountered.

-m

Output a load map.

-o name

Name module name instead of attempting to name it from the object file's name.

-x

Do not export: do not add any external symbols from the module to the kernel's symbol table.

install

install [options] [file] directories

System administration command. Used primarily in makefiles to update files. install copies files into user-specified directories. It will not overwrite a file. Similar to cp but attempts to set permission modes, owner, and group.

Options

-d, --directory

Create any missing directories.

-g group, --group group

Set group ID of new file to group (privileged users only).

-m mode, --mode mode

Set permissions of new file to mode (octal or symbolic). By default, the mode is 0755.

-o [owner], --owner [owner]

Set ownership to owner or, if unspecified, to root (privileged users only).

-s, --strip

Strip symbol tables.

ipchains

ipchains command [options]

System administration command. Edit IP firewall rules in the 2.2 Linux kernel. A 2.2 Linux kernel compiled with firewall support will examine the headers of all network packets and compare them to matching rules to see what it should do with the packet. A firewall rule consists of some matching criteria and a target, a result to be applied if the packet matches the criteria. The rules are organized into chains. You can use these rules to build a firewall or just reject certain kinds of network connections.

Firewall rules are organized into chains, an ordered checklist that the kernel works through looking for matches. There are three built-in chains input, output, and forward. Packets entering the system are tested against the input chain. Those exiting the system are checked against the output chain. If an incoming packet is destined for some other system, it is checked against the forward chain. Each of these chains has a default target, a policy, in case no match is found. User-defined chains can be created and used as targets for packets, but they have no default policies. If no match can be found in a user-defined chain, the packet is returned to the chain from which it was called and tested against the next rule in that chain.

ipchains only changes the rules in the running kernel. When the system is powered off, all those changes are lost. You can use the ipchains-save command to make a script you can later run with ipchains-restore to restore your firewall settings. Such a script is often called at boot up and many distributions have an ipchains initialization script that uses the output from ipchains-save.

Commands

ipchains is always invoked with one of the following commands:

-A chain rules, --append chain rules

Append new rules to chain.

-I chain number rules, --insert <chain number rules

Insert rules into chain at the ordinal position given by number.

-D chain rules, --delete chain rules

Delete rules from chain. Rules can be specified by their ordinal number in the chain as well as by a general rule description.

-R chain number rule, --replace chain number rule

Replace a rule in chain. The rule to be replaced is specified by its ordinal number.

-C chain rule, --check chain rules

Construct a network packet that matches the given rule and check how chain will handle it. The rule must describe the source, destination, protocol, and interface of the packet to be constructed.

-L [chain], --list $PARAMETER

List the rules in chain. If no chain is specified, list the rules in all chains.

-ML, --masquerading --list

List masquerading connections.

-MS tcp tcpfin udp, --masquerading --set tcp tcpfin udp

Set timeout value in seconds for masquerading connections. -MS always takes three parameters specifying the timeout values for TCP sessions, TCP sessions that have received a FIN packet, and UDP packets.

-F chain, --flush chain

Remove all rules from chain.

-Z [chain], --zero [chain]

Reset the packet and byte counters in chain. If no chain is specified, all chains will be reset. When used without specifying a chain and combined with the -L command, it lists the current counter values before they are reset.

-N chain, --new-chain chain

Create a new chain. The chain's name must be unique.

-X [chain], --delete-chain chain

Delete chain. Only user-defined chains can be deleted, and there can be no references to the chain to be deleted. If no argument is given, all user-defined chains will be deleted.

-P chain target, --policy chain target

Set the policy for a built-in chain; the target itself cannot be a chain.

-h [icmp]

Print a brief help message. If the option icmp is given, print a list of valid ICMP types.

Targets

A target can be the name of a chain or one of the following special values:

ACCEPT

Let the packet through.

DENY

Drop the packet.

MASQ

Masquerade the packet so it appears that it originated from the current system. Reverse packets from masqueraded connections are unmasqueraded automatically. This is a legal target for only the forward chain, or user-defined chains used in forwarding packets. To use this target, the kernel must be compiled with support for IP masquerading.

REDIRECT [port]

Redirect incoming packets to a local port on which you are running a transparent proxy program. If the specified port is 0 or is not given, the destination port of the packet is used as the redirection port. REDIRECT is only a legal target for the input chain or user-defined chains used in handling incoming packets. The kernel must be compiled with support for transparent proxies.

REJECT

Drop the packet and send an ICMP message back to the sender indicating the packet was dropped.

RETURN

Return to the chain from which this chain was called and check the next rule. If RETURN is the target of a rule in a built-in chain, then the built-in chain's default policy is applied.

Rule specification parameters

These options are used to create rules for use with the preceding commands. Rules consist of some matching criteria and usually a target to jump to (-j) if the match is made. Many of the parameters for these matching rules can be expressed as a negative with an exclamation point (!) meaning "not." Those rules will match everything except the given parameter.

-p [!] name, --protocol [!]$PARAMETER

Match packets of protocol name. The value of name can be given as a name or number as found in the file /etc/protocols. The most common values are tcp, udp, icmp, or the special value all. The number 0 is equivalent to all, and this is the default value when this option is not used.

-s [!] address[/mask] [!] [port], --source [!] address[/mask] [!] [port]

Specifies the source address and port of the packet that will match this rule. The address may be supplied as a hostname, a network name, or an IP address. The optional mask is the netmask to use and may be supplied either in the traditional form (e.g., /255.255.255.0) or in the modern form (e.g., /24). The optional port specifies the TCP, UDP, or ICMP type that will match. You may supply a port specification only if you've supplied the -p parameter with one of the tcp, udp or icmp protocols. A colon can be used to indicate an inclusive range of ports or ICMP values to be used. (e.g., 20:25 for ports 20 through 25). If the first port parameter is missing, the default value is 0. If the second is omitted, the default value is 65535.

-d [!] address[/mask] [!] [port], --destination [!] address[/mask] [port]

Match packets with the destination address. The syntax for this command's parameters is the same as for the -s option.

-j target, --jump target

Jump to a special target or a user-defined chain. If this option is not specified for a rule, matching the rule only increases the rule's counters and the packet is tested against the next rule.

-i [!] name, --interface name

Match packets from interface name[+]. name is the network interface used by your system (e.g., eth0 or ppp0). A + can be used as a wildcard, so ppp+ would match any interface name beginning with ppp.

[!] -f, [!]--fragment $PARAMETER

The rule applies to everything but the first fragment of a fragmented packet.

--source-port [!] port

Match packets from the source port. The syntax for specifying ports can be found in the preceding description of the -s option.

--destination-port [!] port

Match packets with the destination port. The syntax for specifying ports can be found in the preceding description of the -s option.

--icmp-type [!] type

Match packets with ICMP type name or number of type.

Options

-b, --bidirectional

Put rule in both the input and output chain so packets will be matched in both directions.

-v, --verbose

Verbose mode.

-n, --numeric

Print all IP address and port numbers in numeric form. By default, names are displayed when possible.

-l, --log

Log information for the matching packet to the system log.

-t andmask xormask, --TOS andmask xormask

Change the Type of Service field in the packet's header. The TOS field is first ANDed with the 8-bit hexadecimal mask andmask, then XORed with the 8-bit hexadecimal mask xormask. Rules that would affect the least significant bit (LSB) portion of the TOS field are rejected.

-x, --exact

Expand all numbers in a listing (-L). Display the exact value of the packet and byte counters instead of rounded figures.

[!] -y, --syn

Match only incoming TCP connection requests, those with the SYN bit set and the ACK and FIN bits cleared. This blocks incoming TCP connections but leaves outgoing connections unaffected.

--line-numbers

Used with the -L command. Add the line number to the beginning of each rule in a listing indicating its position in the chain.

--no-warnings

Disable all warnings

ipchains-restore

ipchains-restore [options]

System administration command. Restore firewall rules. ipchains-restore takes commands generated by ipchains-save and uses them to restore the firewall rules for each chain. Often used by initialization scripts to restore firewall settings on boot.

Options

-f

Force updates of existing chains without asking.

-v

Print rules as they are being restored.

-p

If a nonexisting chain is targeted by a rule, create it.

ipchains-save

ipchains-save [chain] [option]

System administration command. Print the IP firewall rules currently stored in the kernel to stdout. If no chain is given, all chains will be printed. Output is usually redirected to a file, which can later be used by ipchains-restore to restore the firewall.

Option

- v

Print out rules to stderr as well as stdout, making them easier to see when redirecting output.

ipfwadm

ipfwadm category command parameters [options]

ipfwadm -M [ -l | -s ] [options]

Administer a firewall and its rules, firewall accounting, and IP masquerading in the 2.0 Linux kernel. This command is replaced with ipchains in the 2.2 kernel, and ipchains is replaced by iptables in the 2.4 kernel.

There are four categories of rules: IP packet accounting, IP input firewall, IP output firewall, and IP forwarding firewall. The rules are maintained in lists, with a separate list for each category. See the manpage for ipfw(4) for a more detailed description of how the lists work.

Each ipfwadm command specifies only one category and one rule. To create a secure firewall, you issue multiple ipfwadm commands; the combination of their rules work together to ensure that your firewall operates as you intend it to. The second form of the command is for masquerading. The commands -l and -s described in the later list are the only ones that can be used with the masquerading category, -M.

Categories

One of the following flags is required to indicate the category of rules to which the command that follows the category applies.

-A [direction]

IP accounting rules. Optionally, a direction can be specified:

in

Count only incoming packets.

out

Count only outgoing packets.

both

Count both incoming and outgoing packets; this is the default.

-F

IP forwarding firewall rules.

-I

IP input firewall rules.

-M

IP masquerading administration. Can be used only with the -l or -s command.

-O

IP output firewall rules.

Commands

The category is followed by a command indicating the specific action to be taken. Unless otherwise specified, only one action can be given on a command line. For the commands that can include a policy, the valid policies are:

accept

Allow matching packets to be received, sent, or forwarded.

deny

Block matching packets from being received, sent, or forwarded.

reject

Block matching packets from being received, sent, or forwarded and also return an ICMP error message to the sending host.

The commands are:

-a [policy]

Append one or more rules to the end of the rules for the category. No policy is specified for accounting rules. For firewall rules, a policy is required. When the source and/or destination names resolve to more than one address, a rule is added for each possible address combination.

-c

Check whether this IP packet would be accepted, denied, or rejected by the type of firewall represented by this category. Valid only when the category is -I, -O, or -F. Requires the -V parameter to be specified (see "Parameters," later).

-d [policy]

Delete one or more entries from the list of rules for the category. No policy is specified for accounting rules. The parameters specified with this command must exactly match the parameters from an append or insert command, or no match will be found and the rule will not be removed. Only the first matching rule in the list of rules is deleted.

-f

Remove (flush) all rules for the category.

-h

Display a help message with a brief description of the command syntax. Specified with no category:

     % ipfwadm -h
-i [policy]

Insert a new rule at the beginning of the selected list for the category. No policy is specified for accounting rules. For firewall rules, a policy is required. When the source and/or destination names resolve to more than one address, a rule is added for each possible address combination.

-l

List all rules for the category. This option may be combined with the -z option to reset the packet and byte counters after listing their current values. Unless the -x option is also specified, the packet and byte counters are shown as numberK or numberM, rounded to the nearest integer. See also the -e option described under "Options" later.

-p policy

Change the default policy for the selected type of firewall to policy. The default policy is used when no matching rule is found. Valid only with -I, -O, or -F.

-s tcp tcpfin udp

Set the masquerading timeout values; valid only with -M. The three parameters are required and represent the timeout value in seconds for TCP sessions, TCP sessions after receiving a FIN packet, and UDP packets, respectively. A timeout value of 0 preserves the current timeout value of the corresponding entry.

-z

Reset the packet and byte counters for all rules in the category. This command may be combined with the -l command.

Parameters

The following parameters can be specified with the -a, -i, -d, or -c commands, except as noted. Multiple parameters can be specified on a single ipfwadm command line.

-D address[/mask] [port ...]

The destination specification (optional). See the description of -S for the syntax, default values, and other requirements. ICMP types cannot be specified with -D.

-P protocol

The protocol of the rule or packet; possible values are tcp, udp, icmp, or all. Defaults to all, which matches all protocols. -P cannot be specified with the -c command.

-S address[/mask] [port ...]

The source IP address, specified as a hostname, a network name, or an IP address. The source address and mask default to 0.0.0.0/0. If -S is specified, -P must also be specified. The optional mask is specified as a network mask or as the number of 1s on the left of the network mask (e.g., a mask of 24 is equivalent to 255.255.255.0). The mask defaults to 32. One or more values of port may optionally be specified, indicating what ports or ICMP types the rule applies to. The default is all. Ports may be specified by their /etc/ services entry. The syntax for indicating a range of ports is:

lowport:highport

For example:

-S 172.29.16.1/24 ftp:ftp-data

-V address

The address of the network interface the packet is received from (if category is -I) or is being sent to (if category is -O). address can be a hostname or an IP address, and defaults to 0.0.0.0, which matches any interface address. -V is required with the -c command:

     -V 172.29.16.1
-W name

Identical to -V but takes a device name instead of its address:

     -W ppp0

Options

-b

Bidirectional mode. The rule matches IP packets in both directions. This option is valid only with the -a, -i, and -d commands.

-e

Extended output. Used with the -l command to also show the interface address and any rule options. When listing firewall rules, also shows the packet and byte counters and the TOS (Type of Service) masks. When used with -M, also shows information related to delta sequence numbers.

-k

Match TCP acknowledgment packets (i.e., only TCP packets with the ACK bit set). This option is ignored for all other protocols and is valid only with the -a, -i, and -d commands.

-m

Accept masquerade packets for forwarding, making them appear to have originated from the local host. Recognizes reverse packets and automatically demasquerades them, bypassing the forwarding firewall. This option is valid only in forwarding firewall rules with policy accept. The kernel must have been compiled with CONFIG_IP_MASQUERADE defined.

-n

Numeric output. Print IP addresses and port numbers in numeric format.

-o

Log packets that match this rule to the kernel log. This option is valid only with the -a, -i, and -d commands. The kernel must have been compiled with CONFIG_IP_FIREWALL_VERBOSE defined.

-r [port]

Redirect packets to a local socket, even if they were sent to a remote host. If port is 0 (the default), the packet's destination port is used. This option is valid only in input firewall rules with policy accept. The kernel must have been compiled with CONFIG_IP_TRANSPARENT_ PROXY defined.

-t andmask xormask

Specify masks used for modifying the TOS field in the IP header. When a packet is accepted (with or without masquerading) by a firewall rule, its TOS field is bitwise ANDed with andmask, and the result is bitwise XORed with xormask. The masks are specified as 8-bit hexadecimal values. This option is valid only with the -a, -i, and -d commands and has no effect when used with accounting rules or with firewall rules for rejecting or denying a packet.

-v

Verbose output. Print detailed information about the rule or packet to be added, deleted, or checked. This option is valid only with the -a, -i, -d, and -c commands.

-x

Expand numbers. Display the exact value of the packet and byte counters, instead of a rounded value. This option is valid only when the counters are being listed anyway (see also the -e option).

-y

Match TCP packets with the SYN bit set and the ACK bit cleared. This option is ignored for packets of other protocols and is valid only with the -a, -i, and -d commands.

iptables

iptables command [options]

System administration command. Configure netfilter filtering rules. In the 2.4 kernel, the ipchains firewall capabilities are replaced with the netfilter kernel module. netfilter can be configured to work just like ipchains, but it also comes with the module iptables, which is similar to ipchains but extensible. iptables rules consist of some matching criteria and a target, a result to be applied if the packet matches the criteria. The rules are organized into chains. You can use these rules to build a firewall, masquerade your local area network, or just reject certain kinds of network connections.

There are three built-in tables for iptables, one for network filtering (filter), one for Network Address Translation (nat), and the last for specialized packet alterations (mangle). Firewall rules are organized into chains, ordered check lists of rules that the kernel works through looking for matches. The filter table has three built-in chains: INPUT, OUTPUT, and FORWARD. The INPUT and OUTPUT chains handle packets originating from or destined for the host system. The FORWARD chain handles mail just passing through the host system. The nat table also has three built-in chains: PREROUTING, POSTROUTING, and OUTPUT. mangle has only two chains: PREROUTING and OUTPUT.

netfilter checks packets entering the system. After applying any PREROUTING rules it passes them to the INPUT chain or to the FORWARD chain if the packet is just passing through. Upon leaving, the system packets are passed to the OUTPUT chain and then on to any POSTROUTING rules. Each of these chains has a default target, a policy, in case no match is found. User-defined chains can also be created and used as targets for packets but do not have default policies. If no match can be found in a user-defined chain, the packet is returned to the chain from which it was called and tested against the next rule in that chain.

iptables only changes the rules in the running kernel. When the system is powered off, all changes are lost. You can use the iptables-save command to make a script you can run with iptables-restore to restore your firewall settings. Such a script is often called at bootup. Many distributions will have an iptables initialization script that uses the output from iptables-save.

Commands

iptables is always invoked with one of the following commands:

-A chain rules, --append chain rules

Append new rules to chain.

-I chain number rules, --insert chain number rules

Insert rules into chain at the ordinal position given by number.

-D chain rules, --delete chain rules

Delete rules from chain. Rules can be specified by their ordinal number in the chain as well as by a general rule description.

-R chain number rule, --replace chain number rule

Replace a rule in chain. The rule to be replaced is specified by its ordinal number.

-C chain rule, --check chain rules

Check how chain will handle a network packet that matches the given rule. The rule must describe the source, destination, protocol, and interface of the packet to be constructed.

-L [chain], --list $PARAMETER

List the rules in chain or all chains if chain is not specified.

-F [chain], --flush chain

Remove all rules from chain or from all chains if chain is not specified.

-Z [chain], --zero chain

Zero the packet and byte counters in chain. If no chain is specified, all chains will be reset. When used without specifying a chain and combined with the -L command, it lists the current counter values before they are reset chain.

-N chain, --new-chain chain

Create a new chain. The chain's name must be unique. This is how user-defined chains are created.

-X [chain], --delete-chain chain

Delete the specified user-defined chain or all user-defined chains if no chain is specified.

-P chain target, --policy chain target

Set the default policy for a built-in chain; the target itself cannot be a chain.

-E old-chain new-chain, --rename-chain old-chain new-chain

Rename old-chain to new-chain.

-h [icmp]

Print a brief help message. If the option icmp is given, print a list of valid ICMP types.

Targets

A target may be the name of a chain or one of the following special values.

ACCEPT

Let the packet through.

DROP

Drop the packet.

QUEUE

Send packets to the user space for processing.

RETURN

Stop traversing the current chain and return to the point in the previous chain from which this one was called. If RETURN is the target of a rule in a built-in chain, the built-in chain's default policy is applied.

Rule specification parameters

These options are used to create rules for use with the preceding commands. Rules consist of some matching criteria and usually a target to jump to (-j) if the match is made. Many of the parameters for these matching rules can be expressed as a negative with an exclamation point (!) meaning "not." Those rules will match everything except the given parameter.

-p [!] name, --protocol [!]$PARAMETER

Match packets of protocol name. The value of name can be given as a name or number as found in the file /etc/protocols. The most common values are tcp, udp, icmp, or the special value all. The number 0 is equivalent to all and this is the default value when this option is not used. If there are extended matching rules associated with the specified protocol, they will be loaded automatically. You need not use the -m option to load them.

-s [!] address[/mask] [!] [port], --source [!] address[/mask] [!] [port]

Match packets with the source address. The address may be supplied as a hostname, a network name, or an IP address. The optional mask is the netmask to use and may be supplied either in the traditional form (e.g., /255.255.255.0) or in the modern form (e.g., /24).

-d [!] address[/mask] [!] [port], --destination [!] address[/mask] [port]

Match packets from the destination address. See the description of -s for the syntax of this option.

-j target, --jump target

Jump to a special target or a user-defined chain. If this option is not specified for a rule, matching the rule only increases the rule's counters, and the packet is tested against the next rule.

-i [!] name[+], --in-interface name[+]

Match packets being received from interface name. name is the network interface used by your system (e.g., eth0 or ppp0). A + can be used as a wildcard, so ppp+ would match any interface name beginning with ppp

-o [!] name[+], --out-interface name[+]

Match packets being sent from interface name. See the description of -i for the syntax for name.

[!] -f, [!]--fragment $PARAMETER

The rule applies only to the second or further fragments of a fragmented packet.

Options

-v, --verbose

Verbose mode.

-n, --numeric

Print all IP address and port numbers in numeric form. By default, text names are displayed when possible.

-x, --exact

Expand all numbers in a listing (-L). Display the exact value of the packet and byte counters instead of rounded figures.

-m module, --match

Explicitly load matching rule extensions associated with module. See the following section, "Match Extensions."

-h [icmp], --help [icmp]

Print help message. If icmp is specified, a list of valid ICMP type names will be printed. -h can also be used with the -m option to get help on an extension module.

--line-numbers

Used with the -L command. Add the line number to the beginning of each rule in a listing, indicating its position in the chain.

Match extensions

Several kernel modules come with netfilter to extend matching capabilities of rules. Those associated with particular protocols are loaded automatically when the -p option is used to specify the protocol. Others need to be loaded explicitly with the -m option.

tcp

Loaded when -p tcp is the only protocol specified.

--source-port [!] [port][:port], --sport [!] [port][:port]

Match the specified source ports. Using the colon specifies an inclusive range of services to match. If the first port is omitted, 0 is the default. If the second port is omitted, 65535 is the default. You can also use a dash instead of a colon to specify the range.

--destination-port [!] [port][:port], --dport [!] [port][:port]

Match the specified destination ports. The syntax is the same as for --source-port.

--tcp-flags [!] mask comp

Match the packets with the TCP flags specified by mask and comp. mask is a comma-separated list of flags that should be examined. comp is a comma-separated list of flags that must be set for the rule to match. Valid flags are SYN, ACK, FIN, RST, URG, PSH, ALL, and NONE.

[!] --syn

Match packets with the SYN bit set and the ACK and FIN bits cleared. These are packets that request TCP connections; blocking them prevents incoming connections. Shorthand for --tcp-flags SYN,RST,ACK SYN.

udp

Loaded when -p udp is the only protocol specified.

--source-port [!] [port][:port], --sport [!] [port][:port]

Match the specified source ports. The syntax is the same as for the --source-port option of the TCP extension.

--destination-port [!] [port][:port], --dport [!] [port][:port]

Match the specified destination ports. The syntax is the same as for --source-port option of the TCP extension.

icmp

Loaded when -p icmp is the only protocol specified.

--icmp-type [!] type

Match the specified icmp type. type may be a numeric ICMP type or one of the ICMP type names shown by the command iptables -p icmp -h.

mac

Loaded explicitly with the -m option.

--mac-source [!] address

Match the source address that transmitted the packet. address must be given in colon-separated hexbyte notation (for example, --mac-source 00:60:08:91:CC:B7.

limit

Loaded explicitly with the -m option. The limit extensions are used to limit the number of packets matched. This is useful when combined with the LOG target. Rules using this extension match until the specified limit is reached.

--limit rate

Match addresses at the given rate. rate is specified as a number with an optional /second, /minute, hour, or /day suffix. When this option is not set, the default is '3/hour'.

--limit-burst [number]

Set the maximum number of packets to match in a burst. Once the number has been reached, no more packets are matched for this rule until the number has recharged. It recharges at the rate set by the --limit option. When not specified, the default is 5.

multiport

Loaded explicitly with the -m option. The multiport extensions match sets of source or destination ports. These rules can be used only in conjunction with -p tcp and -p udp. Up to 15 ports can be specified in a comma-separated list.

--source-port [ports]

Match the given source ports.

--destination-port [ports]

Match the given destination ports.

--port [ports]

Match if the packet has the same source and destination port and that port is one of the given ports.

mark

Loaded explicitly with the -m option. This module works with the MARK extension target:

--mark value[/mask]

Match the given unsigned mark value. If a mask is specified, it is logically ANDed with the mark before comparison.

owner

Loaded explicitly with the -m option. The owner extensions match a local packet's creator's user, group process, and session IDs. This makes sense only as a part of the OUTPUT chain.

--uid-owner userid

Match packets created by a process owned by userid.

--gid-owner groupid

Match packets created by a process owned by groupid.

--pid-owner processid

Match packets created by process ID processid.

--sid-owner sessionid

Match packets created by a process in the session sessionid.

state

Loaded explicitly with the -m option. This module matches the connection state of a packet.

--state states

Match the packet if it has one of the states in the comma-separated list states. Valid states are INVALID, ESTABLISHED, NEW, and RELATED.

tos

Loaded explicitly with the -m option. This module matches the Type of Service field in a packet's header.

--tos value

Match the packet if it has a TOS of value. value can be a numeric value or a Type of Service name. iptables -m tos -h will give you a list of valid TOS values.

Target extensions

Extension targets are optional additional targets supported by separate kernel modules. They have their own associated options.

LOG

Log the packet's information in the system log.

--log-level level

Set the syslog level by name or number (as defined by syslog.conf).

--log-prefix prefix

Begin each log entry with the string prefix. The prefix string may be up to 30 characters long.

--log-tcp-sequence

Log the TCP sequence numbers. This is a security risk if your log is readable by users.

--log-tcp-options

Log options from the TCP packet header.

--log-ip-options

Log options from the IP packet header.

MARK

Used to mark packets with an unsigned integer value you can use later with the mark matching extension. Valid only with the mangle table.

--set-mark value

Mark the packet with value.

REJECT

Drop the packet and, if appropriate, send an ICMP message back to the sender indicating the packet was dropped. If the packet was an ICMP error message, an unknown ICMP type, or a nonhead fragment, or if too many ICMP messages have already been sent to this address, no message is sent.

--reject-with type

Send the specified ICMP message type. Valid values are icmp-net-unreachable, icmp-host- unreachable, icmp-port-unreachable, or icmp-proto-unreachable. If the packet was an ICMP ping packet, type may also be echo-reply.

TOS

Set the Type of Service field in the IP header. TOS is a valid target only for rules in the mangle table.

--set-tos value

Set the TOS field to value. You can specify this as an 8-bit value or as a TOS name. You can get a list of valid names using iptables -j TOS -h.

SNAT

Modify the source address of the packet and all future packets in the current connection. SNAT is valid only as a part of the POSTROUTING chain in the nat table.

--to-source address[-address][port-port]

Specify the new source address or range of addresses. If a tcp or udp protocol has been specified with the -p option, source ports may also be specified. If none is specified, map the new source to the same port if possible. If not, map ports below 512 to other ports below 512, those between 512 and 1024 to other ports below 1024, and ports above 1024 to other ports above 1024.

DNAT

Modify the destination address of the packet and all future packets in the current connection. DNAT is valid only as a part of the POSTROUTING chain in the nat table.

--to-destination address[-address][port-port]

Specify the new destination address or range of addresses. The arguments for this option are the same as the --to-source argument for the SNAT extension target.

MASQUERADE

Masquerade the packet so it appears that it originated from the current system. Reverse packets from masqueraded connections are unmasqueraded automatically. This is a legal target only for chains in the nat table that handle incoming packets and should be used only with dynamic IP addresses (like dial-up.) For static addresses use DNAT.

--to-ports port[-port]

Specify the port or range of ports to use when masquerading. This option is only valid if a tcp or udp protocol has been specified with the -p option. If this option is not used, the masqueraded packet's port will not be changed.

REDIRECT [--to-port port]

Redirect the packet to a local port. This is useful for creating transparent proxies.

--to-ports port[-port]

Specify the port or range of ports on the local system to which the packet should be redirected. This option is valid only if a tcp or udp protocol has been specified with the -p option. If this option is not used, the redirected packet's port will not be changed.

iptables-restore

iptables-restore [file]

System administration command. Restore firewall rules. iptables-restore takes commands generated by iptables-save and uses them to restore the firewall rules for each chain. Often used by initialization scripts to restore firewall settings on boot. file is the name of a file whose contents were generated by iptables-save. If not specified, the command takes its input from stdin. This command was not completed at the time this book went to print. There may be options not listed here.

iptables-save

iptables-save [chain]

System administration command. Print the IP firewall rules currently stored in the kernel to stdout. If no chain is given, all chains will be printed. Output may be redirected to a file that can later be used by iptables-restore to restore the firewall. This command was not completed at the time this book went to print. There may be options not listed here.

ispell

ispell [options] [files]