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.
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).
Option | Meaning |
-c
string
| Execute string, then exit. |
-D
|
Print all |
-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). |
Here is a summary of all built-in commands and keywords.
Name | Command/keyword | Chapter | Summary |
!
| Keyword | 5 | Invert the true/false result of the following pipeline. |
:
| Command | 7 | Do nothing (just do expansions of arguments). |
.
| Command | 4 | Read file and execute its contents in current shell. |
alias | Command | 3 | Set up shorthand for command or command line. |
bg | Command | 8 | Put job in background. |
builtin | Command |
Add or remove built-in commands; print information about them. | |
break | Command | 5 |
Exit from surrounding |
case
| Keyword | 5 | Multiway conditional construct. |
cd | Command | 1 | Change working directory. |
command | Command | 5 |
Locate built-in and external commands; find a built-in command instead of an identically named function. |
continue | Command | 4 |
Skip to next iteration of |
disown | Command | 8 |
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 | Command | 4 | Expand and print arguments (obsolete). |
exec | Command | 9 | Replace shell with given program. |
exit | Command | 5 | Exit from shell. |
export | Command | 3 | Create environment variables. |
eval | Command | 7 | Process arguments as a command line. |
false | Command | 8 |
Do nothing and exit unsuccessfully. Useful for making infinite loops. |
fg | Command | 8 | Put background job in foreground. |
for
| Keyword | 5 | Looping construct. |
function
| Keyword | 4 | Define function. |
getconf | Command |
Get system-specific information. The parameters are defined by POSIX. | |
getopts | Command | 6 | Process command-line options. |
hist | Command | 2 | Work with command history. |
if
| Keyword | 5 | Conditional construct. |
jobs | Command | 1 | List background jobs. |
kill | Command | 8 | Send signal to process. |
let | Command | 6 | Arithmetic variable assignment. |
newgrp | Command | Start new shell with new group ID (obsolete). | |
Command | 1 | Expand and print arguments on standard output. | |
printf | Command | 7 |
Expand and print arguments on standard output, using ANSI C printf(3) format specifiers. |
pwd | Command | 1 | Print working directory. |
read | Command | 7 | Read a line from standard input. |
readonly | Command | 6 | Make variables read-only (unassignable). |
return | Command | 5 | Return from surrounding function or script. |
select
| Keyword | 5 | Menu generation construct. |
set | Command | 3 | Set options. |
shift | Command | 6 | Shift command-line arguments. |
sleep | Command | 8 | Suspend execution for the given number of seconds. |
test | Command | 5 |
Old version of conditional test program.
Use |
time
| Keyword |
Run command and print execution times. By itself, prints cumulative times for the shell and all children. | |
trap | Command | 8 | Set up signal-catching routine. |
true | Command | 8 |
Do nothing and exit successfully. Useful for making infinite loops. |
typeset | Command | 6 | Set special characteristics of variables and functions. |
ulimit | Command | 10 | Set/show process resource limits. |
umask | Command | 10 | Set/show file permission mask. |
unalias | Command | 3 | Remove alias definitions. |
unset | Command | 3 | Remove definitions of variables or functions. |
until
| Keyword | 5 | Looping construct. |
wait | Command | 8 | Wait for background job(s) to finish. |
whence | Command | 3 | Identify source of command. |
while
| Keyword | 5 | Looping 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.
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.
Name | Chapter | Full 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'
|
Here is a summary of all built-in shell variables:
Variable | Chapter | Meaning |
#
| 4 | Number 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. | |
?
| 5 | Exit status of previous command. |
$
| 8 | Process ID of shell process. |
_ (underscore) | 3 |
Inside |
!
| 8 | Process 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
| 3 | List of directories for cd command to search. |
COLUMNS
| 3 |
Width of display in columns (for editing modes and
|
EDITOR
| 2 |
Used to set editing mode; also used by mail
and other programs.
Overriden by |
ENV
| 3 |
Name of file to run as environment file when shell is invoked. |
FCEDIT
| 2 | Obsolete default editor for hist command. |
FIGNORE
| 1 | Pattern for files to ignore during pattern expansion. |
FPATH
| 4 | Search path for autoloaded functions. |
HISTCMD
| 2 | Number of current command in command history. |
HISTEDIT
| 2 | Default editor for hist command. |
HISTFILE
| 2 | Name of command history file. |
HISTSIZE
| 2 | Number of lines kept in history file. |
HOME
| 3 | Home (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_ALL
|
Name of current locale; overrides | |
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
| 9 | Number of line in script or function that just ran. |
LINES
| 3 | Height of display in lines (for select command). |
MAIL
| 3 | Name of file to check for new mail. |
MAILCHECK
| 3 | How often (in seconds) to check for new mail. |
MAILPATH
| 3 |
List of file names to check for new mail, if |
OLDPWD
| 3 | Previous working directory. |
OPTARG
| 6 | Argument to option being processed by getopts. |
OPTIND
| 6 | Number of first argument after options. |
PATH
| 3 | Search path for commands. |
PPID
| 8 | Process ID of parent process. |
PS1
| 3 | Primary command prompt string. |
PS2
| 3 | Prompt string for line continuations. |
PS3
| 5 | Prompt string for select command. |
PS4
| 9 | Prompt string for xtrace option. |
PWD
| 3 | Current working directory. |
RANDOM
| 9 |
Random number between 0 and 32767 (215-1). |
REPLY
| 5, 7 |
User’s response to |
SECONDS
| 3 | Number 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 |
VISUAL
| 2 | Used to set editing mode. |
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.
Operator | True if... |
-a
file
|
file exists. (Obsolete. |
-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; |
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.
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.
Option | Abbrev | Meaning |
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 |
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:
Option | Meaning |
set -A ... | Indexed array assignment. |
set -s
| Sort the positional parameters. |
set -t
|
Read and execute one command, and then exit. (Obsolete.) |
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
.
Option | Meaning |
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. |
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:
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 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 ...
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
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
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.
Operator | Meaning | Associativity |
++
--
| Increment and decrement, prefix and postfix | Left to right |
+
-
!
~
| Unary plus and minus; logical and bitwise negation | Right to left |
**
|
Exponentiation[a] | Right to left |
*
/
%
| Multiplication, division, and remainder | Left to right |
+
-
| Addition and subtraction | Left to right |
<<
>>
| Bit-shift left and right | Left to right |
< <= > >=
| Comparisons | Left to right |
==
!=
| Equal and not equal | Left to right |
&
| Bitwise and | Left to right |
^
| Bitwise exclusive-or | Left to right |
|
| Bitwise or | Left to right |
&&
| Logical and (short circuit) | Left to right |
||
| Logical or (short circuit) | Left to right |
?:
| Conditional expression | Right to left |
| Assignment operators | Right to left |
,
| Sequential evaluation | Left to right |
[a]
ksh93m and newer.
The |
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.
Command | Meaning |
CTRL-A | Move to beginning of line |
CTRL-B | Move backward one character without deleting |
CTRL-C | Capitalize character after point |
CTRL-D | Delete one character forward |
CTRL-E | Move to end of line |
CTRL-F | Move forward one character |
CTRL-I (TAB) |
Do filename completion on current word (starting with ksh93h) |
CTRL-J | Same as ENTER. |
CTRL-K | Delete (“kill”) forward to end of line |
CTRL-L | Redisplay the line |
CTRL-M | Same as ENTER |
CTRL-N | Next line |
CTRL-O | Same as ENTER, then display next line in history file |
CTRL-P | Previous line |
CTRL-R | Search backward |
CTRL-T | Transpose the two characters on either side of point |
CTRL-U | Repeat the following command four times |
CTRL-V | Print 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-X | Exchange point and mark |
CTRL-Y | Retrieve (“yank”) last item deleted |
CTRL-] x
| Search forward for x, where x is any character |
CTRL-@ | Set mark at point |
DEL | Delete one character backward |
CTRL-[ | Same as ESC (most keyboards) |
ESC b | Move one word backward |
ESC c | Change word after point to all capital letters |
ESC d | Delete one word forward |
ESC f | Move one word forward |
ESC h | Delete one word backward |
ESC l | Change word after point to all lowercase letters |
ESC p | Save characters between point and mark as if deleted |
ESC CTRL-H | Delete one word backward |
ESC CTRL-] x
|
Search backward for x, where x is any character |
ESC SPACE | Set mark at point |
ESC # | Insert line in history file for future editing |
ESC DEL | Delete 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 ESC | Do 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 [ A | Previous line (ksh93h and newer) |
ESC [ B | Next line (ksh93h and newer) |
ESC [ C | Move forward one character (ksh93h and newer) |
ESC [ D | Move backward one character (without deleting) (ksh93h and newer) |
ESC [ H | Move to beginning of line (ksh93h and newer) |
ESC [ Y | Move to end of line (ksh93h and newer) |
Kill |
The stty(1) kill character, often CTRL-U or
|
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.
Command | Meaning |
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
|
\
| 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
|
CTRL-J | Same as ENTER |
CTRL-L |
Start a new line and redraw the current line on it |
CTRL-M | Same as ENTER |
CTRL-V | Print the version of the Korn shell |
#
|
Prepend |
@
x
| Insert expansion of alias _x as command mode input |
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.
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 ...
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 ...
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 ...
Add ?
after the :
to
indicate an optional argument:
USAGE="kl#[level:=2]st:?[life_form]" while getopts "$USAGE" optchar ...
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.
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 ...
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.
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+=$'\n\nfile ...\n\n' Use ANSI C string for \n character
USAGE+="[+SEE ALSO?phaser3(1), tricorder(1)]"
while getopts "$USAGE" optchar ...
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 \b
:
USAGE="[+NAME?phaser4 --- combined phaser and tricorder]" USAGE+="[+DESCRIPTION?The \aphaser4\a program combines the operation " USAGE+="of the \aphaser3\a and \atricorder\a 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+=$'\n\nfile ...\n\n' USAGE+=$'[+SEE ALSO?\aphaser3\a(1), \atricorder\a(1)]' while getopts "$USAGE" optchar ...
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).
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 \aphaser4\a program combines the operation "
USAGE+="of the \aphaser3\a and \atricorder\a 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+=$'\n\nfile ...\n\n'
USAGE+=$'[+SEE ALSO?\aphaser3\a(1), \atricorder\a(1)]'
while getopts "$USAGE" optchar ...
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=$'[-?\n@(#)$Id: phaser4 (Starfleet Research and Development)' USAGE+=$' Stardate 57234.22 $\n]' USAGE+="[-author?J. Programmer <J.Prog@r-d.starfleet.mil.fed>]" 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 \aphaser4\a program combines the operation " USAGE+="of the \aphaser3\a and \atricorder\a 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+=$'\n\nfile ...\n\n' USAGE+=$'[+SEE ALSO?\aphaser3\a(1), \atricorder\a(1)]' while getopts "$USAGE" optchar ...
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:
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.
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.
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.
Follow options by descriptive text in between [
and ]
.
Use :=
within the descriptive text to specify a default value for an option argument.
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.
Enclose items to be italicized between two \a
characters.
Enclose items to be emboldened between two \b
characters.
Enclose the name of a customizing function to call between two \f
characters.
Use {
and }
to enclose
nested, indented option descriptions.
Follow the options section with two newlines and additional text for the short options summary.
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=$'[-?\n@(#)$Id: phaser4 (Starfleet Research and Development)' USAGE+=$' Stardate 57234.22 $\n]' USAGE+="[-author?J. Programmer <J.Prog@r-d.starfleet.mil.fed>]" 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 \aphaser4\a program combines the operation " USAGE+="of the \aphaser3\a and \atricorder\a 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+=$'\n\nfile ...\n\n' USAGE+=$'[+SEE ALSO?\aphaser3\a(1), \atricorder\a(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 tricorderSYNOPSIS
phaser4
[options
] file ...DESCRIPTION
Thephaser4
program combines the operation of thephaser3
andtricorder
programs in one handy tool.OPTIONS
-k
, --kill
Use kill setting (default). -l
, --level
=level
Set the phaser level.level=0-2
non-lethal settingslevel=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.22author
J. Programmer <J.Prog@r-d.starfleet.mil.fed>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.