Unix in a Nutshell, Fourth Edition
< Day Day Up > |
Examples to be entered as a command line are shown with the $ prompt. Otherwise, examples should be treated as code fragments that might be included in a shell script. For convenience, some of the reserved words used by multiline commands are also included.
! pipeline
Not ksh88. Negate the sense of a pipeline. Returns an exit status of 0 if the pipeline exited nonzero, and an exit status of 1 if the pipeline exited zero. Typically used in if and while statements. Example
This code prints a message if user jane is not logged on: if ! who | grep jane > /dev/null then echo jane is not currently logged on fi
# Ignore all text that follows on the same line. # is used in shell scripts as the comment character and is not really a command.
#!shell [option]
Used as the first line of a script to invoke the named shell. Anything given on the rest of the line is passed as a single argument to the named shell. This feature is typically implemented by the kernel, but may not be supported on some older systems. Some systems have a limit of around 32 characters on the maximum length of shell. For example: #!/bin/sh
: Null command. Returns an exit status of 0. See this Example and the ones under case. The line is still processed for side effects, such as variable and command substitutions, or I/O redirection. Example
Check whether someone is logged in: if who | grep $1 > /dev/null then : # Do nothing if user is found else echo "User $1 is not logged in" fi
. file [arguments]
Read and execute lines in file. file does not have to be executable but must reside in a directory searched by PATH. The arguments are stored in the positional parameters. If Bash is not in POSIX mode and file is not found in PATH, Bash will look in the current directory for file.
[[ expression ]]
Same as test expression or [ expression ], except that [[ ]] allows additional operators. Word splitting and filename expansion are disabled. Note that the brackets ([ ]) are typed literally, and that they must be surrounded by whitespace. Additional Operators
name ( ) { commands; } Define name as a function. POSIX syntax. The function definition can be written on one line or across many. Bash and the Korn shell provide the function keyword, alternate forms that work similarly. See the earlier section "Functions." Example
$ count ( ) { > ls | wc -l > }
When issued at the command line, count now displays the number of files in the current directory.
alias [options] [name[='cmd']]
Assign a shorthand name as a synonym for cmd. If ='cmd' is omitted, print the alias for name; if name is also omitted, print all aliases. If the alias value contains a trailing space, the next word on the command line also becomes a candidate for alias expansion. See also unalias. These aliases are built into ksh88. Some use names of existing Bourne shell or C shell commands. autoload='typeset -fu' false='let 0' functions='typeset -f' hash='alias -t' history='fc -l' integer='typeset -i' nohup='nohup ' r='fc -e -' true=':' type='whence -v' The following aliases are built into ksh93: autoload='typeset -fu' command='command ' fc='hist' float='typeset -E' functions='typeset -f' hash='alias -t --' history='hist -l' integer='typeset -i' nameref='typeset -n' nohup='nohup ' r='hist -s' redirect='command exec' stop='kill -s STOP' times='{ {time;} 2>&1;}' type='whence -v' Options
Example
alias dir='echo ${PWD##*/}'
autoload [functions] Korn shell alias for typeset -fu. Load (define) the functions only when they are first used.
bind [-m map] [options] bind [-m map] [-q function] [-r sequence] [-u function] bind [-m map] -f file bind [-m map] -x sequence:command bind [-m map] sequence:function bind readline-command Bash only. Manage the readline library. Non-option arguments have the same form as in a .inputrc file. Options
bg [jobIDs]
Put current job or jobIDs in the background. See the earlier section "Job Control."
break [n] Exit from a for, while, select, or until loop (or break out of n loops).
builtin command [ arguments ... ] Bash version. Run the shell built-in command command with the given arguments. This allows you to bypass any functions that redefine a built-in command's name. The command command is more portable. Example
This function lets you do your own tasks when you change directory: cd ( ) { builtin cd "$@" Actually change directory pwd Report location }
builtin [ -ds ] [ -f library ] [ name ... ] ksh93 version. This command allows you to load new built-in commands into the shell at runtime from shared library files. If no arguments are given, builtin prints all the built-in command names. With arguments, builtin adds each name as a new built-in command (like cd or pwd). If the name contains a slash, the newly-added built-in version is used only if a path search would otherwise have found a command of the same name. (This allows replacement of system commands with faster, built-in versions.) Otherwise, the built-in command is always found. Options
caller [expression] Bash only. Print the line number and source filename of the current function call or dot file. With nonzero expression, prints that element from the call stack. The most recent is zero. This command is for use by the Bash debugger.
case value in pattern1) cmds1;; pattern2) cmds2;; . . . esac
Execute the first set of commands (cmds1) if value matches pattern1, execute the second set of commands (cmds2) if value matches pattern2, etc. Be sure the last command in each set ends with ;;. value is typically a positional parameter or other shell variable. cmds are typically Unix commands, shell programming commands, or variable assignments. Patterns can use file-generation metacharacters. Multiple patterns (separated by |) can be specified on the same line; in this case, the associated cmds are executed whenever value matches any of these patterns. See the Examples here and under eval. The shells allow pattern to be preceded by an optional open parenthesis, as in (pattern). In Bash and ksh88, it's necessary for balancing parentheses inside a $( ) construct. The Korn shell allows a case to end with ;& instead of ;;. In such cases control "falls through" to the group of statements for the next pattern. Examples
Check first command-line argument and take appropriate action: case $1 in # Match the first arg no|yes) response=1;; -[tT]) table=TRUE;; *) echo "unknown option"; exit 1;; esac Read user-supplied lines until user exits: while : # Null command; always true do printf "Type . to finish ==> " read line case "$line" in .) echo "Message done" break ;; *) echo "$line" >> $message ;; esac done
cd [-LP] [dir] cd [-LP] [-] cd [-LP] [old new] With no arguments, change to home directory of user. Otherwise, change working directory to dir. If dir is a relative pathname but is not in the current directory, the CDPATH variable is searched. A directory of - stands for the previous directory. The last syntax is specific to the Korn shell. It modifies the current directory name by replacing string old with new and then switches to the resulting directory. Options
Example
$ pwd /var/spool/cron $ cd cron uucp Ksh: cd prints the new directory /var/spool/uucp
command [-pvV] name [arg ...] Not ksh88. Without -v or -V, execute name with given arguments. This command bypasses any aliases or functions that may be defined for name. When used with a special built-in, prevents the built-in from exiting the script if it fails. Options
Example
Create an alias for rm that will get the system's version, and run it with the -i option: $ alias 'rm=command -p rm -i'
compgen [options] [string]
Bash only. Generate possible completions for string according to the options. Options are those accepted by complete, except for -p and -r. For more information, see the entry for complete.
complete [options] command ... Bash only. Specifies the way to complete arguments for each command. This is discussed in the section "Programmable Completion (Bash Only)," earlier in the chapter. Options
continue [n] Skip remaining commands in a for, while, select, or until loop, resuming with the next iteration of the loop (or skipping n loops).
declare [options] [name[=value]]
Bash only. Declare variables and manage their attributes. In function bodies, variables are local, as if declared with the local command. Options
With a + instead of a -, the given attribute is disabled. With no variable names, all variables having the given attribute(s) are printed in a form that can be reread as input to the shell. Examples
$ declare -i val Make val an integer $ val=4+7 Evaluate value $ echo $val Show result 11 $ declare -r z=42 Make z readonly $ z=31 Try to assign to it bash: z: readonly variable Assignment fails $ echo $z 42 $ declare -p val z Show attributes and values declare -i val="11" declare -r z="42"
dirs [-clpv] [+n] [-n]
Bash only. Print the directory stack, which is managed with pushd and popd. Options
disown [-ahr] [job ...]
Bash version. Removes jobs from the list of jobs managed by Bash. Options
disown [job ...]
ksh93 version. When a login shell exits, do not send a SIGHUP to the given jobs. If no jobs are listed, no background jobs will receive SIGHUP.
do Reserved word that precedes the command sequence in a for, while, until, or select statement.
done
Reserved word that ends a for, while, until, or select statement.
echo [-eEn] [string]
Bash version, built-in to the shell. Write string to standard output. (See also echo in Chapter 2.) Options
Examples
$ echo "testing printer" | lp $ echo "Warning: ringing bell \a"
echo [-n] [string]
Korn shell version. Write string to standard output; if -n is specified, the output is not terminated by a newline. If no string is supplied, echo a newline. The Korn shell's echo, even though it is built-in to the shell, emulates the system's version of echo. Thus, if the version found by a path search supports -n, the built-in version does too. Similarly, if the external version supports the escape sequences described below, the built-in version does too; otherwise it does not.[*] (See also echo in Chapter 2.) echo understands special escape characters, which must be quoted (or escaped with a \) to prevent interpretation by the shell: [*] The situation with echo is a mess; consider using printf instead.
enable [-adnps] [-f file] [command ...] Bash only. Enable or disable shell built-in commands. Disabling a built-in lets you use an external version of a command that would otherwise use a built-in version, such as echo or test. Options
esac Reserved word that ends a case statement.
eval args
Typically, eval is used in shell scripts, and args is a line of code that contains shell variables. eval forces variable expansion to happen first and then runs the resulting command. This "double-scanning" is useful any time shell variables contain input/output redirection symbols, aliases, or other shell variables. (For example, redirection normally happens before variable expansion, so a variable containing redirection symbols must be expanded first using eval; otherwise, the redirection symbols remain uninterpreted.) See the C shell eval entry (Chapter 5 ) for another example. Example
This fragment of a shell script shows how eval constructs a command that is interpreted in the right order: for option do case "$option" in Define where output goes save) out=' > $newfile' ;; show) out=' | more' ;; esac done eval sort $file $out
exec [command args ...] exec [-a name] [-cl] [command args ... ]
Execute command in place of the current process (instead of creating a new process). exec is also useful for opening, closing, or copying file descriptors. The second form is for ksh93 and Bash. Options
Examples
trap 'exec 2>&-' 0 Close standard error when shell script exits (signal 0) $ exec /bin/csh Replace shell with C shell $ exec < infile Reassign standard input to infile
exit [n]
Exit a shell script with status n (e.g., exit 1). n can be 0 (success) or nonzero (failure). If n is not given, the shell's exit status is that of the most recent command. exit can be issued at the command line to close a window (log out). Exit statuses can range in value from 0 to 255. Example
if [ $# -eq 0 ] then echo "Usage: $0 [-c] [-d] file(s)" 1>&2 exit 1 # Error status fi
export [variables] export [name=[value] ...] export -p export [-fn] [name=[value] ...] Pass (export) the value of one or more shell variables, giving global meaning to the variables (which are local by default). For example, a variable defined in one shell script must be exported if its value is used in other programs called by the script. If no variables are given, export lists the variables exported by the current shell. The second form is the POSIX version, which is similar to the first form except that you can set a variable name to a value before exporting it. The third form is not available in ksh88. The fourth form is specific to Bash. Options
Examples
In the original Bourne shell, you would type: TERM=vt100 export TERM
In Bash and the Korn shell, you could type this instead: export TERM=vt100
false ksh88 alias for let 0. Built-in command in Bash and ksh93 that exits with a false return value.
fc [options] [first [last]] fc -e - [old=new] [command] fc -s [old=new] [command]
ksh88 and Bash. Display or edit commands in the history list. (Use only one of -e, -l or -s.) first and last are numbers or strings specifying the range of commands to display or edit. If last is omitted, fc applies to a single command (specified by first). If both first and last are omitted, fc edits the previous command or lists the last 16. The second form of fc takes a history command, replaces old with new, and executes the modified command. If no strings are specified, command is just reexecuted. If no command is given either, the previous command is reexecuted. command is a number or string like first. See the examples in the earlier section "Command History." The third form, available in Bash and ksh93, is equivalent to the second form. Options
fc ksh93 alias for hist.
fg [jobIDs]
Bring current job or jobIDs to the foreground. See the earlier section "Job Control."
fi Reserved word that ends an if statement. (Don't forget to use it!)
for x [in list]do commands done For variable x (in optional list of values) do commands. If in list is omitted, "$@" (the positional parameters) is assumed. Examples
Paginate files specified on the command line; save each result: for file; do pr $file > $file.tmp done
Same, but put entire loop into the background: for file; do pr $file > $file.tmp done &
Search chapters for a list of words (like fgrep -f): for item in 'cat program_list' do echo "Checking chapters for" echo "references to program $item..." grep -c "$item.[co]" chap* done
Extract a one-word title from each file and use as new filename: for file do name='sed -n 's/NAME: //p' $file' mv $file $name done
for ((init; cond; incr)) do commands done Bash and ksh93 . Arithmetic for loop, similar to C's. Evaluate init. While cond is true, execute the body of the loop. Evaluate incr before retesting cond. Any one of the expressions may be omitted; a missing cond is treated as being true. Example
Search for a phrase in each odd chapter: for ((x=1; x <= 20; x += 2)) do grep $1 chap$x done
function name { commands; } function name ( ) { commands; }
Define name as a shell function. See the description of semantic issues in the earlier section "Functions." The first form is for the Korn shell, although it may also be used with Bash. The second form is specific to Bash. Bash does not give different semantics to functions declared differently; all Bash functions behave the same way. Example
Define a function to count files. $ function fcount { > ls | wc -l > }
functions
Korn shell alias for typeset -f. (Note the "s" in the name; function is a Korn shell keyword.) See typeset later in this listing.
getconf [name [path]]
ksh93 only. Retrieve the values for parameters that can vary across systems. name is the parameter to retrieve; path is a filename to test for parameters that can vary on different filesystem types. The parameters are defined by the POSIX 1003.1 standard. See the entry for getconf in Chapter 2. Example
Print the maximum value that can be held in a C int. $ getconf INT_MAX 2147483647
getopts [-a name] string name [args]
Process command-line arguments (or args, if specified) and check for legal options. getopts is used in shell script loops and is intended to ensure standard syntax for command-line options. Standard syntax dictates that command-line options begin with a -. Options can be stacked; i.e., consecutive letters can follow a single -. End processing of options by specifying -- on the command line. string contains the option letters to be recognized by getopts when running the shell script. Valid options are processed in turn and stored in the shell variable name. If an option is followed by a colon, the option must be followed by one or more arguments. (Multiple arguments must be given to the command as one shell word. This is done by quoting the arguments or separating them with commas. The application must be written to expect multiple arguments in this format.) getopts uses the shell variables OPTARG and OPTIND. The Bash version also uses OPTERR. Option
hash [-dlrt] [-p file] [commands]
Bash version. As the shell finds commands along the search path ($PATH), it remembers the found location in an internal hash table. The next time you enter a command, the shell uses the value stored in its hash table. With no arguments, hash lists the current hashed commands. The display shows hits (the number of times the command has been called by the shell) and the command name. With commands, the shell adds those commands to the hash table. Options
Besides the -r option, the hash table is also cleared when PATH is assigned. Use PATH=$PATH to clear the hash table without affecting your search path. This is most useful if you have installed a new version of a command in a directory that is earlier in $PATH than the current version of the command.
hash
Korn shell alias for alias -t (alias -t -- in ksh93). Approximates the Bourne shell's hash.
help [-s] [pattern] Bash only. Print usage information on standard output for each command that matches pattern. The information includes descriptions of each command's options. With the -s option, print only brief usage information. Examples
$ help -s cd Short help cd: cd [-L|-P] [dir] $ help true Full help true: true Return a successful result.
hist [options] [first [last]] hist -s [old=new] [command]
ksh93 only. Display or edit commands in the history list. (Use only one of -l or -s.) first and last are numbers or strings specifying the range of commands to display or edit. If last is omitted, hist applies to a single command (specified by first). If both first and last are omitted, hist edits the previous command or lists the last 16. The second form of hist takes a history command, replaces old with new, and executes the modified command. If no strings are specified, command is just reexecuted. If no command is given either, the previous command is reexecuted. command is a number or string like first. See the examples in the earlier section "Command History." Options
history [count] history [options]
Bash version. Print commands in the history list or manage the history file. With no options or arguments, display the history list with command numbers. With a count argument, print only that many of the most recent commands. Options
history ksh88 alias for fc -l. ksh93 alias for hist -l. Show the last 16 commands.
if condition1 then commands1 [ elif condition2 then commands2 ] . . . [ else commands3 ] fi If condition1 is met, do commands1; otherwise, if condition2 is met, do commands2; if neither is met, do commands3. Conditions are often specified with the test and [[ ]] commands. See test and [[]] for a full list of conditions, and see additional Examples under : and exit. Examples
Insert a 0 before numbers less than 10: if [ $counter -lt 10 ] then number=0$counter else number=$counter fi Make a directory if it doesn't exist: if [ ! -d $dir ]; then mkdir $dir chmod 775 $dir fi
integer Korn shell alias for typeset -i. Specify integer variables.
jobs [options] [jobIDs] List all running or stopped jobs, or list those specified by jobIDs. For example, you can check whether a long compilation or text format is still running. Also useful before logging out. See the earlier section "Job Control." Options
kill [options] IDs Terminate each specified process ID or job ID. You must own the process or be a privileged user. This built-in is similar to the external kill command described in Chapter 2 but also allows symbolic job names. See the kill entry in Chapter 2 for a list of commonly available signals and for the header files where the corresponding signal numbers may be found. Stubborn processes can be killed using signal 9. See the earlier section "Job Control." Options
let expressions or ((expressions))
Perform arithmetic as specified by one or more expressions. expressions consist of numbers, operators, and shell variables (which don't need a preceding $). Expressions must be quoted if they contain spaces or other special characters. The (( )) form does the quoting for you. For more information and examples, see the section "Arithmetic Expressions," earlier in this chapter. See also expr in Chapter 2. Examples
Each of these examples adds 1 to variable i: i='expr $i + 1' All Bourne shells let i=i+1 Bash , ksh let "i = i + 1" (( i = i + 1 )) (( i += 1 )) (( i++ )) Bash, ksh93
local [options] [name[=value]] Bash only. Declares local variables for use inside functions. The options are the same as those accepted by declare; see declare for the full list. It is an error to use local outside a function body.
login [user] Korn shell only. The shell does an execve(2) of the standard login program, allowing you to replace one login session with another, without having to logout first.
logout Bash only. Exit a login shell. The command fails if the current shell is not a login shell.
nameref newvar=oldvar ...
ksh93 alias for typeset -n. See the discussion of indirect variables in the section "Variables," earlier in this chapter.
nohup command [arguments] &
Don't terminate a command after logout . nohup is a Korn shell alias: nohup='nohup '
The embedded space at the end lets the shell interpret the following command as an alias, if needed.
popd [-n] [+count] [-count]
Bash only. Pop the top directory off the directory stack (as shown by the dirs command), and change to the new top directory, or manage the directory stack. Options
print [options] [string ...]
Korn shell only. Display string (on standard output by default). print includes the functions of echo and can be used in its place on most Unix systems. Options
printf format [val ...]
Not ksh88. Formatted printing, like the ANSI C printf function. Additional Format Letters
Both Bash and ksh93 accept additional format letters. Bash only provides %b and %q, while ksh93 provides all those in the following list.
Examples
$ date Reformat date/time Tue Sep 7 15:39:42 EDT 2004 $ printf "%(It is now %m/%d/%Y %H:%M:%S)T\n" "$(date)" It is now 09/07/2004 15:40:10 $ printf "%H\n" "Here is a <string>" Convert to HTML Here is a <string>
pwd [-LP]
Print your present working directory on standard output. Options
Options give control over the use of logical versus physical treatment of the printed path. See also the entry for cd, earlier in this section.
pushd [-n] [directory] pushd [-n] [+count] [-count] Bash only. Add directory to the directory stack, or rotate the directory stack. With no arguments, swap the top two entries on the stack, and change to the new top entry. Options
r
ksh88 alias for fc -e -. ksh93 alias for hist -s. Reexecute previous command.
read [options] [variable1[?string]] [variable2 ...]
Read one line of standard input and assign each word to the corresponding variable, with all leftover words assigned to the last variable. If only one variable is specified, the entire line is assigned to that variable. See the Examples here and under case. The return status is 0 unless EOF is reached. Both Bash and the Korn shell support options, as shown below. If no variables are given, input is stored in the REPLY variable. Additionally, the Korn shell version supports the ? syntax for prompting. If the first variable is followed by ?string, string is displayed as a user prompt. Options
Examples
Read three variables: $ read first last address Sarah Caldwell 123 Main Street $ echo "$last, $first\n$address" Caldwell, Sarah 123 Main Street Prompt yourself to enter two temperatures, Korn shell version: $ read n1?"High low: " n2 High low: 65 33
readonly [-afp] [variable[=value] ...]
Prevent the specified shell variables from being assigned new values. An initial value may be supplied using the assignment syntax, but that value may not be changed subsequently. Options
ksh88 does not accept options for this command.
redirect i/o-redirection ... ksh93 alias for command exec. Example
Change the shell's standard error to the console: $ redirect 2>/dev/console
return [n] Use inside a function definition. Exit the function with status n or with the exit status of the previously executed command.
select x [in list] do commands done
Display a list of menu items on standard error, numbered in the order they are specified in list. If no in list is given, items are taken from the command line (via "$@"). Following the menu is a prompt string (set by PS3). At the PS3 prompt, users select a menu item by typing its number, or they redisplay the menu by pressing the ENTER key. User input is stored in the shell variable REPLY. If a valid item number is typed, commands are executed. Typing EOF terminates the loop. Example
PS3="Select the item number: " select event in Format Page View Exit do case "$event" in Format) nroff $file | lp;; Page) pr $file | lp;; View) more $file;; Exit) exit 0;; * ) echo "Invalid selection";; esac done
The output of this script looks like this: 1. Format 2. Page 3. View 4. Exit Select the item number:
set [options arg1 arg2 ...] With no arguments, set prints the values of all variables known to the current shell. Options can be enabled (-option) or disabled (+option). Options can also be set when the shell is invoked. (See the earlier section "Invoking the Shell.") Arguments are assigned in order to $1, $2, etc. Options
There is a large set of overlapping options amongst ksh88, ksh93, and Bash. To minimize confusion, the following list includes every option. The table provided after the list summarizes which options are available in which shells.
Option Availability Summary
Examples
set -- "$num" -20 -30 Set $1 to $num, $2 to -20, $3 to -30 set -vx Read each command line; show it; execute it; show it again (with arguments) set +x Stop command tracing set -o noclobber Prevent file overwriting set +o noclobber Allow file overwriting again
shopt [-opqsu] [option] Bash only. Sets or unsets shell options. With no options or just -p, prints the names and settings of the options. Options
Settable Shell Options
The following descriptions describe the behavior when set. Options marked with a dagger (|) are enabled by default.
shift [n] Shift positional arguments (e.g., $2 becomes $1). If n is given, shift to the left n places. Used in while loops to iterate through command-line arguments. In the Korn shell, n can be an integer expression. Examples
shift $1+$6 Korn shell: use expression result as shift count shift $(($1 + $6)) Same, portable to any POSIX shell
sleep [n]
ksh93 only. Sleep for n seconds. n can have a fractional part.
source file [arguments]
Bash only. Identical to the . (dot) command; see that entry.
stop [jobIDs]
ksh88 alias for kill -STOP. ksh93 alias for kill -s STOP. Suspend the background job specified by jobIDs; this is the complement of CTRL-Z or suspend. See the earlier section "Job Control."
suspend [-f] Suspend the current shell. Often used to stop an su command. In ksh88, suspend is an alias for kill -STOP $$. In ksh93, it is an alias for kill -s STOP $$. In Bash, it is a built-in command. Option
test condition or [ condition ] or [[ condition ]] Evaluate a condition and, if its value is true, return a zero exit status; otherwise, return a nonzero exit status. An alternate form of the command uses [ ] rather than the word test. An additional alternate form uses [[ ]], in which case word splitting and pathname expansion are not done. (See the [[]] enTRy.) condition is constructed using the following expressions. Conditions are true if the description holds true. Features that are specific to Bash are marked with a (B). Features that are specific to the Korn shell are marked with a (K). Features that are specific to ksh93 are marked with a (K93). File Conditions
String Conditions
Internal Shell Conditions
Integer Comparisons
Combined Forms
Examples
The following examples show the first line of various statements that might use a test condition: while test $# -gt 0 While there are arguments... while [ -n "$1" ] While there are nonempty arguments... if [ $count -lt 10 ] If $count is less than 10... if [ -d RCS ] If the RCS directory exists... if [ "$answer" != "y" ] If the answer is not y... if [ ! -r "$1" -o ! -f "$1" ] If the first argument is not a readable file or a regular file...
time command time [command]
Execute command and print the total elapsed time, user time, and system time (in seconds). Same as the Unix command time (see Chapter 2), except that the built-in version can also time other built-in commands as well as all commands in a pipeline. The second form applies to ksh93; with no command, the total user and system times for the shell, and all children are printed.
times Print accumulated process times for user and system.
times
ksh93 alias for { {time;} 2>&1;}. See also time.
trap [ [commands] signals] TRap -p trap -l Execute commands if any signals are received. The second form is specific to Bash and ksh93; it prints the current trap settings in a form suitable for rereading later. The third form is specific to Bash; it lists all signals and their numbers, like kill -l. Common signals include EXIT (0), HUP (1), INT (2), and TERM (15). Multiple commands must be quoted as a group and separated by semicolons internally. If commands is the null string (i.e., TRap "" signals), signals are ignored by the shell. If commands are omitted entirely, reset processing of specified signals to the default action. Bash and ksh93: if commands is "-", reset signals to their initial defaults. If both commands and signals are omitted, list current trap assignments. See the Examples here and in exec. Signals
A list of signal names, numbers, and meanings were given earlier, in the kill entry in Chapter 2. The shells allow you to use either the signal number, or the signal name (without the SIG prefix). In addition, the shells support "pseudo-signals," signal names or numbers that aren't real operating system signals but which direct the shell to perform a specific action. These signals are:
Examples
trap "" INT Ignore interrupts (signal 2) trap INT Obey interrupts again
Remove a $tmp file when the shell program exits, or if the user logs out, presses CTRL-C, or does a kill: trap "rm -f $tmp; exit" EXIT HUP INT TERM POSIX style trap "rm -f $tmp; exit" 0 1 2 15 Pre-POSIX Bourne shell style
Print a "clean up" message when the shell program receives signals SIGHUP, SIGINT, or SIGTERM: trap 'echo Interrupt! Cleaning up...' HUP INT TERM
true ksh88 alias for :. Bash and ksh93 built-in command that exits with a true return value.
type [-afpPt] commands
Bash version. Show whether each command name is a Unix command, a built-in command, an alias, a shell keyword, or a defined shell function. Options
Example
$ type mv read if mv is /bin/mv read is a shell builtin if is a shell keyword
type commands
Korn shell alias for whence -v.
typeset [options] [variable[=value ...]] typeset -p
In Bash, identical to declare. See declare. In the Korn shell, assign a type to each variable (along with an optional initial value), or, if no variables are supplied, display all variables of a particular type (as determined by the options). When variables are specified, -option enables the type and +option disables it. With no variables, -option prints variable names and values; +option prints only the names. The second form shown is specific to ksh93. Options
Examples
typeset List name, value, and type of all set variables typeset -x List names and values of exported variables typeset +r PWD End read-only status of PWD typeset -i n1 n2 n3 Three variables are integers typeset -R5 zipcode zipcode is flush right, five characters wide
ulimit [options] [n] Print the value of one or more resource limits, or, if n is specified, set a resource limit to n. Resource limits can be either hard (-H) or soft (-S). By default, ulimit sets both limits or prints the soft limit. The options determine which resource is acted on. Options
umask [nnn] umask [-pS] [mask]
Display file creation mask or set file creation mask to octal value nnn. The file creation mask determines which permission bits are turned off (e.g., umask 002 produces rw-rw-r--). See the entry in Chapter 2 for examples. The second form is not in ksh88. A symbolic mask is permissions to keep. Options
unalias names unalias -a Remove names from the alias list. See also alias. Option
unset [options] names
Erase definitions of functions or variables listed in names. Options
until condition do commandsdone
Until condition is met, do commands. condition is often specified with the test command. See the Examples under case and test.
wait [ID] Pause in execution until all background jobs complete (exit status 0 is returned), or pause until the specified background process ID or job ID completes (exit status of ID is returned). Note that the shell variable $! contains the process ID of the most recent background process. Example
wait $! Wait for most recent background process to finish
whence [options]commands
Korn shell only. Show whether each command name is a Unix command, a built-in command, a defined shell function, or an alias. Options
while conditiondo commands done
While condition is met, do commands. condition is often specified with the test commands. See the Examples under case and test.
filename Read and execute commands from executable file filename, or execute a binary object file. |
< Day Day Up > |