Appendix B. Reference Information

This appendix contains reference lists for invocation options, built-in commands and keywords, predefined aliases, built-in shell variables, test operators, shell options, typeset options, arithmetic, emacs-mode commands, and vi-mode control commands. Furthermore, it describes how to use the full facilities of the built-in getopts command.

Invocation Options

Here is a list of the options you can use when invoking the Korn shell. In addition to these, any set option can be used on the command line; see the table on options later in this appendix. Login shells are usually invoked with the options -i (interactive), -s (read from standard input), and -m (enable job control).

OptionMeaning
-c string Execute string, then exit.
-D

Print all $"..." strings in the script. This is for use in creating a database of locale-specific translations of strings in a script.

-i Interactive shell. Ignore signals TERM, INTR, and QUIT.
-r Restricted shell. See Chapter 10.
-R filename

Create a cross-reference database for variable and command definitions in filename. May not be compiled in.

-s

Read commands from the standard input. If an argument is given, this flag takes precedence (i.e., the argument won’t be treated as a script name and standard input will be read).

Built-in Commands and Keywords

Here is a summary of all built-in commands and keywords.

NameCommand/keywordChapterSummary
! Keyword5Invert the true/false result of the following pipeline.
: Command7Do nothing (just do expansions of arguments).
. Command4Read file and execute its contents in current shell.
alias Command3Set up shorthand for command or command line.
bg Command8Put job in background.
builtin Command 

Add or remove built-in commands; print information about them.

break Command5

Exit from surrounding for, select, while, or until loop.

case Keyword5Multiway conditional construct.
cd Command1Change working directory.
command Command5

Locate built-in and external commands; find a built-in command instead of an identically named function.

continue Command4

Skip to next iteration of for, select, while, or until loop.

disown Command8

Disassociate a background job from the current shell. The effect is that the job is not sent the HUP signal when the shell exits.

echo Command4Expand and print arguments (obsolete).
exec Command9Replace shell with given program.
exit Command5Exit from shell.
export Command3Create environment variables.
eval Command7Process arguments as a command line.
false Command8

Do nothing and exit unsuccessfully. Useful for making infinite loops.

fg Command8Put background job in foreground.
for Keyword5Looping construct.
function Keyword4Define function.
getconf Command 

Get system-specific information. The parameters are defined by POSIX.

getopts Command6Process command-line options.
hist Command2Work with command history.
if Keyword5Conditional construct.
jobs Command1List background jobs.
kill Command8Send signal to process.
let Command6Arithmetic variable assignment.
newgrp Command Start new shell with new group ID (obsolete).
print Command1Expand and print arguments on standard output.
printf Command7

Expand and print arguments on standard output, using ANSI C printf(3) format specifiers.

pwd Command1Print working directory.
read Command7Read a line from standard input.
readonly Command6Make variables read-only (unassignable).
return Command5Return from surrounding function or script.
select Keyword5Menu generation construct.
set Command3Set options.
shift Command6Shift command-line arguments.
sleep Command8Suspend execution for the given number of seconds.
test Command5

Old version of conditional test program. Use [[...]] instead.

time Keyword 

Run command and print execution times. By itself, prints cumulative times for the shell and all children.

trap Command8Set up signal-catching routine.
true Command8

Do nothing and exit successfully. Useful for making infinite loops.

typeset Command6Set special characteristics of variables and functions.
ulimit Command10Set/show process resource limits.
umask Command10Set/show file permission mask.
unalias Command3Remove alias definitions.
unset Command3Remove definitions of variables or functions.
until Keyword5Looping construct.
wait Command8Wait for background job(s) to finish.
whence Command3Identify source of command.
while Keyword5Looping construct.

Assignments for the alias, export, readonly, and typeset commands are processed like variable assignments, in that tilde expansion is done after the = character, and field splitting is not done on any variable substitutions in the value being assigned.

Predefined Aliases

A number of aliases are predefined, i.e. automatically built-in to ksh at compile time. They are listed in the table below. Note that some of them are defined with a trailing space character. This enables alias expansion on the word following the alias on the command line.

NameChapterFull value
autoload 4, 6 alias autoload='typeset -fu'
command 7 alias command='command '
fc 2 alias fc=hist
float 6 alias float='typeset -E'
functions 6 alias functions='typeset -f'
hash 3 alias hash='alias -t --'
history 2 alias history='hist -l'
integer 6 alias integer='typeset -i'
nameref 4 alias nameref='typeset -n'
nohup 3, 8 alias nohup='nohup '
r 2 alias r='hist -s'
redirect 9 alias redirect='command exec'
stop 8 alias stop='kill -s STOP'
times   alias times='{ {time;} 2>&1;}'
type 4 alias type='whence -v'

Built-in Shell Variables

Here is a summary of all built-in shell variables:

VariableChapterMeaning
# 4Number of arguments given to current process.
@ 4

Command-line arguments to current process. Inside double quotes, expands to individual arguments.

* 4

Command-line arguments to current process. Inside double quotes, expands to a single argument.

- (hyphen) Options given to shell on invocation.
? 5Exit status of previous command.
$ 8Process ID of shell process.
_ (underscore)3

Inside $MAILPATH: the filename that triggered a “you have mail” message. On the command line: last argument to previous command. Inside a script: the full pathname used to find and run the script.

! 8Process ID of last background command.
.sh.edchar 10

Characters entered when processing a KEYBD trap.

.sh.edcol 10

Position of the cursor in the most recent KEYBD trap.

.sh.edmode 10

Equal to ESC in vi-mode, empty otherwise.

.sh.edtext 10

Characters in the input buffer during a KEYBD trap.

.sh.match 4

Array variable with text that matched pattern in variable substitution. (Starting with ksh93l.)

.sh.name 9

Name of a variable executing a discipline function.

.sh.subscript 9

Subscript of an array variable executing a discipline function.

.sh.value 9

Value of the variable executing a discipline function.

.sh.version 4, 9

Version of ksh.

CDPATH 3List of directories for cd command to search.
COLUMNS 3

Width of display in columns (for editing modes and select).

EDITOR 2

Used to set editing mode; also used by mail and other programs. Overriden by VISUAL, if that is set.

ENV 3

Name of file to run as environment file when shell is invoked.

FCEDIT 2Obsolete default editor for hist command.
FIGNORE 1Pattern for files to ignore during pattern expansion.
FPATH 4Search path for autoloaded functions.
HISTCMD 2Number of current command in command history.
HISTEDIT 2Default editor for hist command.
HISTFILE 2Name of command history file.
HISTSIZE 2Number of lines kept in history file.
HOME 3Home (login) directory.
IFS 7

Internal field separator: list of characters that act as word separators. Normally set to space, TAB, and newline.

LANG  

Default name of current locale; overridden by the other LC_* variables.

LC_ALL  

Name of current locale; overrides LANG and the other LC_* variables.

LC_COLLATE  

Name of current locale for character collation (sorting) purposes.

LC_CTYPE  

Name of current locale for character class determination during pattern matching; see Chapter 4.

LC_NUMERIC  

Name of current locale for number formatting (decimal point, thousands separator).

LINENO 9Number of line in script or function that just ran.
LINES 3Height of display in lines (for select command).
MAIL 3Name of file to check for new mail.
MAILCHECK 3How often (in seconds) to check for new mail.
MAILPATH 3

List of file names to check for new mail, if MAIL is not set.

OLDPWD 3Previous working directory.
OPTARG 6Argument to option being processed by getopts.
OPTIND 6Number of first argument after options.
PATH 3Search path for commands.
PPID 8Process ID of parent process.
PS1 3Primary command prompt string.
PS2 3Prompt string for line continuations.
PS3 5Prompt string for select command.
PS4 9Prompt string for xtrace option.
PWD 3Current working directory.
RANDOM 9

Random number between 0 and 32767 (215-1).

REPLY 5, 7

User’s response to select command; result of read command if no variable names given.

SECONDS 3Number of seconds since shell was invoked.
SHELL 3

Full pathname of shell programs should use to run commands.

TMOUT 5, 7, 10

If set to a positive integer, number of seconds between commands after which shell automatically terminates. Also applies to reading responses to select and read.

VISUAL 2Used to set editing mode.

Test Operators

These are the operators that are used with the [[...]] construct. They can be logically combined with && (“and”) and || (“or”) and grouped with parenthesis. When used with filenames of the form /dev/fd/ N, they test the corresponding attribute of open file descriptor N.

OperatorTrue if...
-a file

file exists. (Obsolete. -e is preferred.)

-b file file is a block device file.
-c file file is a character device file.
-C file

file is a contiguous file. (Not for most Unix versions.)

-d file file is a directory.
-e file file exists.
-f file file is a regular file.
-g file file has its setgid bit set.
-G file

file’s group ID is the same as the effective group ID of the shell.

-h file file is a symbolic link.
-k file file has its sticky bit set.
-l file

file is a symbolic link. (Only works on systems where /bin/test -l tests for symbolic links.)

-L file file is a symbolic link.
-n string string is non-null.
-o option option is set.
-O file file is owned by the shell’s effective user ID.
-p file file is a pipe or named pipe (FIFO file).
-r file file is readable.
-s file file is not empty.
-S file file is a socket.
-t N File descriptor N points to a terminal.
-u file file has its setuid bit set.
-w file file is writable.
-x file

file is executable, or file is a directory that can be searched.

-z string string is null.
fileA -nt fileB

fileA is newer than fileB, or fileB does not exist.

fileA -ot fileB

fileA is older than fileB, or fileB does not exist.

fileA -ef fileB

fileA and fileB point to the same file.

string = pattern

string matches pattern (which can contain wildcards). Obsolete; == is preferred.

string == pattern

string matches pattern (which can contain wildcards).

string != pattern string does not match pattern.
stringA < stringB

stringA comes before stringB in dictionary order.

stringA > stringB

stringA comes after stringB in dictionary order.

exprA -eq exprB

Arithmetic expressions exprA and exprB are equal.

exprA -ne exprB

Arithmetic expressions exprA and exprB are not equal.

exprA -lt exprB exprA is less than exprB.
exprA -gt exprB exprA is greater than exprB.
exprA -le exprB exprA is less than or equal to exprB.
exprA -ge exprB exprA is greater than or equal to exprB.

The operators -eq, -ne, -lt, -le, -gt, and -ge are considered obsolete in ksh93; the let command or ((...)) should be used instead.

For =, ==, and !=, quote pattern to do literal string comparisons.

Options

These are options that can be turned on with the set -o command. All are initially off except where noted. Abbreviations, where listed, are options to set that can be used instead of the full set -o command (e.g., set -a is an abbreviation for set -o allexport). For the most part, the abbreviations are actually backward-compatible Bourne shell options. To disable an option, use set +o long-name or set +X, where long-name and X are the long form or the single character form of the option, respectively.

OptionAbbrevMeaning
allexport -a

Export all subsequently defined variables.

bgnice  

Run all background jobs at decreased priority (on by default).

emacs  

Use Emacs-style command-line editing.

errexit -e

Exit the shell when a command exits with nonzero status.

gmacs  

Use Emacs-style command-line editing, but with a slightly different meaning for CTRL-T (See Chapter 2).

ignoreeof  

Disallow CTRL-D to exit the shell.

keyword -k

Execute assignments in the middle of command lines. (Very obsolete.)

markdirs  

Add / to all directory names generated from wildcard expansion.

monitor -m

Enable job control (on by default).

noclobber -C

Don’t allow > redirection to existing files.

noexec -n

Read commands and check for syntax errors, but don’t execute them.

noglob -f

Disable wildcard expansion.

nolog  

Disable command history for function definitions.

notify -b

Print job completion messages right away, instead of waiting for next prompt.

nounset -u

Treat undefined variables as errors, not as null.

pipefail  

Wait for all jobs in a pipeline to complete. Exit status is that of last command that failed, or zero otherwise. (ksh93g and later.)

privileged -p

Script is running in suid mode.

trackall -h

Create an alias for each full pathname found in a command search. (ksh93 ignores this option; the behavior is always on, even if this option is turned off.)

verbose -v

Print commands (verbatim) before running them.

vi  

Use vi-style command-line editing.

viraw  

Use vi-mode and have each keystroke take effect immediately. (This is required on some very old systems for vi-mode to work at all, and is necessary on all systems in order to use TAB for completion. Starting with ksh93n, it is automatically enabled when vi-mode is being used.)

xtrace -x

Print commands (after expansions) before running them.

The set command has a few additional options that don’t have corresponding set -o versions, as follows:

OptionMeaning
set -A ...Indexed array assignment.
set -s Sort the positional parameters.
set -t

Read and execute one command, and then exit. (Obsolete.)

Typeset Options

These are the options to the typeset command. Use + option to turn an option off, e.g., typeset +x foo to stop exporting the variable foo.

OptionMeaning
 With no option, create local variable within function.
-A Declare variable as an associative array.
-E[n]

Declare variable as a floating-point number. Optional n is number of significant figures.

-F[n]

Declare variable as a floating-point number. Optional n is number of significant digits.

-f With no arguments, prints all function definitions.
-f fname Print the definition of function fname.
+f Print all function names.
-ft Turn on trace mode for named function(s).
+ft Turn off trace mode for named function(s).
-fu Define given name(s) as autoloaded function(s).
-fx Obsolete; does nothing in ksh93.
-H Unix to host filename mapping for non-Unix system.
-i[n]

Declare variable as an integer. Optional n is output base.

-l Convert all letters to lowercase.
-L Left-justify and remove leading spaces.
-n Declare variable as a nameref.
-p

Print typeset commands to re-create variables with the same attributes.

-r Make variable read-only.
-R Right-justify and remove trailing spaces.
-t Tag the variable. (Obsolete.)
-u Convert all letters to uppercase.
-ui[n]

Declare variable as an unsigned integer. Optional n is output base. (ksh93m and newer.)

-x

Export variable, i.e., put in environment so that it is passed to subprocesses.

-Z[n]

Right-justify and fill with leading zeros. n is width, or width is set from value used in first assignment.

Arithmetic

Starting with ksh93m, the built-in arithmetic facility understands a large percentage of the C language’s expressions. This makes the shell more attractive as a full-blown programming language. The following features are available:

Trailing type suffixes

Integer constants can have a trailing U or L suffix to indicate that they are unsigned or long, respectively. While the lowercase versions may also be used, this is not recommended, since it is easy to confuse an l (letter ell) with a 1 (digit one).

C character constants

C single-quoted character constants are recognized. As in C, they act like integer constants. For example:

$ typeset -i c
$ for ((c = 'a'; c <= 'z'; c++))
> do print $c
> done
97
98
99
100
...

Octal and hexadecimal constants

You can use the C format for octal (base 8) and hexadecimal (base 16) constants. Octal constants start with a leading 0, and hexadecimal constants start with a leading 0x or 0X. For example:

$ print $((010 + 1))     
                        Octal 10 is decimal 8
9
$ print $((0x10 + 1))    
                        Hexadecimal 10 is decimal 16
17

Unsigned integer arithmetic

By using typeset -ui, you can create unsigned integers. Regular integers represent both positive and negative numbers. Unsigned integers start at 0, go up to some implementation-dependent value, and then “wrap” around again to 0. Similarly, subtracting 1 from 0 wraps around the other way, yielding the largest unsigned number:

$ typeset -ui u=0
$ let u--
$ print $u
4294967295

C operators and precedence

ksh supports the full set of C operators, with the same precedence and associativity. The operators were presented in detail in Chapter 6 and are summarized again below.

OperatorMeaningAssociativity
++ -- Increment and decrement, prefix and postfixLeft to right
+ - ! ~ Unary plus and minus; logical and bitwise negationRight to left
**

Exponentiation[a]

Right to left
* / % Multiplication, division, and remainderLeft to right
+ - Addition and subtractionLeft to right
<< >> Bit-shift left and rightLeft to right
< <= > >= ComparisonsLeft to right
== != Equal and not equalLeft to right
& Bitwise andLeft to right
^ Bitwise exclusive-orLeft to right
| Bitwise orLeft to right
&& Logical and (short circuit)Left to right
|| Logical or (short circuit)Left to right
?: Conditional expressionRight to left

= += -= *= /= %= &= ^= <<= >>=

Assignment operatorsRight to left
, Sequential evaluationLeft to right

[a] ksh93m and newer. The ** operator is not in the C language.

Emacs Mode Commands

Here is a complete list of all emacs editing mode commands. Some of these, such as “ESC [ A,” represent ANSI standard terminal arrow key sequences; they were added for ksh93h.

CommandMeaning
CTRL-AMove to beginning of line
CTRL-BMove backward one character without deleting
CTRL-CCapitalize character after point
CTRL-DDelete one character forward
CTRL-EMove to end of line
CTRL-FMove forward one character
CTRL-I (TAB)

Do filename completion on current word (starting with ksh93h)

CTRL-JSame as ENTER.
CTRL-KDelete (“kill”) forward to end of line
CTRL-LRedisplay the line
CTRL-MSame as ENTER
CTRL-NNext line
CTRL-OSame as ENTER, then display next line in history file
CTRL-PPrevious line
CTRL-RSearch backward
CTRL-TTranspose the two characters on either side of point
CTRL-URepeat the following command four times
CTRL-VPrint the version of the Korn shell
CTRL-W

Delete (“wipe”) all characters between point and mark

CTRL-X CTRL-E

Invoke the emacs program on the current command

CTRL-X CTRL-XExchange point and mark
CTRL-YRetrieve (“yank”) last item deleted
CTRL-] x Search forward for x, where x is any character
CTRL-@Set mark at point
DELDelete one character backward
CTRL-[Same as ESC (most keyboards)
ESC bMove one word backward
ESC cChange word after point to all capital letters
ESC dDelete one word forward
ESC fMove one word forward
ESC hDelete one word backward
ESC lChange word after point to all lowercase letters
ESC pSave characters between point and mark as if deleted
ESC CTRL-HDelete one word backward
ESC CTRL-] x

Search backward for x, where x is any character

ESC SPACESet mark at point
ESC #Insert line in history file for future editing
ESC DELDelete one word backward
ESC <Move to first line of history file
ESC >Move to last line of history file
ESC .Insert last word in previous command line after point
ESC _Same as above
ESC ESCDo filename/command/variable completion on current word
ESC *Do filename/command/variable expansion on current word
ESC =Do filename/command/variable listing on current word
ESC [ APrevious line (ksh93h and newer)
ESC [ BNext line (ksh93h and newer)
ESC [ CMove forward one character (ksh93h and newer)
ESC [ DMove backward one character (without deleting) (ksh93h and newer)
ESC [ HMove to beginning of line (ksh93h and newer)
ESC [ YMove to end of line (ksh93h and newer)
Kill

The stty(1) kill character, often CTRL-U or @ or CTRL-X. This erases everything on the line. Typing it twice toggles “line feed” mode, which issues a line-feed character to start over on a new line. This is appropriate for paper-only terminals

vi Control Mode Commands

Here is a complete list of all vi-mode control commands. As for the emacs mode commands, the sequences such as “[ A” are for ANSI standard terminal arrow keys and were added for ksh93h.

CommandMeaning
h Move left one character
[ D Move left one character (ksh93h and newer)
l Move right one character
space Move right one character
[ C Move right one character (ksh93h and newer)
w Move right one word
b Move left one word
W Move to beginning of next nonblank word
B Move to beginning of preceding nonblank word
e Move to end of current word
E Move to end of current nonblank word
0 Move to beginning of line
[ H Move to beginning of line (ksh93h and newer)
^ Move to first nonblank character in line
$ Move to end of line
[ Y Move to end of line (ksh93h and newer)
i Insert text before current character
a Insert text after current character
I Insert text at beginning of line
A Insert text at end of line
r Replace one character (doesn’t enter input mode)
R Overwrite existing text
dh Delete one character backwards
dl Delete one character forwards
db Delete one word backwards
dw Delete one word forwards
dB Delete one nonblank word backwards
dW Delete one nonblank word forwards
d$ Delete to end of line
d0 Delete to beginning of line
D Equivalent to d$ (delete to end of line)
dd Equivalent to 0d$ (delete entire line)
C Equivalent to c$ (delete to end of line, enter input mode)
cc Equivalent to 0c$ (delete entire line, enter input mode)
s Equivalent to xi (delete current character, enter input mode)
S Equivalent to cc (delete entire line, enter input mode)
x Equivalent to dl (delete character backwards)
X Equivalent to dh (delete character forwards)
k or - Move backward one line
[ A Move backward one line (ksh93h and newer)
j or + Move forward one line
[ B Move forward one line (ksh93h and newer)
G Move to line given by repeat count
/ string Search forward for string
? string Search backward for string
n Repeat search forward
N Repeat search backward
f x Move right to next occurrence of x
F x Move left to previous occurrence of x
t x Move right to next occurrence of x, then back one space
T x Move left to previous occurrence of x, then forward one space
yh Yank one character backwards
yl Yank one character forwards
yb Yank one word backwards
yw Yank one word forwards
yB Yank one nonblank word backwards
yW Yank one nonblank word forwards
y$ Yank to end of line
y0 Yank to beginning of line
Y Equivalent to y$ (yank to end of line)
yy Equivalent to 0y$ (yank entire line)
u Undo last editing change
U Undo all editing changes made to the line
. (dot)Repeat last editing command
| Move to absolute column position
; Redo last character finding command
, Redo last character finding command, but in opposite direction
%

Move to matching (, ), {, }, [, or ]

Do filename/command/variable completion
CTRL-I (TAB)

Do filename/command/variable completion (only for set -o viraw) (starting with ksh93h)

* Do filename/command/variable expansion (onto command line)
= Do filename/command/variable expansion (as printed list)
~ Invert (“twiddle”) case of current character(s)
_ Append last word of previous command, enter input mode
v

Run the hist command on the current line (actually, run the command hist -e ${VISUAL:-${EDITOR:-vi}}); usually this means run the full vi on the current line

CTRL-JSame as ENTER
CTRL-L

Start a new line and redraw the current line on it

CTRL-MSame as ENTER
CTRL-VPrint the version of the Korn shell
#

Prepend # (comment character) to the line and send it. If the line starts with #, remove the leading # and all leading # characters after any embedded newlines

@ x Insert expansion of alias _x as command mode input

Using getopts

The getopts command is extremely capable. With it, you can make your shell scripts accept long options, specify that arguments are optional or numeric, and provide descriptions of the arguments and values such that the -?, --man, --html and --nroff options work the same for your program as they do for the ksh93 built-in commands.

The price for this power is the complexity of the option description “language.” Based on a description provided by Dr. Glenn Fowler of AT&T Research, we describe how the facilities evolved, how they work, and summarize how to use them in your own programs. We use the the extended getopts command in the solution to Task B-1.

The first step is to describe the options. This is done with a comment at the top of the script:

# usage: phaser4 [ options ] files
#   -k, --kill                  use kill setting (default)
#   -l n, --level n             set phaser level (default = 2)
#   -s, --stun                  use stun-only setting
#   -t [lf], --tricorder [lf]   tricorder mode, opt. scan for life form lf

Now the fun begins. This outline of capabilities follows the order in which features were added to getopts.

  1. Start with the getopts command as described in Chapter 6. This yields a simple option string that only allows one-letter options:

    USAGE="kl#st:"
    while getopts "$USAGE" optchar ...

  2. Add a textual description for the option argument. This is done by enclosing arbitrary text in between [ and ]:

    USAGE="kl#[level]st:[life_form]"
    while getopts "$USAGE" optchar ...

  3. Allow a default value for an option’s argument. This is done by specifying := value within the description in between the brackets:

    USAGE="kl#[level:=2]st:[life_form]"
    while getopts "$USAGE" optchar ...

  4. Add ? after the : to indicate an optional argument:

    USAGE="kl#[level:=2]st:?[life_form]"
    while getopts "$USAGE" optchar ...

  5. Allow long options that start with --. This is done by using [ let : long ] instead of the single option letter:

    USAGE="[k:kill]"
    USAGE+="[l:level]#[level:=2]"
    USAGE+="[s:stun]"
    USAGE+="[t:tricorder]:?[life_form]"
    while getopts "$USAGE" optchar ...

    Here, we’ve split each option out into its own line, to make things easier to follow, and concatenated them together using the += assignment operator. Note that there are no newlines in the string.

  6. Within the square brackets for an option letter, allow descriptive text to follow a question mark. This text is ignored, as are any whitespace characters, including newlines:

    USAGE="[k:kill?Use kill setting (default).]"
    USAGE+="[l:level]#[level:=2?Set the phaser level.]"
    USAGE+="[s:stun?Stun-only.]"
    USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
    while getopts "$USAGE" optchar ...

  7. Now it gets interesting. Unix man page style section headings come before the option description. They are distinguished from option descriptions by starting with a + inside square brackets:

    USAGE="[+NAME?phaser4 --- combined phaser and tricorder]"
    USAGE+="[+DESCRIPTION?The phaser4 program combines the operation "
    USAGE+="of the phaser3 and tricorder programs in one handy tool.]"
    USAGE+="[k:kill?Use kill setting (default).]"
    USAGE+="[l:level]#[level:=2?Set the phaser level.]"
    USAGE+="[s:stun?Stun-only.]"
    USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
    while getopts "$USAGE" optchar ...

    Note that getopts automatically understands that the actual options description comes after the man page headings; there is no explicit [+OPTIONS?...] in the text of the string.

  8. Additional descriptive text for the short usage summary can be given after the options description, separated by two newlines:

    USAGE="[+NAME?phaser4 --- combined phaser and tricorder]"
    USAGE+="[+DESCRIPTION?The phaser4 program combines the operation "
    USAGE+="of the phaser3 and tricorder programs in one handy tool.]"
    USAGE+="[k:kill?Use kill setting (default).]"
    USAGE+="[l:level]#[level:=2?Set the phaser level.]"
    USAGE+="[s:stun?Stun-only.]"
    USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
    USAGE+=$'
    
    file ...
    
    '                     Use ANSI C string for 
     character
    USAGE+="[+SEE ALSO?phaser3(1), tricorder(1)]"
    while getopts "$USAGE" optchar ...

  9. To indicate text to be italicized, enclose it in between pairs of a characters. To indicate text to be emboldened, enclose it between pairs of :

    USAGE="[+NAME?phaser4 --- combined phaser and tricorder]"
    USAGE+="[+DESCRIPTION?The aphaser4a program combines the operation "
    USAGE+="of the aphaser3a and atricordera programs in one handy tool.]" 
    USAGE+="[k:kill?Use kill setting (default).]"
    USAGE+="[l:level]#[level:=2?Set the phaser level.]"
    USAGE+="[s:stun?Stun-only.]"
    USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
    USAGE+=$'
    
    file ...
    
    '
    USAGE+=$'[+SEE ALSO?aphaser3a(1), atricordera(1)]'
    while getopts "$USAGE" optchar ...

  10. Dynamic control of descriptive output is possible. To do this, write a function that prints whatever you want, and then enclose the function name in a pair of f characters: f name f (this isn’t needed for phaser4).

  11. If an option (or anything else) needs a verbose description, enclosing the text between { and } creates an indented list. This is particularly useful for describing different option values:

    USAGE="[+NAME?phaser4 --- combined phaser and tricorder]"
    USAGE+="[+DESCRIPTION?The aphaser4a program combines the operation "
    USAGE+="of the aphaser3a and atricordera programs in one handy tool.]"
    USAGE+="[k:kill?Use kill setting (default).]"
    USAGE+="[l:lev*el]#[level:=2?Set the phaser level.]{   Add value descriptions
                    [level=0-2?non-lethal settings]
                    [level=3-10?lethal, use with caution]
    }"
    USAGE+="[s:stun?Stun-only.]"
    USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
    USAGE+=$'
    
    file ...
    
    '
    USAGE+=$'[+SEE ALSO?aphaser3a(1), atricordera(1)]'
    while getopts "$USAGE" optchar ...

  12. Almost done. Text in between square brackets that begins with a minus sign provides version and identification information. Such text comes at the very beginning. The empty item indicates a version and may contain both SCCS and RCS ID strings as shown here:

    USAGE=$'[-?
    @(#)$Id: phaser4 (Starfleet Research and Development)'
    USAGE+=$' Stardate 57234.22 $
    ]'
    USAGE+="[-author?J. Programmer <[email protected]>]"
    USAGE+="[-copyright?Copyright (c) Stardate 57000 Starfleet.]"
    USAGE+="[-license?http://www.starfleet.mil.fed/weapons-license.xml23]"
    USAGE+="[+NAME?phaser4 --- combined phaser and tricorder]"
    USAGE+="[+DESCRIPTION?The aphaser4a program combines the operation "
    USAGE+="of the aphaser3a and atricordera programs in one handy tool.]"
    USAGE+="[k:kill?Use kill setting (default).]"
    USAGE+="[l:lev*el]#[level:=2?Set the phaser level.]{
                    [level=0-2?non-lethal settings]
                    [level=3-10?lethal, use with caution]
    }"
    USAGE+="[s:stun?Stun-only.]"
    USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
    USAGE+=$'
    
    file ...
    
    '
    USAGE+=$'[+SEE ALSO?aphaser3a(1), atricordera(1)]'
    while getopts "$USAGE" optchar ...

  13. Finally, allow escapes within the strings. ]] represents a literal ] when getopts might otherwise take it to mean a closing bracket. Similarly, ?? stands for a literal ? that might otherwise start a description.

Whew! That’s a lot of stuff. However, seeing it in the order it was added helps it to make sense. Here is a summary of the items that go in the usage string, in the order that getopts requires:

  1. Identification strings for the version, author, license, and so on are the very first part. They are enclosed in square brackets and begin with a minus sign. The item name, such as author, follows the minus sign and ends at a question mark. Following the question mark is the associated information.

    The empty item indicates version information, and should be of the form as shown earlier; getopts strips out the special SCCS and RCS identification characters.

  2. Unix man page-style section headings and text come next. These are enclosed in square brackets and begin with a + sign. The section heading name ends at the ? character, and the descriptive text follows.

    Text separated by two successive newlines from the options description is appended to the short usage message.

  3. Option descriptions form the third section. The original short form as described in Chapter 6 is still allowed:

    • Use : for options that require arguments.

    • Use # for options that require numeric arguments.

    • Use :? and #? for options that allow arguments but don’t require them.

  4. Follow options by descriptive text in between [ and ]. Use := within the descriptive text to specify a default value for an option argument.

  5. Long options are matched with a short option letter by enclosing them in square brackets, separated by a colon. This replaces the single letter form.

  6. Enclose items to be italicized between two a characters. Enclose items to be emboldened between two  characters. Enclose the name of a customizing function to call between two f characters.

  7. Use { and } to enclose nested, indented option descriptions.

  8. Follow the options section with two newlines and additional text for the short options summary.

  9. Use ]] to represent a literal ] and ?? to represent a literal ?.

Here is the skeletal version of phaser4:

#! /bin/ksh

# usage: phaser4 [ options ] files
#   -k, --kill                  use kill setting (default)
#   -l n, --level n             set phaser level (default = 2)
#   -s, --stun                  use stun-only setting
#   -t [lf], --tricorder [lf]   tricorder mode, opt. scan for life form lf

USAGE=$'[-?
@(#)$Id: phaser4 (Starfleet Research and Development)'
USAGE+=$' Stardate 57234.22 $
]'
USAGE+="[-author?J. Programmer <[email protected]>]"
USAGE+="[-copyright?Copyright (c) Stardate 57000 Starfleet.]"
USAGE+="[-license?http://www.starfleet.mil.fed/weapons-license.xml23]"
USAGE+="[+NAME?phaser4 --- combined phaser and tricorder]"
USAGE+="[+DESCRIPTION?The aphaser4a program combines the operation "
USAGE+="of the aphaser3a and atricordera programs in one handy tool.]"
USAGE+="[k:kill?Use kill setting (default).]"
USAGE+="[l:lev*el]#[level:=2?Set the phaser level.]{
                [0-2?non-lethal settings]
                [3-10?lethal, use with caution]
}"
USAGE+="[s:stun?Stun-only.]"
USAGE+="[t:tricorder?Tricorder mode.]:?[life_form]"
USAGE+=$'

file ...

'
USAGE+=$'[+SEE ALSO?aphaser3a(1), atricordera(1)]'

kill=1 stun=0 level=2   # defaults
tricorder=0 phaser=1
life_form=
while getopts "$USAGE" optchar ; do
    case $optchar in
    k)  kill=1 stun=0 ;;
    s)  kill=0 stun=1 ;;
    l)  level=$OPTARG
        if ((level < 0)) ; then level=0 ; fi
        if ((level > 10)) ; then level=10 ; fi
        ;;
    t)  phaser=0 tricorder=1
        life_form=${OPTARG:-"general_unknown"}
        ;;
    esac
done

print kill=$kill
print stun=$stun
print level=$level
print phaser=$phaser
print tricorder=$tricorder
print life_form=$life_form

Here is the output from phaser4 --man:

            NAME
  phaser4 --- combined phaser and tricorder

SYNOPSIS
            phaser4 [ options ] file ...

DESCRIPTION
  The phaser4 program combines the operation of the phaser3 and tricorder
  programs in one handy tool.

OPTIONS
  -k, --kill      Use kill setting (default).
  -l, --level=level
                  Set the phaser level.
                    level=0-2
                          non-lethal settings
                    level=3-10
                          lethal, use with caution
                  The default value is 2.
  -s, --stun      Stun-only.
  -t, --tricorder[=life form]
                  Tricorder mode. The option value may be omitted.

SEE ALSO
            phaser3(1), tricorder(1)

IMPLEMENTATION
            version         phaser4 (Starfleet Research and Development) Stardate
                  57234.22
  author          J. Programmer <[email protected]>
  copyright       Copyright (c) Stardate 57000 Starfleet.
  license         http://www.starfleet.mil.fed/weapons-license.xml23


[142] No, the walls of my room are not covered with Star Trek posters. I outgrew that a long time ago, and besides, my wife wouldn’t let me anyway. ADR.

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

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