start page | rating of books | rating of authors | reviews | copyrights

Book HomeBook TitleSearch this book

4.9. Built-in Commands (Bourne and Korn Shells)

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

ksh93 only. 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. (Take care when commenting a Bourne shell script. A file that has # as its first character is sometimes interpreted by older systems as a C shell script.)

#!shell#!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. Sometimes used on older systems as the first character in a file to denote a Bourne shell script. See this Example and under case. The line is still processed for side effects, such as variable and command substitutions.

Example

Check whether someone is logged in:

if who | grep $1 > /dev/null
then :	 # Do nothing if pattern 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 Korn shell supports arguments that are stored in the positional parameters.

[[ ]]

[[ expression ]]

Korn shell only. 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

&&

Logical AND of test expressions (short circuit).

||

Logical OR of test expressions (short circuit).

<

First string is lexically “less than” the second.

>

First string is lexically “greater than” the second.

name()name () { commands; }

Define name as a function. Syntax can be written on one line or across many. Since the Bourne shell has no aliasing capability, simple functions can serve as aliases. The Korn shell provides the function keyword, an alternate form that works the same way.

There are semantic differences that should be kept in mind:

  • In the Bourne shell, all functions share traps with the “parent” shell and may not be recursive.

  • In ksh88, all functions have their own traps and local variables, and may be recursive.

  • In ksh93, name () functions share traps with the “parent” shell and may not be recursive.

  • In ksh93, function functions have their own traps and local variables, and may be recursive. Using the . command with a function function gives it Bourne shell semantics.

Example

$ count () {
> ls | wc -l
> }

When issued at the command line, count now displays the number of files in the current directory.

aliasalias [options] [name[='cmd']]

Korn shell only. 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 (which points out the similarities among the shells).

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

-p
Print the word alias before each alias. ksh93 only.

-t
Create a tracked alias for a Unix command name. The Korn shell remembers the full pathname of the command, allowing it to be found more quickly and to be issued from any directory. If no name is supplied, current tracked aliases are listed. Tracked aliases are the similar to hashed commands in the Bourne shell.

-x
Export the alias; it can now be used in shell scripts and other subshells. If no name is supplied, current exported aliases are listed.

Example

alias dir='echo ${PWD##*/}'
autoloadautoload [functions]

Load (define) the functions only when they are first used. Korn shell alias for typeset -fu.

bgbg [jobIDs]

Put current job or jobIDs in the background. See Section 4.6.

breakbreak [n]

Exit from a for while, select, or until loop (or break out of n loops).

builtinbuiltin [ -ds ] [ -f library ] [ name ... ]

ksh93 only. 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

-d
Delete the built-in command name.

-f
Load new built-in command from library.

-s
Only print “special” built-ins (those designated as special by POSIX).

case
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.

Korn Shell Notes

  • The Korn shell allows pattern to be preceded by an optional open parenthesis, as in (pattern). It's useful for balancing parentheses inside a $( ) construct.

  • The Korn shell also 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
   echo "Type . to finish ==> \c"
   read line
   case "$line" in
      .) echo "Message done"
         break ;;
      *) echo "$line" >> $message ;;
   esac
done
cdcd [dir]
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. The last three command forms are specific to the Korn shell, where - stands for the previous directory. The fourth syntax modifies the current directory name by replacing string old with new and then switches to the resulting directory.

Options

-L
Use the logical path (what the user typed, including any symbolic links) for cd .. and the value of PWD. This is the default.

-P
Use the actual filesystem physical path for cd .. and the value of PWD.

Example

$ pwd
/var/spool/cron
$ cd cron uucp	cd prints the new directory
/var/spool/uucp
commandcommand [-pvV] name [arg ...]

ksh93 only. Without -v or -V, execute name with given arguments. This command bypasses any aliases or functions that may be defined for name.

Options

-p
Use a predefined, default search path, not the current value of PATH.

-v
Just like whence.

-V
Just like whence -v.

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'
continuecontinue [n]

Skip remaining commands in a for, while, select, or until loop, resuming with the next iteration of the loop (or skipping n loops).

disowndisown [job ...]

ksh93 only. 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.

dodo

Reserved word that precedes the command sequence in a for, while, until, or select statement.

donedone

Reserved word that ends a for, while, until, or select statement.

echoecho [-n] [string]

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. In the Korn shell, echo is built-in, and it emulates the system's real echo command.[6] (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:

[6]But, if a path search finds /usr/bin/echo, the ksh built-in echo doesn't accept the -n option. (The situation with echo is a mess; consider using printf instead.)

\a
Alert (ASCII BEL). (Not in /bin/sh's echo.)

\b
Backspace.

\c
Suppress the terminating newline (same as -n).

\f
Formfeed.

\n
Newline.

\r
Carriage return.

\t
Tab character.

\v
Vertical-tab character.

\\
Backslash.

\0nnn
ASCII character represented by octal number nnn, where nnn is one, two, or three digits and is preceded by a 0.

Examples

$ echo "testing printer" | lp
$ echo "Warning: ringing bell \a"
esacesac

Reserved word that ends a case statement. Omitting esac is a common programming error.

evaleval 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 (Chapter 5) for another example.

Example

This fragment of a Bourne 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

exec [command args ...]

exec [-a name] [-c] [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 only.

Options

-a
Use name for the value of argv[0].

-c
Clear the environment before executing the program.

Examples

trap 'exec 2>&-' 0		Close standard error when 
			shell script exits (signal 0)
$ exec /bin/csh		Replace Bourne shell with C shell
$ exec < infile		Reassign standard input to infile
exitexit [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, 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
exportexport [variables]
export [name=[value
] ...]
export -p

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 Korn shell 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 specific to ksh93.

Option

-p
Print export before printing the names and values of exported variables. This allows saving a list of exported variables for rereading later.

Example

In the Bourne shell, you would type:

TERM=vt100
export TERM

In the Korn shell, you could type this instead:

export TERM=vt100
falsefalse

ksh88 alias for let 0. Built-in command in ksh93 that exits with a false return value.

fcfc [options] [first [last]]
fc -e - [old=new] [command
]

ksh88 only. Display or edit commands in the history list. (Use only one of -l or -e.) 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 string with new string, 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 Section 4.5.

Options

-e [editor]
Invoke editor to edit the specified history commands. The default editor is set by the shell variable FCEDIT. If that variable is not set, the default is /bin/ed.

-e -
Execute (or redo) a history command; refer to second syntax line above.

-l
List the specified command or range of commands, or list the last 16.

-n
Suppress command numbering from the -l listing.

-r
Reverse the order of the -l listing.

fcfc

ksh93 alias for hist.

fgfg [jobIDs]

Bring current job or jobIDs to the foreground. See Section 4.6

fifi

Reserved word that ends an if statement. (Don't forget to use it!)

forfor 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

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
forfor ((init; cond; incr))
do
    commands

done

ksh93 only. Arithmetic for loop, similar to C's. Evaluate init. While cond is true, execute the body of the loop. Evaluate incr before re-testing cond. Any one of the expressions may be omitted; a missing cond is treated as being true.

Examples

Search for a phrase in each odd chapter:

for ((x=1; x <= 20; x += 2))
do
	grep $1 chap$x
done
functionfunction name { commands; }

Korn shell only. Define name as a shell function. See the description of semantic issues in the name () entry earlier.

Example

Define a function to count files.

$ function fcount {
>	ls | wc -l
> }
functionsfunctions

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

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 and 1003.2 standards. 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
getoptsgetopts [-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 + or 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. getopts is available to non-Bourne shell users as /usr/bin/getopts.

Option

-a
Use name in error messages about invalid options. ksh93 only.

hashhash [-r] [commands]

Bourne shell 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 is called by the shell) and cost (the level of work needed to find the command). Commands that were found in a relative directory have an asterisk (*) added in the hits column.

With commands, the shell will add those commands to the hash table.

-r removes commands from the hash list, either all of them or just the specified commands. 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.

hashhash

Korn shell alias for alias -t (alias -t -- in ksh93). Emulates Bourne shell's hash.

histhist [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 string with new string, 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 Section 4.5.

Options

-e [editor]
Invoke editor to edit the specified history commands. The default editor is set by the shell variable HISTEDIT. If that variable is not set, FCEDIT is used. If neither is set, the default is /bin/ed.

-l
List the specified command or range of commands, or list the last 16.

-n
Suppress command numbering from the -l listing.

-r
Reverse the order of the -l listing.

-s
Execute (or redo) a history command; refer to second syntax line above.

history

history

Show the last 16 commands. ksh88 alias for fc -l. ksh93 alias for hist -l.

if 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 usually 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
integerinteger

Specify integer variables. Korn shell alias for typeset -i.

jobsjobs [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 Section 4.6

Options

-l
List job IDs and process group IDs.

-n
List only jobs whose status changed since last notification. Korn shell only.

-p
List process group IDs only.

-x cmd
Replace each job ID found in cmd with the associated process ID and then execute cmd. Not valid for Korn shell.

killkill [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 /usr/bin/kill described in Chapter 2. See Section 4.6.

Options

-l
List the signal names. (Used by itself.)

-n num
Send the given signal number. ksh93 only.

-s name
Send the given signal name. ksh93 only.

-signal
The signal number (from /usr/include/sys/signal.h) or name (from kill -l). With a signal number of 9, the kill is absolute.

Signals

Signals are defined in /usr/include/sys/signal.h and are listed here without the SIG prefix. You probably have more signals on your system than the ones shown here.

HUP	1	hangup
INT	2	interrupt
QUIT	3	quit
ILL	4	illegal instruction
TRAP	5	trace trap
IOT	6	IOT instruction
EMT	7	EMT instruction
FPE	8	floating point exception
KILL	9	kill
BUS	10	bus error
SEGV	11	segmentation violation
SYS	12	bad argument to system call
PIPE	13	write to pipe, but no process to read it
ALRM	14	alarm clock
TERM	15	software termination (the default signal)
USR1	16	user-defined signal 1
USR2	17	user-defined signal 2
CLD	18	child process died
PWR	19	restart after power failure
letlet expressions
     or
((expressions
))

Korn shell only. 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 “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`	sh, ksh88, ksh93
let i=i+1		ksh88 and ksh93
let "i = i + 1"
(( i = i + 1 ))
(( i += 1 ))
(( i++ ))		ksh93 only
namerefnameref newvar=oldvar ...

ksh93 alias for typeset -n. See the discussion of indirect variables in Section 4.3 earlier in this chapter.

newgrpnewgrp [group]

Change your group ID to group, or return to your default group. On modern Unix systems where users can be in multiple groups, this command is obsolete.

nohupnohup

Don't terminate a command after log out. nohup is a Korn shell alias:

nohup='nohup '

The embedded space at the end lets nohup interpret the following command as an alias, if needed.

printprint [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

-
Ignore all subsequent options.

--
Same as .

-f format
Print like printf, using format as the format string. Ignores the -n, -r, and -R options. ksh93 only.

-n
Don't end output with a newline.

-p
Send string to the process created by |&, instead of to standard output.

-r
Ignore the escape sequences often used with echo.

-R
Same as -r and ignore subsequent options (except -n).

-s
Send string to the history file.

-u[n]
Send string to file descriptor n (default is 1).

printfprintf format [val ...]

ksh93 only.Formatted printing, like the ANSI C printf function.

Additional Format Letters

%b
Expand escape sequences in strings (e.g., \t to tab, and so on).

%d
An additional period and the output base can follow the precision (e.g., %5.3.6d to produce output in base 6).

%P
Translate egrep extended regular expression into ksh pattern.

%q
Print a quoted string that can be reread later on.

pwd

pwd

pwd [-LP]

Print your present working directory on standard output. The second form is specific to the Korn shell.

Options

Options give control over the use of logical versus physical treatment of the printed path. See the entry for cd, earlier in this section.

-L
Use logical path (what the user typed, including any symbolic links) and the value of PWD for the current directory. This is the default.

-P
Use the actual filesystem physical path for the current directory.

rr

Reexecute previous command. ksh88 alias for fc -e -. ksh93 alias for hist -s.

readread variable1 [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 will be assigned to that variable. See the Examples here and under case. The return status is 0 unless EOF is reached.

Example

$ read first last address
Sarah Caldwell 123 Main Street
$ echo "$last, $first\n$address"
Caldwell, Sarah
123 Main Street
readread [options] [variable1[?string]] [variable2 ...]

Korn shell only. Same as in the Bourne shell, except that the Korn shell version supports the following options as well as the ? syntax for prompting. If the first variable is followed by ?string, string is displayed as a user prompt. If no variables are given, input is stored in the REPLY variable. Additionally, ksh93 allows you to specify a timeout.

Options

-A array
Read into indexed array array. ksh93 only.

-d delim
Read up to first occurrence of delim, instead of newline. ksh93 only.

-p
Read from the output of a |& coprocess.

-r
Raw mode; ignore \ as a line continuation character.

-s
Save input as a command in the history file.

-t timeout
When reading from a terminal or pipe, if no data is entered after timeout seconds, return l. This prevents an application from hanging forever, waiting for user input. ksh93 only.

-u[n]
Read input from file descriptor n (default is 0).

Example

Prompt yourself to enter two temperatures:

$ read n1?"High low: " n2
High low: 65 33
readonlyreadonly [variable1 variable2 ...]
readonly -p

Prevent the specified shell variables from being assigned new values. Variables can be accessed (read) but not overwritten. In the Korn shell, the syntax variable=value can assign a new value that cannot be changed. The second form is specific to ksh93.

Option

-p
Print readonly before printing the names and values of read-only variables. This allows saving a list of read-only variables for rereading later.

redirectredirect i/o-redirection ...

ksh93 alias for command exec.

Example

Change the shell's standard error to the console:

$ redirect 2>/dev/console
returnreturn [n]

Use inside a function definition. Exit the function with status n or with the exit status of the previously executed command.

selectselect x [in list]
do
    commands

done

Korn shell only. 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 line number, or they redisplay the menu by pressing the Return key. (User input is stored in the shell variable REPLY.) If a valid line 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:
setset [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, via ksh or sh. (See the earlier Section 4.7.) Arguments are assigned in order to $1, $2, etc.

Options

+A name
Assign remaining arguments as elements of array name. Korn shell only.

-A name
Same as +A, but unset name before making assignments. Korn shell only.

-a
From now on automatically mark variables for export after defining or changing them.

-b
Same as -o notify. The single-letter form is only in ksh93.

-C
Same as -o noclobber. The single-letter form is only in ksh93.

-e
Exit if a command yields a nonzero exit status. In the Korn shell, the ERR trap is executed before the shell exits.

-f
Ignore filename metacharacters (e.g., * ? [ ]).

-h
Locate commands as they are defined. The Korn shell creates tracked aliases, whereas the Bourne shell hashes command names. See hash.

-k
Assignment of environment variables (var=value) takes effect regardless of where they appear on the command line. Normally, assignments must precede the command name.

-m
Enable job control; background jobs execute in a separate process group. -m is usually set automatically. Korn shell only.

-n
Read commands but don't execute; useful for checking syntax. The Korn shell ignores this option if it is interactive.

-o [mode]
List Korn shell modes, or turn on mode mode. Many modes can be set by other options. Modes are:

allexport

Same as -a.

bgnice

Run background jobs at lower priority.

emacs

Set command-line editor to emacs.

errexit

Same as -e.

ignoreeof

Don't process EOF signals. To exit the shell, type exit.

keyword

Same as -k.

markdirs

Append / to directory names.

monitor

Same as -m.

noclobber

Prevent overwriting via > redirection; use >| to overwrite files.

noexec

Same as -n.

noglob

Same as -f.

nolog

Omit function definitions from history file.

notify

Print job completion messages as soon as jobs terminate; don't wait until the next prompt.

nounset

Same as -u.

privileged

Same as -p.

trackall

Same as -h.

verbose

Same as -v.

vi

Set command-line editor to vi.

viraw

Same as vi, but process each character when it's typed.

xtrace

Same as -x.

-p
Start up as a privileged user (i.e., don't process $HOME/.profile).

-s
Sort the positional parameters. Korn shell only.

-t
Exit after one command is executed.

-u
In substitutions, treat unset variables as errors.

-v
Show each shell command line when read.

-x
Show commands and arguments when executed, preceded by a +. (Korn shell: precede with the value of PS4.) This provides step-by-step debugging of shell scripts.

-
Turn off -v and -x, and turn off option processing. Included in Korn shell for compatibility with older versions of Bourne shell.

--
Used as the last option; -- turns off option processing so that arguments beginning with - are not misinterpreted as options. (For example, you can set $1 to -1.) If no arguments are given after --, unset the positional parameters.

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
shiftshift [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.

sleepsleep [n]

ksh93 only. Sleep for n seconds. n can have a fractional part.

stopstop [jobIDs]

Suspend the background job specified by jobIDs; this is the complement of CTRL-Z or suspend. Not valid in ksh88. See Section 4.6.

stopstop [jobIDs]

ksh93 alias for kill -s STOP.

suspendsuspend

Same as CTRL-Z. Often used to stop an su command. Not valid in ksh88; in ksh93, suspend is an alias for kill -s STOP $$.

testtest 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. The Korn shell allows an additional form, [[ ]]. condition is constructed using the following expressions. Conditions are true if the description holds true. 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

-a file
file exists. (K)

-b file
file exists and is a block special file.

-c file
file exists and is a character special file.

-d file
file exists and is a directory.

-f file
file exists and is a regular file.

-g file
file exists, and its set-group-id bit is set.

-G file
file exists, and its group is the effective group ID. (K)

-k file
file exists, and its sticky bit is set.

-L file
file exists and is a symbolic link. (K)

-o c
Option c is on. (K)

-O file
file exists, and its owner is the effective user ID. (K)

-p file
file exists and is a named pipe (fifo).

-r file
file exists and is readable.

-s file
file exists and has a size greater than zero.

-S file
file exists and is a socket. (K)

-t [n]
The open file descriptor n is associated with a terminal device; default n is 1.

-u file
file exists, and its set-user-id bit is set.

-w file
file exists and is writable.

-x file
file exists and is executable.

f1 -ef f2
Files f1 and f2 are linked (refer to same file). (K)

f1 -nt f2
File f1 is newer than f2. (K)

f1 -ot f2
File f1 is older than f2. (K)

String Conditions

string
string is not null.

-n s1
String s1 has nonzero length.

-z s1
String s1 has zero length.

s1 = s2
Strings s1 and s2 are identical. In the Korn shell, s2 can be a wildcard pattern. (See Section 4.2.2 earlier in this chapter.)

s1 == s2
Strings s1 and s2 are identical. s2 can be a wildcard pattern. Preferred over =. (K93)

s1 != s2
Strings s1 and s2 are not identical. In the Korn shell, s2 can be a wildcard pattern.

s1 < s2
ASCII value of s1 precedes that of s2. (Valid only within [[]] construct). (K)

s1 > s2
ASCII value of s1 follows that of s2. (Valid only within [[]] construct). (K)

Integer Comparisons

n1 -eq n2
n1 equals n2.

n1 -ge n2
n1 is greater than or equal to n2.

n1 -gt n2
n1 is greater than n2.

n1 -le n2
n1 is less than or equal to n2.

n1 -lt n2
n1 is less than n2.

n1 -ne n2
n1 does not equal n2.

Combined Forms

(condition)
True if condition is true (used for grouping). The () s should be quoted by a \.

! condition
True if condition is false.

condition1 -a condition2
True if both conditions are true.

condition1 && condition2
True if both conditions are true. (Valid only within [[]] construct.) (K)

condition1 -o condition2
True if either condition is true.

condition1 || condition2
True if either condition is true. (Valid only within [[]] construct.) (K)

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...
timetime command
time [command
]

Korn shell only. 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

times

Print accumulated process times for user and system.

timestimes

ksh93 alias for { {time;} 2>&1;}. See also time.

traptrap [ [commands] signals]
trap -p

Execute commands if any signals are received. The second form is specific to ksh93; it prints the current trap settings in a form suitable for rereading later.

Common signals include 0, 1, 2, and 15. Multiple commands should 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. 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

Signals are listed along with what triggers them:

0

Exit from shell (usually when shell script finishes).

1

Hangup (usually logout).

2

Interrupt (usually CTRL-C).

3

Quit.

4

Illegal instruction.

5

Trace trap.

6

IOT instruction.

7

EMT instruction.

8

Floating-point exception.

10

Bus error.

12

Bad argument to a system call.

13

Write to a pipe without a process to read it.

14

Alarm timeout.

15

Software termination (usually via kill).

ERR

Nonzero exit status. Korn shell only.

DEBUG

Execution of any command. Korn shell only.

KEYBD

A key has been read in emacs, gmacs, or vi editing mode. ksh93 only.

Examples

trap "" 2		Ignore signal 2 (interrupts)
trap 2		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" 0 1 2 15

Print a “clean up” message when the shell program receives signals 1, 2, or 15:

trap 'echo Interrupt!  Cleaning up...' 1 2 15
truetrue

ksh88 alias for :. ksh93 built-in command that exits with a true return value.

typetype commands

Show whether each command name is a Unix command, a built-in command, or a defined shell function. In the Korn shell, this is simply an alias for whence -v.

Example

$ type mv read
mv is /bin/mv
read is a shell builtin
typesettypeset [options] [variable[=value ...]]
typeset -p

Korn shell only. 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 given, -option prints variable names and values; +option prints only the names.

The second form shown is specific to ksh93.

Options

-A arr
arr is an associative array. ksh93 only.

-E d
variable is a floating-point number. d is the number of decimal places. The value is printed using printf %g format. ksh93 only.

-F d
variable is a floating-point number. d is the number of decimal places. The value is printed using printf %f format. ksh93 only.

-f[c]
The named variable is a function; no assignment is allowed. If no variable is given, list current function names. Flag c can be t, u, or x. t turns on tracing (same as set -x). u marks the function as undefined, which causes autoloading of the function (i.e., a search of FPATH locates the function when it's first used. ksh93 also searches PATH). x exports the function. Note the aliases autoload and functions.

-H
On non-Unix systems, map Unix filenames to host filenames.

-i[n]
Define variables as integers of base n. integer is an alias for typeset -i.

-L[n]
Define variables as left-justified strings, n characters long (truncate or pad with blanks on the right as needed). Leading blanks are stripped; leading 0s are stripped if -Z is also specified. If no n is supplied, field width is that of the variable's first assigned value.

-l
Convert uppercase to lowercase.

-n
variable is an indirect reference to another variable (a nameref). ksh93 only. (See Section 4.3 earlier in this chapter.)

-p
Print typeset commands to recreate the types of all the current variables. ksh93 only.

-R[n]
Define variables as right-justified strings, n characters long (truncate or pad with blanks on the left as needed). Trailing blanks are stripped. If no n is supplied, field width is that of the variable's first assigned value.

-r
Mark variables as read-only. See also readonly.

-t
Mark variables with a user-definable tag.

-u
Convert lowercase to uppercase.

-x
Mark variables for automatic export.

-Z[n]
When used with -L, strip leading 0s. When used alone, it's similar to -R except that -Z pads numeric values with 0s and pads text values with blanks.

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
ulimitulimit [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

-H
Hard limit. Anyone can lower a hard limit; only privileged users can raise it.

-S
Soft limit. Must be lower than the hard limit.

-a
Print all limits.

-c
Maximum size of core files.

-d
Maximum kilobytes of data segment or heap.

-f
Maximum size of files (the default option).

-m
Maximum kilobytes of physical memory. Korn shell only. (Not effective on all Unix systems.)

-n
Maximum file descriptor plus 1.

-p
Size of pipe buffers. Korn shell only. (Not effective on all Unix systems.)

-s
Maximum kilobytes of stack segment.

-t
Maximum CPU seconds.

-v
Maximum kilobytes of virtual memory.

umask

umask [nnn]

umask [-S] [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 specific to ksh93. A symbolic mask is permissions to keep.

Option

-S
Print the current mask using symbolic notation. ksh93 only.

unaliasunalias names
unalias -a

Korn shell only. Remove names from the alias list. See also alias.

Option

-a
Remove all aliases. ksh93 only.

unsetunset names

Bourne shell version. Erase definitions of functions or variables listed in names.

unsetunset [options] names

Erase definitions of functions or variables listed in names. The Korn shell version supports options.

Options

-f
Unset functions in names.

-n
Unset indirect variable (nameref) name, not the variable the nameref refers to. ksh93 only.

-v
Unset variables names (default). ksh93 only.

until

until condition

do

    commands

done

Until condition is met, do commands. condition is usually specified with the test command.

waitwait [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. If job control is not in effect, ID can be only a process ID number. See Section 4.6.

Example

wait $!	Wait for most recent background process to finish
whencewhence [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

-a
Print all interpretations of commands. ksh93 only.

-f
Skip the search for shell functions. ksh93 only.

-p
Search for the pathname of commands.

-v
Verbose output; same as type.

whilewhile condition
do
    commands

done

While condition is met, do commands. condition is usually specified with the test command. See the Examples under case and test.

filename

filename

Read and execute commands from executable file filename, or execute a binary object file.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.