Functions
*********

Shell functions are defined with the function reserved word or the
special syntax `FUNCNAME ()'.  Shell functions are read in and stored
internally.  Alias names are resolved when the function is read.
Functions are executed like commands with the arguments passed as
positional parameters.  (See Command Execution.)

Functions execute in the same process as the caller and share all files
and present working directory with the caller.  A trap on EXIT set
inside a function is executed after the function completes in the
environment of the caller.

The return builtin is used to return from function calls.

Function identifiers can be listed with the functions builtin.
Functions can be undefined with the unfunction builtin.

Autoloading Functions
=====================

A function can be marked as _undefined_ using the autoload builtin (or
`functions -u' or `typeset -fu').  Such a function has no body.  When
the function is first executed, the shell searches for its definition
using the elements of the fpath variable.  Thus to define functions for
autoloading, a typical sequence is:

     fpath=(~/myfuncs $fpath)
     autoload myfunc1 myfunc2 ...

The usual alias expansion during reading will be suppressed if the
autoload builtin or its equivalent is given the option -U. This is
recommended for the use of functions supplied with the zsh distribution.
Note that for functions precompiled with the zcompile builtin command
the flag -U must be provided when the .zwc file is created, as the
corresponding information is compiled into the latter.

For each ELEMENT in fpath, the shell looks for three possible files,
the newest of which is used to load the definition for the function:

ELEMENT.zwc
     A file created with the zcompile builtin command, which is
     expected to contain the definitions for all functions in the
     directory named ELEMENT.  The file is treated in the same manner
     as a directory containing files for functions and is searched for
     the definition of the function.   If the definition is not found,
     the search for a definition proceeds with the other two
     possibilities described below.

     If ELEMENT already includes a .zwc extension (i.e. the extension
     was explicitly given by the user), ELEMENT is searched for the
     definition of the function without comparing its age to that of
     other files; in fact, there does not need to be any directory
     named ELEMENT without the suffix.  Thus including an element such
     as `/usr/local/funcs.zwc' in fpath will speed up the search for
     functions, with the disadvantage that functions included must be
     explicitly recompiled by hand before the shell notices any changes.

ELEMENT/FUNCTION.zwc
     A file created with zcompile, which is expected to contain the
     definition for FUNCTION.  It may include other function definitions
     as well, but those are neither loaded nor executed; a file found
     in this way is searched _only_ for the definition of FUNCTION.

ELEMENT/FUNCTION
     A file of zsh command text, taken to be the definition for
     FUNCTION.

In summary, the order of searching is, first, in the _parents of_
directories in fpath for the newer of either a compiled directory or a
directory in fpath; second, if more than one of these contains a
definition for the function that is sought, the leftmost in the fpath
is chosen; and third, within a directory, the newer of either a compiled
function or an ordinary function definition is used.

If the KSH_AUTOLOAD option is set, or the file contains only a simple
definition of the function, the file's contents will be executed.  This
will normally define the function in question, but may also perform
initialization, which is executed in the context of the function
execution, and may therefore define local parameters.  It is an error
if the function is not defined by loading the file.

Otherwise, the function body (with no surrounding `FUNCNAME() {...}')
is taken to be the complete contents of the file.  This form allows the
file to be used directly as an executable shell script.  If processing
of the file results in the function being re-defined, the function
itself is not re-executed.  To force the shell to perform
initialization and then call the function defined, the file should
contain initialization code (which will be executed then discarded) in
addition to a complete function definition (which will be retained for
subsequent calls to the function), and a call to the shell function,
including any arguments, at the end.

For example, suppose the autoload file func contains

     func() { print This is func; }
     print func is initialized

then `func; func' with KSH_AUTOLOAD set will produce both messages on
the first call, but only the message `This is func' on the second and
subsequent calls.  Without KSH_AUTOLOAD set, it will produce the
initialization message on the first call, and the other message on the
second and subsequent calls.

It is also possible to create a function that is not marked as
autoloaded, but which loads its own definition by searching fpath, by
using `autoload -X' within a shell function.  For example, the
following are equivalent:

     myfunc() {
       autoload -X
     }
     myfunc args...

and

     unfunction myfunc   # if myfunc was defined
     autoload myfunc
     myfunc args...

In fact, the functions command outputs `builtin autoload -X' as the
body of an autoloaded function.  A true autoloaded function can be
identified by the presence of the comment `# undefined' in the body,
because all comments are discarded from defined functions.  This is done
so that

     eval "$(functions)"

produces a reasonable result.

To load the definition of an autoloaded function myfunc without
executing myfunc, use:

     autoload +X myfunc

Special Functions
=================

The following functions, if defined, have special meaning to the shell:

chpwd
     Executed whenever the current working directory is changed.

periodic
     If the parameter PERIOD is set, this function is executed every
     $PERIOD seconds, just before a prompt.

precmd
     Executed before each prompt.

preexec
     Executed just after a command has been read and is about to be
     executed.  If the history mechanism is active (and the line was not
     discarded from the history buffer), the string that the user typed
     is passed as the first argument, otherwise it is an empty string.
     The actual command that will be executed (including expanded
     aliases) is passed in two different forms: the second argument is
     a single-line, size-limited version of the command (with things
     like function bodies elided); the third argument contains the full
     text what what is being executed.

TRAPNAL
     If defined and non-null, this function will be executed whenever
     the shell catches a signal SIGNAL, where NAL is a signal name as
     specified for the kill builtin.  The signal number will be passed
     as the first parameter to the function.

     If a function of this form is defined and null, the shell and
     processes spawned by it will ignore SIGNAL.

TRAPDEBUG
     Executed after each command.

TRAPEXIT
     Executed when the shell exits, or when the current function exits
     if defined inside a function.

TRAPZERR
     Executed whenever a command has a non-zero exit status.  However,
     the function is not executed if the command occurred in a sublist
     followed by `&&' or `||'; only the final command in a sublist of
     this type causes the trap to be executed.

The functions beginning `TRAP' may alternatively be defined with the
trap builtin:  this may be preferable for some uses, as they are then
run in the environment of the calling process, rather than in their own
function environment.  Apart from the difference in calling procedure
and the fact that the function form appears in lists of functions, the
forms

     TRAPNAL() {
      # code
     }

and

     trap '
      # code
     ' NAL

are equivalent.

Jobs & Signals
**************

Jobs
====

If the MONITOR option is set, an interactive shell associates a _job_
with each pipeline.  It keeps a table of current jobs, printed by the
jobs command, and assigns them small integer numbers.  When a job is
started asynchronously with `&', the shell prints a line which looks
like:

     [1] 1234

indicating that the job which was started asynchronously was job number
1 and had one (top-level) process, whose process ID was 1234.

If a job is started with `&|' or `&!', then that job is immediately
disowned.  After startup, it does not have a place in the job table,
and is not subject to the job control features described here.

If you are running a job and wish to do something else you may hit the
key ^Z (control-Z) which sends a TSTP signal to the current job:  this
key may be redefined by the susp option of the external stty command.
The shell will then normally indicate that the job has been `suspended',
and print another prompt.  You can then manipulate the state of this
job, putting it in the background with the bg command, or run some other
commands and then eventually bring the job back into the foreground with
the foreground command fg.  A ^Z takes effect immediately and is like
an interrupt in that pending output and unread input are discarded when
it is typed.

A job being run in the background will suspend if it tries to read from
the terminal.  Background jobs are normally allowed to produce output,
but this can be disabled by giving the command `stty tostop'.  If you
set this tty option, then background jobs will suspend when they try to
produce output like they do when they try to read input.

When a command is suspended and continued later with the fg or wait
builtins, zsh restores tty modes that were in effect when it was
suspended.  This (intentionally) does not apply if the command is
continued via `kill -CONT', nor when it is continued with bg.

There are several ways to refer to jobs in the shell.  A job can be
referred to by the process ID of any process of the job or by one of
the following:

%NUMBER
     The job with the given number.

%STRING
     Any job whose command line begins with STRING.

%?STRING
     Any job whose command line contains STRING.

%%
     Current job.

%+
     Equivalent to `%%'.

%-
     Previous job.

The shell learns immediately whenever a process changes state.  It
normally informs you whenever a job becomes blocked so that no further
progress is possible.  If the NOTIFY option is not set, it waits until
just before it prints a prompt before it informs you.

When the monitor mode is on, each background job that completes
triggers any trap set for CHLD.

When you try to leave the shell while jobs are running or suspended,
you will be warned that `You have suspended (running) jobs'.  You may
use the jobs command to see what they are.  If you do this or
immediately try to exit again, the shell will not warn you a second
time; the suspended jobs will be terminated, and the running jobs will
be sent a SIGHUP signal, if the HUP option is set.

To avoid having the shell terminate the running jobs, either use the
`nohup' command (see man page nohup(1)) or the disown builtin.

Signals
=======

The INT and QUIT signals for an invoked command are ignored if the
command is followed by `&' and the MONITOR option is not active.
Otherwise, signals have the values inherited by the shell from its
parent (but see the TRAPNAL special functions in Functions).

Arithmetic Evaluation
*********************

The shell can perform integer and floating point arithmetic, either
using the builtin let, or via a substitution of the form $((...)).  For
integers, the shell is usually compiled to use 8-byte precision where
this is available, otherwise precision is 4 bytes.  This can be tested,
for example, by giving the command `print - $(( 12345678901 ))'; if the
number appears unchanged, the precision is at least 8 bytes.  Floating
point arithmetic is always double precision.

The let builtin command takes arithmetic expressions as arguments; each
is evaluated separately.  Since many of the arithmetic operators, as
well as spaces, require quoting, an alternative form is provided: for
any command which begins with a `((', all the characters until a
matching `))' are treated as a quoted expression and arithmetic
expansion performed as for an argument of let.  More precisely,
`((...))' is equivalent to `let "..."'.  For example, the following
statement

     (( val = 2 + 1 ))

is equivalent to

     let "val = 2 + 1"

both assigning the value 3 to the shell variable var and returning a
zero status.

Integers can be in bases other than 10.  A leading `0x' or `0X' denotes
hexadecimal.  Integers may also be of the form `BASE#N', where BASE is
a decimal number between two and thirty-six representing the arithmetic
base and N is a number in that base (for example, `16#ff' is 255 in
hexadecimal).  The BASE# may also be omitted, in which case base 10 is
used.  For backwards compatibility the form `[BASE]N' is also accepted.

It is also possible to specify a base to be used for output in the form
`[#BASE]', for example `[#16]'.  This is used when outputting
arithmetical substitutions or when assigning to scalar parameters, but
an explicitly defined integer or floating point parameter will not be
affected.  If an integer variable is implicitly defined by an
arithmetic expression, any base specified in this way will be set as the
variable's output arithmetic base as if the option `-i BASE' to the
typeset builtin had been used.  The expression has no precedence and if
it occurs more than once in a mathematical expression, the last
encountered is used.  For clarity it is recommended that it appear at
the beginning of an expression.  As an example:

     typeset -i 16 y
     print $(( [#8] x = 32, y = 32 ))
     print $x $y

outputs first `8#40', the rightmost value in the given output base, and
then `8#40 16#20', because y has been explicitly declared to have
output base 16, while x (assuming it does not already exist) is
implicitly typed by the arithmetic evaluation, where it acquires the
output base 8.

When an output base is specified using the `[#BASE]' syntax, an
appropriate base prefix will be output if necessary, so that the value
output is valid syntax for input.  If the # is doubled, for example
`[##16]', then no base prefix is output.

Floating point constants are recognized by the presence of a decimal
point or an exponent.  The decimal point may be the first character of
the constant, but the exponent character e or E may not, as it will be
taken for a parameter name.

An arithmetic expression uses nearly the same syntax, precedence, and
associativity of expressions in C.  The following operators are
supported (listed in decreasing order of precedence):

+ - ! ~ ++ -
     unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement

<< >>
     bitwise shift left, right

&
     bitwise AND

^
     bitwise XOR

|
     bitwise OR

**
     exponentiation

* / %
     multiplication, division, modulus (remainder)

+ -
     addition, subtraction

< > <= >=
     comparison

== !=
     equality and inequality

&&
     logical AND

|| ^^
     logical OR, XOR

? :
     ternary operator

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

,
     comma operator

The operators `&&', `||', `&&=', and `||=' are short-circuiting, and
only one of the latter two expressions in a ternary operator is
evaluated.  Note the precedence of the bitwise AND, OR, and XOR
operators.

Mathematical functions can be called with the syntax `FUNC(ARGS)',
where the function decides if the ARGS is used as a string or a
comma-separated list of arithmetic expressions. The shell currently
defines no mathematical functions by default, but the module
zsh/mathfunc may be loaded with the zmodload builtin to provide
standard floating point mathematical functions.

An expression of the form `##X' where X is any character sequence such
as `a', `^A', or `\M-\C-x' gives the ASCII value of this character and
an expression of the form `#FOO' gives the ASCII value of the first
character of the value of the parameter FOO.  Note that this is
different from the expression `$#FOO', a standard parameter
substitution which gives the length of the parameter FOO.  `#\' is
accepted instead of `##', but its use is deprecated.

Named parameters and subscripted arrays can be referenced by name
within an arithmetic expression without using the parameter expansion
syntax.  For example,

     ((val2 = val1 * 2))

assigns twice the value of $val1 to the parameter named val2.

An internal integer representation of a named parameter can be
specified with the integer builtin.  Arithmetic evaluation is performed
on the value of each assignment to a named parameter declared integer
in this manner.  Assigning a floating point number to an integer
results in rounding down to the next integer.

Likewise, floating point numbers can be declared with the float
builtin; there are two types, differing only in their output format, as
described for the typeset builtin.  The output format can be bypassed
by using arithmetic substitution instead of the parameter substitution,
i.e. `${FLOAT}' uses the defined format, but `$((FLOAT))' uses a
generic floating point format.

Promotion of integer to floating point values is performed where
necessary.  In addition, if any operator which requires an integer
(`~', `&', `|', `^', `%', `<<', `>>' and their equivalents with
assignment) is given a floating point argument, it will be silently
rounded down to the next integer.

Scalar variables can hold integer or floating point values at different
times; there is no memory of the numeric type in this case.

If a variable is first assigned in a numeric context without previously
being declared, it will be implicitly typed as integer or float and
retain that type either until the type is explicitly changed or until
the end of the scope.  This can have unforeseen consequences.  For
example, in the loop

     for (( f = 0; f < 1; f += 0.1 )); do
     # use $f
     done

if f has not already been declared, the first assignment will cause it
to be created as an integer, and consequently the operation `f += 0.1'
will always cause the result to be truncated to zero, so that the loop
will fail.  A simple fix would be to turn the initialization into `f =
0.0'.  It is therefore best to declare numeric variables with explicit
types.

Conditional Expressions
***********************

A _conditional expression_ is used with the [[ compound command to test
attributes of files and to compare strings.  Each expression can be
constructed from one or more of the following unary or binary
expressions:

-a FILE
     true if FILE exists.

-b FILE
     true if FILE exists and is a block special file.

-c FILE
     true if FILE exists and is a character special file.

-d FILE
     true if FILE exists and is a directory.

-e FILE
     true if FILE exists.

-f FILE
     true if FILE exists and is a regular file.

-g FILE
     true if FILE exists and has its setgid bit set.

-h FILE
     true if FILE exists and is a symbolic link.

-k FILE
     true if FILE exists and has its sticky bit set.

-n STRING
     true if length of STRING is non-zero.

-o OPTION
     true if option named OPTION is on.  OPTION may be a single
     character, in which case it is a single letter option name.  (See
     Specifying Options.)

-p FILE
     true if FILE exists and is a FIFO special file (named pipe).

-r FILE
     true if FILE exists and is readable by current process.

-s FILE
     true if FILE exists and has size greater than zero.

-t FD
     true if file descriptor number FD is open and associated with a
     terminal device.  (note: FD is not optional)

-u FILE
     true if FILE exists and has its setuid bit set.

-w FILE
     true if FILE exists and is writable by current process.

-x FILE
     true if FILE exists and is executable by current process.  If FILE
     exists and is a directory, then the current process has permission
     to search in the directory.

-z STRING
     true if length of STRING is zero.

-L FILE
     true if FILE exists and is a symbolic link.

-O FILE
     true if FILE exists and is owned by the effective user ID of this
     process.

-G FILE
     true if FILE exists and its group matches the effective group ID
     of this process.

-S FILE
     true if FILE exists and is a socket.

-N FILE
     true if FILE exists and its access time is not newer than its
     modification time.

FILE1 -nt FILE2
     true if FILE1 exists and is newer than FILE2.

FILE1 -ot FILE2
     true if FILE1 exists and is older than FILE2.

FILE1 -ef FILE2
     true if FILE1 and FILE2 exist and refer to the same file.

STRING = PATTERN
STRING == PATTERN
     true if STRING matches PATTERN.  The `==' form is the preferred
     one.  The `=' form is for backward compatibility and should be
     considered obsolete.

STRING != PATTERN
     true if STRING does not match PATTERN.

STRING1 < STRING2
     true if STRING1 comes before STRING2 based on ASCII value of their
     characters.

STRING1 > STRING2
     true if STRING1 comes after STRING2 based on ASCII value of their
     characters.

EXP1 -eq EXP2
     true if EXP1 is numerically equal to EXP2.

EXP1 -ne EXP2
     true if EXP1 is numerically not equal to EXP2.

EXP1 -lt EXP2
     true if EXP1 is numerically less than EXP2.

EXP1 -gt EXP2
     true if EXP1 is numerically greater than EXP2.

EXP1 -le EXP2
     true if EXP1 is numerically less than or equal to EXP2.

EXP1 -ge EXP2
     true if EXP1 is numerically greater than or equal to EXP2.

( EXP )
     true if EXP is true.

! EXP
     true if EXP is false.

EXP1 && EXP2
     true if EXP1 and EXP2 are both true.

EXP1 || EXP2
     true if either EXP1 or EXP2 is true.

Normal shell expansion is performed on the FILE, STRING and PATTERN
arguments, but the result of each expansion is constrained to be a
single word, similar to the effect of double quotes.  However, pattern
metacharacters are active for the PATTERN arguments; the patterns are
the same as those used for filename generation, see Filename Generation,
but there is no special behaviour of `/' nor initial
dots, and no glob qualifiers are allowed.

In each of the above expressions, if FILE is of the form `/dev/fd/N',
where N is an integer, then the test applied to the open file whose
descriptor number is N, even if the underlying system does not support
the /dev/fd directory.

In the forms which do numeric comparison, the expressions EXP undergo
arithmetic expansion as if they were enclosed in $((...)).

For example, the following:

     [[ ( -f foo || -f bar ) && $report = y* ]] && print File exists.

tests if either file foo or file bar exists, and if so, if the value of
the parameter report begins with `y'; if the complete condition is
true, the message `File exists.' is printed.

Prompt Expansion
****************

Prompt sequences undergo a special form of expansion.  This type of
expansion is also available using the -P option to the print builtin.

If the PROMPT_SUBST option is set, the prompt string is first subjected
to _parameter expansion_, _command substitution_ and _arithmetic
expansion_.  See Expansion.

Certain escape sequences may be recognised in the prompt string.

If the PROMPT_BANG option is set, a `!' in the prompt is replaced by
the current history event number.  A literal `!' may then be
represented as `!!'.

If the PROMPT_PERCENT option is set, certain escape sequences that
start with `%' are expanded.  Some escapes take an optional integer
argument, which should appear between the `%' and the next character of
the sequence.  The following escape sequences are recognized:

%%
     A `%'.

%)
     A `)'.

%d
%/
     Present working directory ($PWD).  If an integer follows the `%',
     it specifies a number of trailing components of $PWD to show; zero
     means the whole path.  A negative integer specifies leading
     components, i.e. %-1d specifies the first component.

%~
     As %d and %/, but if $PWD has a named directory as its prefix,
     that part is replaced by a `~' followed by the name of the
     directory.  If it starts with $HOME, that part is replaced by a
     `~'.

%h
%!
     Current history event number.

%L
     The current value of $SHLVL.

%M
     The full machine hostname.

%m
     The hostname up to the first `.'.  An integer may follow the `%'
     to specify how many components of the hostname are desired.  With
     a negative integer, trailing components of the hostname are shown.

%S (%s)
     Start (stop) standout mode.

%U (%u)
     Start (stop) underline mode.

%B (%b)
     Start (stop) boldface mode.

%t
%@
     Current time of day, in 12-hour, am/pm format.

%T
     Current time of day, in 24-hour format.

%*
     Current time of day in 24-hour format, with seconds.

%n
     $USERNAME.

%N
     The name of the script, sourced file, or shell function that zsh is
     currently executing, whichever was started most recently.  If
     there is none, this is equivalent to the parameter $0.  An integer
     may follow the `%' to specify a number of trailing path components
     to show; zero means the full path.  A negative integer specifies
     leading components.

%i
     The line number currently being executed in the script, sourced
     file, or shell function given by %N.  This is most useful for
     debugging as part of $PS4.

%w
     The date in DAY-DD format.

%W
     The date in MM/DD/YY format.

%D
     The date in YY-MM-DD format.

%D{STRING}
     STRING is formatted using the strftime function.  See man page
     strftime(3) for more details.  Three additional codes are
     available:  %f prints the day of the month, like %e but without
     any preceding space if the day is a single digit, and %K/%L
     correspond to %k/%l for the hour of the day (24/12 hour clock) in
     the same way.

%l
     The line (tty) the user is logged in on without /dev/ prefix.  If
     name starts with /dev/tty this is stripped.

%y
     The line (tty) the user is logged in on without /dev/ prefix.  It
     does not treat /dev/tty* specially.

%?
     The return code of the last command executed just before the
     prompt.

%_
     The status of the parser, i.e. the shell constructs (like `if' and
     `for') that have been started on the command line. If given an
     integer number that many strings will be printed; zero or negative
     or no integer means print as many as there are.  This is most
     useful in prompts PS2 for continuation lines and PS4 for debugging
     with the XTRACE option; in the latter case it will also work
     non-interactively.

%E
     Clears to end of line.

%#
     A `#' if the shell is running with privileges, a `%' if not.
     Equivalent to `%(!.#.%%)'.  The definition of `privileged', for
     these purposes, is that either the effective user ID is zero, or,
     if POSIX.1e capabilities are supported, that at least one
     capability is raised in either the Effective or Inheritable
     capability vectors.

%v
     The value of the first element of the psvar array parameter.
     Following the `%' with an integer gives that element of the array.
     Negative integers count from the end of the array.

%{...%}
     Include a string as a literal escape sequence.  The string within
     the braces should not change the cursor position.  Brace pairs can
     nest.

%(X.TRUE-TEXT.FALSE-TEXT)
     Specifies a ternary expression.  The character following the X is
     arbitrary; the same character is used to separate the text for the
     `true' result from that for the `false' result.  This separator
     may not appear in the TRUE-TEXT, except as part of a %-escape
     sequence.  A `)' may appear in the FALSE-TEXT as `%)'.  TRUE-TEXT
     and FALSE-TEXT may both contain arbitrarily-nested escape
     sequences, including further ternary expressions.

     The left parenthesis may be preceded or followed by a positive
     integer N, which defaults to zero.  A negative integer will be
     multiplied by -1.  The test character X may be any of the
     following:

    c
    .
    ~
          True if the current path, with prefix replacement, has at
          least N elements.

    /
    C
          True if the current absolute path has at least N elements.

    t
          True if the time in minutes is equal to N.

    T
          True if the time in hours is equal to N.

    d
          True if the day of the month is equal to N.

    D
          True if the month is equal to N (January = 0).

    w
          True if the day of the week is equal to N (Sunday = 0).

    ?
          True if the exit status of the last command was N.

    #
          True if the effective uid of the current process is N.

    g
          True if the effective gid of the current process is N.

    l
          True if at least N characters have already been printed on
          the current line.

    L
          True if the SHLVL parameter is at least N.

    S
          True if the SECONDS parameter is at least N.

    v
          True if the array psvar has at least N elements.

    _
          True if at least N shell constructs were started.

    !
          True if the shell is running with privileges.

%<STRING<
%>STRING>
%[XSTRING]
     Specifies truncation behaviour for the remainder of the prompt
     string.  The third, deprecated, form is equivalent to `%XSTRINGX',
     i.e. X may be `<' or `>'.  The numeric argument, which in the
     third form may appear immediately after the `[', specifies the
     maximum permitted length of the various strings that can be
     displayed in the prompt.  The STRING will be displayed in place of
     the truncated portion of any string; note this does not undergo
     prompt expansion.

     The forms with `<' truncate at the left of the string, and the
     forms with `>' truncate at the right of the string.  For example,
     if the current directory is `/home/pike', the prompt `%8<..<%/'
     will expand to `..e/pike'.  In this string, the terminating
     character (`<', `>' or `]'), or in fact any character, may be
     quoted by a preceding `\'; note when using print -P, however, that
     this must be doubled as the string is also subject to standard
     print processing, in addition to any backslashes removed by a
     double quoted string:  the worst case is therefore `print -P
     "%<\\\\<<..."'.

     If the STRING is longer than the specified truncation length, it
     will appear in full, completely replacing the truncated string.

     The part of the prompt string to be truncated runs to the end of
     the string, or to the end of the next enclosing group of the `%('
     construct, or to the next truncation encountered at the same
     grouping level (i.e. truncations inside a `%(' are separate), which
     ever comes first.  In particular, a truncation with argument zero
     (e.g. `%<<') marks the end of the range of the string to be
     truncated while turning off truncation from there on. For example,
     the prompt '%10<...<%~%<<%# ' will print a truncated
     representation of the current directory, followed by a `%' or `#',
     followed by a space.  Without the `%<<', those two characters
     would be included in the string to be truncated.

%c
%.
%C
     Trailing component of $PWD.  An integer may follow the `%' to get
     more than one component.  Unless `%C' is used, tilde contraction
     is performed first.  These are deprecated as %c and %C are
     equivalent to %1~ and %1/, respectively, while explicit positive
     integers have the same effect as for the latter two sequences.

Expansion
*********

The following types of expansions are performed in the indicated order
in five steps:

_History Expansion_
     This is performed only in interactive shells.

_Alias Expansion_
     Aliases are expanded immediately before the command line is parsed
     as explained in Aliasing.

_Process Substitution_
_Parameter Expansion_
_Command Substitution_
_Arithmetic Expansion_
_Brace Expansion_
     These five are performed in one step in left-to-right fashion.
     After these expansions, all unquoted occurrences of the characters
     `\', `'' and `"' are removed.

_Filename Expansion_
     If the SH_FILE_EXPANSION option is set, the order of expansion is
     modified for compatibility with `sh' and `ksh'.  In that case
     _filename expansion_ is performed immediately after _alias
     expansion_, preceding the set of five expansions mentioned above.

_Filename Generation_
     This expansion, commonly referred to as `globbing', is always done
     last.

The following sections explain the types of expansion in detail.

History Expansion
=================

History expansion allows you to use words from previous command lines
in the command line you are typing.  This simplifies spelling
corrections and the repetition of complicated commands or arguments.
Immediately before execution, each command is saved in the history list,
the size of which is controlled by the HISTSIZE parameter.  The one
most recent command is always retained in any case.  Each saved command
in the history list is called a history _event_ and is assigned a
number, beginning with 1 (one) when the shell starts up.  The history
number that you may see in your prompt (see Prompt Expansion)
is the number that is to be assigned to the _next_ command.

Overview
--------

A history expansion begins with the first character of the histchars
parameter, which is `!' by default, and may occur anywhere on the
command line; history expansions do not nest.  The `!' can be escaped
with `\' or can be enclosed between a pair of single quotes ('') to
suppress its special meaning.  Double quotes will _not_ work for this.
Following this history character is an optional event designator (see
Event Designators) and then an optional word designator (see Word Designators);
if neither of these designators is present, no history
expansion occurs.

Input lines containing history expansions are echoed after being
expanded, but before any other expansions take place and before the
command is executed.  It is this expanded form that is recorded as the
history event for later references.

By default, a history reference with no event designator refers to the
same event as any preceding history reference on that command line; if
it is the only history reference in a command, it refers to the previous
command.  However, if the option CSH_JUNKIE_HISTORY is set, then every
history reference with no event specification _always_ refers to the
previous command.

For example, `!' is the event designator for the previous command, so
`!!:1' always refers to the first word of the previous command, and
`!!$' always refers to the last word of the previous command.  With
CSH_JUNKIE_HISTORY set, then `!:1' and `!$' function in the same manner
as `!!:1' and `!!$', respectively.  Conversely, if CSH_JUNKIE_HISTORY
is unset, then `!:1' and `!$' refer to the first and last words,
respectively, of the same event referenced by the nearest other history
reference preceding them on the current command line, or to the
previous command if there is no preceding reference.

The character sequence `^FOO^BAR' (where `^' is actually the second
character of the histchars parameter) repeats the last command,
replacing the string FOO with BAR.  More precisely, the sequence
`^FOO^BAR^' is synonymous with `!!:s^FOO^BAR^', hence other modifiers
(see Modifiers) may follow the final `^'.

If the shell encounters the character sequence `!"'  in the input, the
history mechanism is temporarily disabled until the current list (see
Shell Grammar) is fully parsed.  The `!"' is removed from the
input, and any subsequent `!' characters have no special significance.

A less convenient but more comprehensible form of command history
support is provided by the fc builtin.

Event Designators
-----------------

An event designator is a reference to a command-line entry in the
history list.  In the list below, remember that the initial `!' in each
item may be changed to another character by setting the histchars
parameter.

!
     Start a history expansion, except when followed by a blank,
     newline, `=' or `('.  If followed immediately by a word designator
     (see Word Designators), this forms a history reference with no
     event designator (see Overview).

!!
     Refer to the previous command.  By itself, this expansion repeats
     the previous command.

!N
     Refer to command-line N.

!-N
     Refer to the current command-line minus N.

!STR
     Refer to the most recent command starting with STR.

!?STR[?]
     Refer to the most recent command containing STR.  The trailing `?'
     is necessary if this reference is to be followed by a modifier or
     followed by any text that is not to be considered part of STR.

!#
     Refer to the current command line typed in so far.  The line is
     treated as if it were complete up to and including the word before
     the one with the `!#' reference.

!{...}
     Insulate a history reference from adjacent characters (if
     necessary).

Word Designators
----------------

A word designator indicates which word or words of a given command line
are to be included in a history reference.  A `:' usually separates the
event specification from the word designator.  It may be omitted only
if the word designator begins with a `^', `$', `*', `-' or `%'.  Word
designators include:

0
     The first input word (command).

N
     The Nth argument.

^
     The first argument.  That is, 1.

$
     The last argument.

%
     The word matched by (the most recent) ?STR search.

X-Y
     A range of words; X defaults to 0.

*
     All the arguments, or a null value if there are none.

X*
     Abbreviates `X-$'.

X-
     Like `X*' but omitting word $.

Note that a `%' word designator works only when used in one of `!%',
`!:%' or `!?STR?:%', and only when used after a !? expansion (possibly
in an earlier command).  Anything else results in an error, although
the error may not be the most obvious one.

Modifiers
---------

After the optional word designator, you can add a sequence of one or
more of the following modifiers, each preceded by a `:'.  These
modifiers also work on the result of _filename generation_ and
_parameter expansion_, except where noted.

h
     Remove a trailing pathname component, leaving the head.  This works
     like `dirname'.

r
     Remove a filename extension of the form `.XXX', leaving the root
     name.

e
     Remove all but the extension.

t
     Remove all leading pathname components, leaving the tail.  This
     works like `basename'.

p
     Print the new command but do not execute it.  Only works with
     history expansion.

q
     Quote the substituted words, escaping further substitutions.  Works
     with history expansion and parameter expansion, though for
     parameters it is only useful if the resulting text is to be
     re-evaluated such as by eval.

Q
     Remove one level of quotes from the substituted words.

x
     Like q, but break into words at whitespace.  Does not work with
     parameter expansion.

l
     Convert the words to all lowercase.

u
     Convert the words to all uppercase.

s/L/R[/]
     Substitute R for L as described below.  Unless preceded
     immediately by a g, with no colon between, the substitution is
     done only for the first string that matches L.  For arrays and for
     filename generation, this applies to each word of the expanded
     text.

&
     Repeat the previous s substitution.  Like s, may be preceded
     immediately by a g.  In parameter expansion the & must appear
     inside braces, and in filename generation it must be quoted with a
     backslash.

The s/l/r/ substitution works as follows.  The left-hand side of
substitutions are not regular expressions, but character strings.  Any
character can be used as the delimiter in place of `/'.  A backslash
quotes the delimiter character.  The character `&', in the
right-hand-side R, is replaced by the text from the left-hand-side L.
The `&' can be quoted with a backslash.  A null L uses the previous
string either from the previous L or from the contextual scan string S
from `!?S'.  You can omit the rightmost delimiter if a newline
immediately follows R; the rightmost `?' in a context scan can
similarly be omitted.  Note the same record of the last L and R is
maintained across all forms of expansion.

The following f, F, w and W modifiers work only with parameter
expansion and filename generation.  They are listed here to provide a
single point of reference for all modifiers.

f
     Repeats the immediately (without a colon) following modifier until
     the resulting word doesn't change any more.

F:EXPR:
     Like f, but repeats only N times if the expression EXPR evaluates
     to N.  Any character can be used instead of the `:'; if `(', `[',
     or `{' is used as the opening delimiter, the closing delimiter
     should be ')', `]', or `}', respectively.

w
     Makes the immediately following modifier work on each word in the
     string.

W:SEP:
     Like w but words are considered to be the parts of the string that
     are separated by SEP. Any character can be used instead of the
     `:'; opening parentheses are handled specially, see above.

Process Substitution
====================

Each command argument of the form `<(LIST)', `>(LIST)' or `=(LIST)' is
subject to process substitution.  In the case of the < or > forms, the
shell runs process LIST asynchronously.  If the system supports the
/dev/fd mechanism, the command argument is the name of the device file
corresponding to a file descriptor; otherwise, if the system supports
named pipes (FIFOs), the command argument will be a named pipe.  If the
form with > is selected then writing on this special file will provide
input for LIST.  If < is used, then the file passed as an argument will
be connected to the output of the LIST process.  For example,

     paste <(cut -f1 FILE1) <(cut -f3 FILE2) |
     tee >(PROCESS1) >(PROCESS2) >/dev/null

cuts fields 1 and 3 from the files FILE1 and FILE2 respectively, pastes
the results together, and sends it to the processes PROCESS1 and
PROCESS2.

Both the /dev/fd and the named pipe implementation have drawbacks.  In
the former case, some programmes may automatically close the file
descriptor in question before examining the file on the command line,
particularly if this is necessary for security reasons such as when the
programme is running setuid.  In the second case, if the programme does
not actually open the file, the subshell attempting to read from or
write to the pipe will (in a typical implementation, different
operating systems may have different behaviour) block for ever and have
to be killed explicitly.  In both cases, the shell actually supplies the
information using a pipe, so that programmes that expect to lseek (see
man page lseek(2)) on the file will not work.

Also note that the previous example can be more compactly and
efficiently written (provided the MULTIOS option is set) as:

     paste <(cut -f1 FILE1) <(cut -f3 FILE2) > >(PROCESS1) > >(PROCESS2)

The shell uses pipes instead of FIFOs to implement the latter two
process substitutions in the above example.

If = is used, then the file passed as an argument will be the name of a
temporary file containing the output of the LIST process.  This may be
used instead of the < form for a program that expects to lseek (see man
page lseek(2)) on the input file.