ZSHAL(1) ZSHAL(1)
NAME
zshall - the Z shell meta-man page
OVERVIEW
Because zsh contains many features, the zsh manual has been split into
a number of sections. This manual page includes all the separate man-
ual pages in the following order:
zshmisc Anything not fitting into the other sections
zshexpn Zsh command and parameter expansion
zshparam Zsh parameters
zshoptions Zsh options
zshbuiltins Zsh built-in functions
zshzle Zsh command line editing
zshcompwid Zsh completion widgets
zshcompsys Zsh completion system
zshcompctl Zsh completion control
zshmodules Zsh loadable modules
zshzftpsys Zsh built-in FTP client
DESCRIPTION
Zsh is a UNIX command interpreter (shell) usable as an interactive
login shell and as a shell script command processor. Of the standard
shells, zsh most closely resembles ksh but includes many enhancements.
Zsh has command line editing, builtin spelling correction, programmable
command completion, shell functions (with autoloading), a history mech-
anism, and a host of other features.
AUTHOR
Zsh was originally written by Paul Falstad <>. Zsh is now
maintained by the members of the zsh-workers mailing list <>. The development is currently coordinated by Peter
Stephenson <>. The coordinator can be contacted at <>, but matters relating to the code should generally go to
the mailing list.
AVAILABILITY
Zsh is available from the following anonymous FTP sites. These mirror
sites are kept frequently up to date. The sites marked with (H) may be
mirroring ftp.cs.elte.hu instead of the primary site.
Primary site
ftp:://ftp.zsh.org/pub/zsh/
http:://www.zsh.org/pub/zsh/
Australia
ftp:://ftp.zsh.org/pub/zsh/
http:://www.zsh.org/pub/zsh/
Denmark
ftp:://sunsite.dk/pub/unix/shells/zsh/
Finland
ftp:://ftp.funet.fi/pub/unix/shells/zsh/
Germany
ftp:://ftp.fu-berlin.de/pub/unix/shells/zsh/ (H)
ftp:://ftp.gmd.de/packages/zsh/
ftp:://ftp.uni-trier.de/pub/unix/shell/zsh/
Hungary
ftp:://ftp.cs.elte.hu/pub/zsh/
http:://www.cs.elte.hu/pub/zsh/
ftp:://ftp.kfki.hu/pub/packages/zsh/
Israel
ftp:://ftp.math.technion.ac.il/pub/zsh/
http:://www.math.technion.ac.il/pub/zsh/
Japan
ftp:://ftp.win.ne.jp/pub/shell/zsh/
ftp:://ftp.ayamura.org/pub/zsh/
Korea
ftp:://linux.sarang.net/mirror/system/shell/zsh/
Netherlands
ftp:://ftp.demon.nl/pub/mirrors/zsh/
Norway
ftp:://ftp.uit.no/pub/unix/shells/zsh/
Poland
ftp:://sunsite.icm.edu.pl/pub/unix/shells/zsh/
Romania
ftp:://ftp.roedu.net/pub/mirrors/ftp.zsh.org/pub/zsh/
ftp:://ftp.kappa.ro/pub/mirrors/ftp.zsh.org/pub/zsh/
Slovenia
ftp:://ftp.siol.net/mirrors/zsh/
Sweden
ftp:://ftp.lysator.liu.se/pub/unix/zsh/
UK
ftp:://ftp.net.lut.ac.uk/zsh/
ftp:://sunsite.org.uk/packages/zsh/
USA
ftp:://uiarchive.uiuc.edu/mirrors/ftp/ftp.zsh.org/pub/
ftp:://ftp.rge.com/pub/shells/zsh/
http:://zsh.disillusion.org/
http:://foad.org/zsh/
The up-to-date source code is available via anonymous CVS from Source-
forge. See http:://sourceforge.net/projects/zsh/ for details.
MAILING LISTS
Zsh has 3 mailing lists:
<>
Announcements about releases, major changes in the shell and the
monthly posting of the Zsh FAQ. (moderated)
<>
User discussions.
<>
Hacking, development, bug reports and patches.
To subscribe or unsubscribe, send mail to the associated administrative
address for the mailing list.
<>
<>
<>
<>
<>
<>
YOU ONLY NED TO JOIN ONE OF THE MAILING LISTS AS THEY ARE NESTED. All
submissions to zsh-announce are automatically forwarded to zsh-users.
All submissions to zsh-users are automatically forwarded to zsh-work-
ers.
If you have problems subscribing/unsubscribing to any of the mailing
lists, send mail to <>. The mailing lists are main-
tained by Karsten Thygesen <>.
The mailing lists are archived; the archives can be accessed via the
administrative addresses listed above. There is also a hypertext ar-
chive, maintained by Geoff Wing <>, available at
http:://www.zsh.org/mla/.
THE ZSH FAQ
Zsh has a list of Frequently Asked Questions (FAQ), maintained by Peter
Stephenson <>. It is regularly posted to the newsgroup
comp.unix.shell and the zsh-announce mailing list. The latest version
can be found at any of the Zsh FTP sites, or at
http:://www.zsh.org/FAQ/. The contact address for FAQ-related matters
is <>.
THE ZSH WEB PAGE
Zsh has a web page which is located at http:://www.zsh.org/. This is
maintained by Karsten Thygesen <>, of SunSITE Denmark.
The contact address for web-related matters is <>.
THE ZSH USERGUIDE
A userguide is currently in preparation. It is intended to complement
the manual, with explanations and hints on issues where the manual can
be cabbalistic, hierographic, or downright mystifying (for example, the
word `hierographic' does not exist). It can be viewed in its current
state at http:://zsh.sunsite.dk/Guide/. At the time of writing, chap-
ters dealing with startup files and their contents and the new comple-
tion system were essentially complete.
THE ZSH WIKI
A `wiki' website for zsh has been created at http:://www.zshwiki.org/.
This is a site which can be added to and modified directly by users
without any special permission. You can add your own zsh tips and con-
figurations.
INVOCATION OPTIONS
The following flags are interpreted by the shell when invoked to deter-
mine where the shell will read commands from:
-c Take the first argument as a command to execute, rather than
reading commands from a script or standard input. If any fur-
ther arguments are given, the first one is assigned to $$00,
rather than being used as a positional parameter.
-i Force shell to be interactive.
-s Force shell to read commands from the standard input. If the -s
flag is not present and an argument is given, the first argument
is taken to be the pathname of a script to execute.
After the first one or two arguments have been appropriated as
described above, the remaining arguments are assigned to the positional
parameters.
For further options, which are common to invocation and the set
builtin, see zshoptions(1).
Options may be specified by name using the -o option. -o acts like a
single-letter option, but takes a following string as the option name.
For example,
zsh -x -o shwordsplit scr
runs the script scr, setting the XTRACE option by the corresponding
letter `-x' and the SHWORDSPLIT option by name. Options may be
turned off by name by using ]o instead of -o. -o can be stacked up
with preceding single-letter options, so for example `-xo shwordsplit'
or `-xoshwordsplit' is equivalent to `-x -o shwordsplit'.
Options may also be specified by name in GNU long option style,
`--option-name'. When this is done, `-' characters in the option name
are permitted: they are translated into `', and thus ignored. So, for
example, `zsh --sh-word-split' invokes zsh with the SHWORDSPLIT
option turned on. Like other option syntaxes, options can be turned
off by replacing the initial `-' with a `]'; thus `]-sh-word-split' is
equivalent to `--no-sh-word-split'. Unlike other option syntaxes,
GNU-style long options cannot be stacked with any other options, so for
example `-x-shwordsplit' is an error, rather than being treated like
`-x --shwordsplit'.
The special GNU-style option `--version' is handled; it sends to stan-
dard output the shell's version information, then exits successfully.
`--help' is also handled; it sends to standard output a list of options
that can be used when invoking the shell, then exits successfully.
Option processing may be finished, allowing following arguments that
start with `-' or `]' to be treated as normal arguments, in two ways.
Firstly, a lone `-' (or `]') as an argument by itself ends option pro-
cessing. Secondly, a special option `--' (or `]-'), which may be spec-
ified on its own (which is the standard POSIX usage) or may be stacked
with preceding options (so `-x-' is equivalent to `-x --'). Options
are not permitted to be stacked after `--' (so `-x-f' is an error), but
note the GNU-style option form discussed above, where `--shwordsplit'
is permitted and does not end option processing.
Except when the sh/ksh emulation single-letter options are in effect,
the option `-b' (or `]b') ends option processing. `-b' is like `--',
except that further single-letter options can be stacked after the `-b'
and will take effect as normal.
COMPATIBILITY
Zsh tries to emulate sh or ksh when it is invoked as sh or ksh respec-
tively; more precisely, it looks at the first letter of the name by
which it was invoked, excluding any initial `r' (assumed to stand for
`restricted'), and if that is `s' or `k' it will emulate sh or ksh.
Furthermore, if invoked as su (which happens on certain systems when
the shell is executed by the su command), the shell will try to find an
alternative name from the SHEL environment variable and perform emula-
tion based on that.
In sh and ksh compatibility modes the following parameters are not spe-
cial and not initialized by the shell: ARGC, argv, cdpath, fignore,
fpath, HISTCHARS, mailpath, MANPATH, manpath, path, prompt, PROMPT,
PROMPT2, PROMPT3, PROMPT4, psvar, status, watch.
The usual zsh startup/shutdown scripts are not executed. Login shells
source /etc/profile followed by $$HOME/.profile. If the ENV environment
variable is set on invocation, $$ENV is sourced after the profile
scripts. The value of ENV is subjected to parameter expansion, command
substitution, and arithmetic expansion before being interpreted as a
pathname. Note that the PRIVILEGED option also affects the execution
of startup files.
The following options are set if the shell is invoked as sh or ksh:
NOBADPATERN, NOBANGHIST, NOBGNICE, NOEQUALS, NOFUNC-
TIONARGZERO, GLOBSUBST, NOGLOBALEXPORT, NOHUP, INTERACTIVECO-
MENTS, KSHARAYS, NOMULTIOS, NONOMATCH, NONOTIFY, POSIXBUILTINS,
NOPROMPTPERCENT, RMSTARSILENT, SHFILEXPANSION, SHGLOB,
SHOPTIONLETERS, SHWORDSPLIT. Additionally the BSDECHO and
IGNOREBRACES options are set if zsh is invoked as sh. Also, the
KSHOPTIONPRINT, LOCALOPTIONS, PROMPTBANG, PROMPTSUBST and SIN-
GLELINEZLE options are set if zsh is invoked as ksh.
RESTRICTED SHEL
When the basename of the command used to invoke zsh starts with the
letter `r' or the `-r' command line option is supplied at invocation,
the shell becomes restricted. Emulation mode is determined after
stripping the letter `r' from the invocation name. The following are
disabled in restricted mode:
]o changing directories with the cd builtin
]o changing or unsetting the PATH, path, MODULEPATH, modulepath,
SHEL, HISTFILE, HISTSIZE, GID, EGID, UID, EUID, USERNAME,
LDLIBRARYPATH, LDAOUTLIBRARYPATH, LDPRELOAD and
LDAOUTPRELOAD parameters
]o specifying command names containing /
]o specifying command pathnames using hash
]o redirecting output to files
]o using the exec builtin command to replace the shell with another
command
]o using jobs -Z to overwrite the shell process' argument and envi-
ronment space
]o using the ARGV00 parameter to override argv[00] for external com-
mands
]o turning off restricted mode with set ]r or unsetopt RESTRICTED
These restrictions are enforced after processing the startup files.
The startup files should set up PATH to point to a directory of com-
mands which can be safely invoked in the restricted environment. They
may also add further restrictions by disabling selected builtins.
Restricted mode can also be activated any time by setting the
RESTRICTED option. This immediately enables all the restrictions
described above even if the shell still has not processed all startup
files.
STARTUP/SHUTDOWN FILES
Commands are first read from /etc/zshenv; this cannot be overridden.
Subsequent behaviour is modified by the RCS and GLOBALRCS options; the
former affects all startup files, while the second only affects those
in the /etc directory. If one of the options is unset at any point,
any subsequent startup file(s) of the corresponding type will not be
read. It is also possible for a file in $$ZDOTDIR to re-enable
GLOBALRCS. Both RCS and GLOBALRCS are set by default.
Commands are then read from $$ZDOTDIR/.zshenv. If the shell is a login
shell, commands are read from /etc/zprofile and then $$ZDOTDIR/.zpro-
file. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $$ZDOTDIR/.zshrc. Finally, if the shell is a login
shell, /etc/zlogin and $$ZDOTDIR/.zlogin are read.
When a login shell exits, the files $$ZDOTDIR/.zlogout and then
/etc/zlogout are read. This happens with either an explicit exit via
the exit or logout commands, or an implicit exit by reading end-of-file
from the terminal. However, if the shell terminates due to exec'ing
another process, the logout files are not read. These are also
affected by the RCS and GLOBALRCS options. Note also that the RCS
option affects the saving of history files, i.e. if RCS is unset when
the shell exits, no history file will be saved.
If ZDOTDIR is unset, HOME is used instead. Those files listed above as
being in /etc may be in another directory, depending on the installa-
tion.
As /etc/zshenv is run for all instances of zsh, it is important that it
be kept as small as possible. In particular, it is a good idea to put
code that does not need to be run for every single shell behind a test
of the form `if [ -o rcs ];; then ...' so that it will not be executed
when zsh is invoked with the `-f' option.
Any of these files may be pre-compiled with the zcompile builtin com-
mand (see zshbuiltins(1)). If a compiled file exists (named for the
original file plus the .zwc extension) and it is newer than the origi-
nal file, the compiled file will be used instead.
ZSHMISC(1) ZSHMISC(1)
NAME
zshmisc - everything and then some
SIMPLE COMANDS && PIPELINES
A simple command is a sequence of optional parameter assignments fol-
lowed by blank-separated words, with optional redirections inter-
spersed. The first word is the command to be executed, and the remain-
ing words, if any, are arguments to the command. If a command name is
given, the parameter assignments modify the environment of the command
when it is executed. The value of a simple command is its exit status,
or 128 plus the signal number if terminated by a signal. For example,
echo foo
is a simple command with arguments.
A pipeline is either a simple command, or a sequence of two or more
simple commands where each command is separated from the next by `' or
`&&'. Where commands are separated by `', the standard output of the
first command is connected to the standard input of the next. `&&' is
shorthand for `2>>&&1 ', which connects both the standard output and the
standard error of the command to the standard input of the next. The
value of a pipeline is the value of the last command, unless the pipe-
line is preceded by `!!' in which case the value is the logical inverse
of the value of the last command. For example,
echo foo sed ''s/foo/bar/''
is a pipeline, where the output (`foo' plus a newline) of the first
command will be passed to the input of the second.
If a pipeline is preceded by `coproc', it is executed as a coprocess; a
two-way pipe is established between it and the parent shell. The shell
can read from or write to the coprocess by means of the `>>&&p' and `<<&&p'
redirection operators or with `print -p' and `read -p'. A pipeline
cannot be preceded by both `coproc' and `!!'. If job control is active,
the coprocess can be treated in other than input and output as an ordi-
nary background job.
A sublist is either a single pipeline, or a sequence of two or more
pipelines separated by `&&&&' or `'. If two pipelines are separated by
`&&&&', the second pipeline is executed only if the first succeeds
(returns a zero value). If two pipelines are separated by `', the
second is executed only if the first fails (returns a nonzero value).
Both operators have equal precedence and are left associative. The
value of the sublist is the value of the last pipeline executed. For
example,
dmesg grep panic &&&& print yes
is a sublist consisting of two pipelines, the second just a simple com-
mand which will be executed if and only if the grep command returns a
zero value. If it does not, the value of the sublist is that return
value, else it is the value returned by the print (almost certainly
zero).
A list is a sequence of zero or more sublists, in which each sublist is
terminated by `;;', `&&', `&&', `&&!!', or a newline. This terminator may
optionally be omitted from the last sublist in the list when the list
appears as a complex command inside `(...)' or `{{...}}'. When a sub-
list is terminated by `;;' or newline, the shell waits for it to finish
before executing the next sublist. If a sublist is terminated by a
`&&', `&&', or `&&!!', the shell executes the last pipeline in it in the
background, and does not wait for it to finish (note the difference
from other shells which execute the whole sublist in the background).
A backgrounded pipeline returns a status of zero.
More generally, a list can be seen as a set of any shell commands what-
soever, including the complex commands below; this is implied wherever
the word `list' appears in later descriptions. For example, the com-
mands in a shell function form a special sort of list.
PRECOMAND MODIFIERS
A simple command may be preceded by a precommand modifier, which will
alter how the command is interpreted. These modifiers are shell
builtin commands with the exception of nocorrect which is a reserved
word.
- The command is executed with a `-' prepended to its argv[00]
string.
noglob Filename generation (globbing) is not performed on any of the
words.
nocorrect
Spelling correction is not done on any of the words. This must
appear before any other precommand modifier, as it is inter-
preted immediately, before any parsing is done. It has no
effect in non-interactive shells.
exec The command is executed in the parent shell without forking.
command
The command word is taken to be the name of an external command,
rather than a shell function or builtin.
builtin
The command word is taken to be the name of a builtin command,
rather than a shell function or external command.
COMPLEX COMANDS
A complex command in zsh is one of the following:
if list then list [ elif list then list ] ... [ else list ] fi
The if list is executed, and if it returns a zero exit status,
the then list is executed. Otherwise, the elif list is executed
and if its value is zero, the then list is executed. If each
elif list returns nonzero, the else list is executed.
for name ... [ in word ... ] term do list done
where term is at least one newline or ;;. Expand the list of
words, and set the parameter name to each of them in turn, exe-
cuting list each time. If the in word is omitted, use the posi-
tional parameters instead of the words.
More than one parameter name can appear before the list of
words. If N names are given, then on each execution of the loop
the next N words are assigned to the corresponding parameters.
If there are more names than remaining words, the remaining
parameters are each set to the empty string. Execution of the
loop ends when there is no remaining word to assign to the first
name. It is only possible for in to appear as the first name in
the list, else it will be treated as marking the end of the
list.
for (( [expr1] ;; [expr2] ;; [expr3] )) do list done
The arithmetic expression expr1 is evaluated first (see the sec-
tion `Arithmetic Evaluation'). The arithmetic expression expr2
is repeatedly evaluated until it evaluates to zero and when
non-zero, list is executed and the arithmetic expression expr3
evaluated. If any expression is omitted, then it behaves as if
it evaluated to 1.
while list do list done
Execute the do list as long as the while list returns a zero
exit status.
until list do list done
Execute the do list as long as until list returns a nonzero exit
status.
repeat word do list done
word is expanded and treated as an arithmetic expression, which
must evaluate to a number n. list is then executed n times.
case word in [ [(] pattern [ pattern ] ... ) list (;;;;;;&&) ] ... esac
Execute the list associated with the first pattern that matches
word, if any. The form of the patterns is the same as that used
for filename generation. See the section `Filename Generation'.
If the list that is executed is terminated with ;;&& rather than
;;;;, the following list is also executed. This continues until
either a list is terminated with ;;;; or the esac is reached.
select name [ in word ... term ] do list done
where term is one or more newline or ;; to terminate the words.
Print the set of words, each preceded by a number. If the in
word is omitted, use the positional parameters. The PROMPT3
prompt is printed and a line is read from the line editor if the
shell is interactive and that is active, or else standard input.
If this line consists of the number of one of the listed words,
then the parameter name is set to the word corresponding to this
number. If this line is empty, the selection list is printed
again. Otherwise, the value of the parameter name is set to
null. The contents of the line read from standard input is
saved in the parameter REPLY. list is executed for each selec-
tion until a break or end-of-file is encountered.
( list )
Execute list in a subshell. Traps set by the trap builtin are
reset to their default values while executing list.
{{ list }}
Execute list.
{{ try-list }} always {{ always-list }}
First execute try-list. Regardless of errors, or break, con-
tinue, or return commands encountered within try-list, execute
always-list. Execution then continues from the result of the
execution of try-list; in other words, any error, or break, con-
tinue, or return command is treated in the normal way, as if
always-list were not present. The two chunks of code are
referred to as the `try block' and the `always block'.
Optional newlines or semicolons may appear after the always;
note, however, that they may not appear between the preceeding
closing brace and the always.
An `error' in this context is a condition such as a syntax error
which causes the shell to abort execution of the current func-
tion, script, or list. Syntax errors encountered while the
shell is parsing the code do not cause the always-list to be
executed. For example, an erroneously constructed if block in
try-list would cause the shell to abort during parsing, so that
always-list would not be executed, while an erroneous substitu-
tion such as $${{**foo**}} would cause a run-time error, after which
always-list would be executed.
An error condition can be tested and reset with the special
integer variable TRYBLOCKEROR. Outside an always-list the
value is irrelevant, but it is initialised to -1. Inside
always-list, the value is 1 if an error occurred in the
try-list, else 0. If TRYBLOCKEROR is set to 0 during the
always-list, the error condition caused by the try-list is
reset, and shell execution continues normally after the end of
always-list. Altering the value during the try-list is not use-
ful (unless this forms part of an enclosing always block).
Regardless of TRYBLOCKEROR, after the end of always-list the
normal shell status $$?? is the value returned from always-list.
This will be non-zero if there was an error, even if
TRYBLOCKEROR was set to zero.
The following executes the given code, ignoring any errors it
causes. This is an alternative to the usual convention of pro-
tecting code by executing it in a subshell.
{{
## code which may cause an error
}} always {{
## This code is executed regardless of the error.
(( TRYBLOCKEROR == 00 ))
}}
## The error condition has been reset.
An exit command encountered in try-list does not cause the exe-
cution of always-list. Instead, the shell exits immediately
after any EXIT trap has been executed.
function word ... [ () ] [ term ] {{ list }}
word ... () [ term ] {{ list }}
word ... () [ term ] command
where term is one or more newline or ;;. Define a function which
is referenced by any one of word. Normally, only one word is
provided; multiple words are usually only useful for setting
traps. The body of the function is the list between the {{ and
}}. See the section `Functions'.
If the option SHGLOB is set for compatibility with other
shells, then whitespace may appear between between the left and
right parentheses when there is a single word; otherwise, the
parentheses will be treated as forming a globbing pattern in
that case.
time [ pipeline ]
The pipeline is executed, and timing statistics are reported on
the standard error in the form specified by the TIMEFMT parame-
ter. If pipeline is omitted, print statistics about the shell
process and its children.
[ exp ]
Evaluates the conditional expression exp and return a zero exit
status if it is true. See the section `Conditional Expressions'
for a description of exp.
ALTERNATE FORMS FOR COMPLEX COMANDS
Many of zsh's complex commands have alternate forms. These particular
versions of complex commands should be considered deprecated and may be
removed in the future. The versions in the previous section should be
preferred instead.
The short versions below only work if sublist is of the form `{{ list }}'
or if the SHORTLOPS option is set. For the if, while and until com-
mands, in both these cases the test part of the loop must also be suit-
ably delimited, such as by `[ ... ]' or `(( ... ))', else the end of
the test will not be recognized. For the for, repeat, case and select
commands no such special form for the arguments is necessary, but the
other condition (the special form of sublist or use of the SHORTLOPS
option) still applies.
if list {{ list }} [ elif list {{ list }} ] ... [ else {{ list }} ]
An alternate form of if. The rules mean that
if [ -o ignorebraces ] {{
print yes
}}
works, but
if true {{ ## Does not work!!
print yes
}}
does not, since the test is not suitably delimited.
if list sublist
A short form of the alternate `if'. The same limitations on the
form of list apply as for the previous form.
for name ... ( word ... ) sublist
A short form of for.
for name ... [ in word ... ] term sublist
where term is at least one newline or ;;. Another short form of
for.
for (( [expr1] ;; [expr2] ;; [expr3] )) sublist
A short form of the arithmetic for command.
foreach name ... ( word ... ) list end
Another form of for.
while list {{ list }}
An alternative form of while. Note the limitations on the form
of list mentioned above.
until list {{ list }}
An alternative form of until. Note the limitations on the form
of list mentioned above.
repeat word sublist
This is a short form of repeat.
case word {{ [ [(] pattern [ pattern ] ... ) list (;;;;;;&&) ] ... }}
An alternative form of case.
select name [ in word term ] sublist
where term is at least one newline or ;;. A short form of
select.
RESERVED WORDS
The following words are recognized as reserved words when used as the
first word of a command unless quoted or disabled using disable -r:
do done esac then elif else fi for case if while function repeat time
until select coproc nocorrect foreach end !! [ {{ }}
Additionally, `}}' is recognized in any position if the IGNOREBRACES
option is not set.
COMENTS
In noninteractive shells, or in interactive shells with the INTERAC-
TIVECOMENTS option set, a word beginning with the third character of
the histchars parameter (`##' by default) causes that word and all the
following characters up to a newline to be ignored.
ALIASING
Every token in the shell input is checked to see if there is an alias
defined for it. If so, it is replaced by the text of the alias if it
is in command position (if it could be the first word of a simple com-
mand), or if the alias is global. If the text ends with a space, the
next word in the shell input is treated as though it were in command
position for purposes of alias expansion. An alias is defined using
the alias builtin; global aliases may be defined using the -g option to
that builtin.
Alias expansion is done on the shell input before any other expansion
except history expansion. Therefore, if an alias is defined for the
word foo, alias expansion may be avoided by quoting part of the word,
e.g. \\foo. But there is nothing to prevent an alias being defined for
\\foo as well.
QUOTING
A character may be quoted (that is, made to stand for itself) by pre-
ceding it with a `\\'. `\\' followed by a newline is ignored.
A string enclosed between `$$''' and `''' is processed the same way as the
string arguments of the print builtin, and the resulting string is con-
sidered to be entirely quoted. A literal `''' character can be included
in the string by using the `\\''' escape.
All characters enclosed between a pair of single quotes ('''') that is
not preceded by a `$$' are quoted. A single quote cannot appear within
single quotes unless the option RCQUOTES is set, in which case a pair
of single quotes are turned into a single quote. For example,
print ''''''''
outputs nothing apart from a newline if RCQUOTES is not set, but one
single quote if it is set.
Inside double quotes (""""), parameter and command substitution occur,
and `\\' quotes the characters `\\', ```', `""', and `$$'.
REDIRECTION
If a command is followed by && and job control is not active, then the
default standard input for the command is the empty file /dev/null.
Otherwise, the environment for the execution of a command contains the
file descriptors of the invoking shell as modified by input/output
specifications.
The following may appear anywhere in a simple command or may precede or
follow a complex command. Expansion occurs before word or digit is
used except as noted below. If the result of substitution on word pro-
duces more than one filename, redirection occurs for each separate
filename in turn.
<< word Open file word for reading as standard input.
<<>> word
Open file word for reading and writing as standard input. If
the file does not exist then it is created.
>> word Open file word for writing as standard output. If the file does
not exist then it is created. If the file exists, and the CLOB-
BER option is unset, this causes an error; otherwise, it is
truncated to zero length.
>> word
>>!! word
Same as >>, except that the file is truncated to zero length if
it exists, even if CLOBER is unset.
>>>> word
Open file word for writing in append mode as standard output.
If the file does not exist, and the CLOBER option is unset,
this causes an error; otherwise, the file is created.
>>>> word
>>>>!! word
Same as >>>>, except that the file is created if it does not
exist, even if CLOBER is unset.
<<<<[-] word
The shell input is read up to a line that is the same as word,
or to an end-of-file. No parameter expansion, command substitu-
tion or filename generation is performed on word. The resulting
document, called a here-document, becomes the standard input.
If any character of word is quoted with single or double quotes
or a `\\', no interpretation is placed upon the characters of the
document. Otherwise, parameter and command substitution occurs,
`\\' followed by a newline is removed, and `\\' must be used to
quote the characters `\\', `$$', ```' and the first character of
word.
Note that word itself does not undergo shell expansion. Back-
quotes in word do not have their usual effect; instead they
behave similarly to double quotes, except that the backquotes
themselves are passed through unchanged. (This information is
given for completeness and it is not recommended that backquotes
be used.) Quotes in the form $$''...'' have their standard effect
of expanding backslashed references to special characters.
If <<<<- is used, then all leading tabs are stripped from word and
from the document.
<<<<<< word
Perform shell expansion on word and pass the result to standard
input. This is known as a here-string. Compare the use of word
in here-documents above, where word does not undergo shell
expansion.
<<&& number
>>&& number
The standard input/output is duplicated from file descriptor
number (see dup2(2)).
<<&& -
>>&& - Close the standard input/output.
<<&& p
>>&& p The input/output from/to the coprocess is moved to the standard
input/output.
>>&& word
&&>> word
(Except where `>>&& word' matches one of the above syntaxes; `&&>>'
can always be used to avoid this ambiguity.) Redirects both
standard output and standard error (file descriptor 2) in the
manner of `>> word'. Note that this does not have the same
effect as `>> word 2>>&&1' in the presence of multios (see the sec-
tion below).
>>&& word
>>&&!! word
&&>> word
&&>>!! word
Redirects both standard output and standard error (file descrip-
tor 2) in the manner of `>> word'.
>>>>&& word
&&>>>> word
Redirects both standard output and standard error (file descrip-
tor 2) in the manner of `>>>> word'.
>>>>&& word
>>>>&&!! word
&&>>>> word
&&>>>>!! word
Redirects both standard output and standard error (file descrip-
tor 2) in the manner of `>>>> word'.
If one of the above is preceded by a digit, then the file descriptor
referred to is that specified by the digit instead of the default 0 or
1. The order in which redirections are specified is significant. The
shell evaluates each redirection in terms of the (file descriptor,
file) association at the time of evaluation. For example:
... 1>>fname 2>>&&1
first associates file descriptor 1 with file fname. It then associates
file descriptor 2 with the file associated with file descriptor 1 (that
is, fname). If the order of redirections were reversed, file descrip-
tor 2 would be associated with the terminal (assuming file descriptor 1
had been) and then file descriptor 1 would be associated with file
fname.
The `&&' command separator described in Simple Commands & Pipelines in
zshmisc(1) is a shorthand for `2>>&&1 '.
For output redirections only, if word is of the form `>>(list)' then the
output is piped to the command represented by list. See Process Sub-
stitution in zshexpn(1).
MULTIOS
If the user tries to open a file descriptor for writing more than once,
the shell opens the file descriptor as a pipe to a process that copies
its input to all the specified outputs, similar to tee, provided the
MULTIOS option is set, as it is by default. Thus:
date >>foo >>bar
writes the date to two files, named `foo' and `bar'. Note that a pipe
is an implicit redirection; thus
date >>foo cat
writes the date to the file `foo', and also pipes it to cat.
If the MULTIOS option is set, the word after a redirection operator is
also subjected to filename generation (globbing). Thus
:: >> **
will truncate all files in the current directory, assuming there's at
least one. (Without the MULTIOS option, it would create an empty file
called `**'.) Similarly, you can do
echo exit 00 >>>> **.sh
If the user tries to open a file descriptor for reading more than once,
the shell opens the file descriptor as a pipe to a process that copies
all the specified inputs to its output in the order specified, similar
to cat, provided the MULTIOS option is set. Thus
sort <> bar >> baz
when MULTIOS is unset will truncate bar, and write `foo' into baz.
There is a problem when an output multio is attached to an external
program. A simple example shows this:
cat file >>file1 >>file2
cat file1 file2
Here, it is possible that the second `cat' will not display the full
contents of file1 and file2 (i.e. the original contents of file
repeated twice).
The reason for this is that the multios are spawned after the cat
process is forked from the parent shell, so the parent shell does not
wait for the multios to finish writing data. This means the command as
shown can exit before file1 and file2 are completely written. As a
workaround, it is possible to run the cat process as part of a job in
the current shell:
{{ cat file }} >>file >>file2
Here, the {{...}} job will pause to wait for both files to be written.
REDIRECTIONS WITH NO COMAND
When a simple command consists of one or more redirection operators and
zero or more parameter assignments, but no command name, zsh can behave
in several ways.
If the parameter NULCMD is not set or the option CSHNULCMD is set,
an error is caused. This is the csh behavior and CSHNULCMD is set by
default when emulating csh.
If the option SHNULCMD is set, the builtin `::' is inserted as a com-
mand with the given redirections. This is the default when emulating
sh or ksh.
Otherwise, if the parameter NULCMD is set, its value will be used as a
command with the given redirections. If both NULCMD and READNULCMD
are set, then the value of the latter will be used instead of that of
the former when the redirection is an input. The default for NULCMD
is `cat' and for READNULCMD is `more'. Thus
<< file
shows the contents of file on standard output, with paging if that is a
terminal. NULCMD and READNULCMD may refer to shell functions.
COMAND EXECUTION
If a command name contains no slashes, the shell attempts to locate it.
If there exists a shell function by that name, the function is invoked
as described in the section `Functions'. If there exists a shell
builtin by that name, the builtin is invoked.
Otherwise, the shell searches each element of $$path for a directory
containing an executable file by that name. If the search is unsuc-
cessful, the shell prints an error message and returns a nonzero exit
status.
If execution fails because the file is not in executable format, and
the file is not a directory, it is assumed to be a shell script.
/bin/sh is spawned to execute it. If the program is a file beginning
with `##!!', the remainder of the first line specifies an interpreter for
the program. The shell will execute the specified interpreter on oper-
ating systems that do not handle this executable format in the kernel.
FUNCTIONS
Shell functions are defined with the function reserved word or the spe-
cial syntax `funcname ()'. Shell functions are read in and stored
internally. Alias names are resolved when the function is read. Func-
tions are executed like commands with the arguments passed as posi-
tional parameters. (See the section `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 envi-
ronment of the caller.
The return builtin is used to return from function calls.
Function identifiers can be listed with the functions builtin. Func-
tions 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 rec-
ommended 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 cor-
responding 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 defini-
tions as well, but those are neither loaded nor executed; a file
found in this way is searched only for the definition of func-
tion.
element/function
A file of zsh command text, taken to be the definition for func-
tion.
In summary, the order of searching is, first, in the parents of direc-
tories in fpath for the newer of either a compiled directory or a
directory in fpath; second, if more than one of these contains a defi-
nition 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 KSHAUTOLOAD 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 execu-
tion, 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 initializa-
tion and then call the function defined, the file should contain ini-
tialization 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 KSHAUTOLOAD set will produce both messages on
the first call, but only the message `This is func' on the second and
subsequent calls. Without KSHAUTOLOAD set, it will produce the ini-
tialization 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 follow-
ing 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. This is done so that
eval ""$$(functions)""
produces a reasonable result. A true autoloaded function can be iden-
tified by the presence of the comment `## undefined' in the body,
because all comments are discarded from defined functions.
To load the definition of an autoloaded function myfunc without execut-
ing 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 that 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.
The return value from the function is handled specially. If it
is zero, the signal is assumed to have been handled, and execu-
tion continues normally. Otherwise, the normal effect of the
signal is produced; if this causes execution to terminate, the
status returned to the shell is the status returned from the
function.
Programs terminated by uncaught signals typically return the
status 128 plus the signal number. Hence the following causes
the handler for SIGINT to print a message, then mimic the usual
effect of the signal.
TRAPINT() {{
print ""Caught SIGINT,, aborting.""
return $$(( 128 ] $$1 ))
}}
The functions TRAPZER, TRAPDEBUG and TRAPEXIT are never exe-
cuted inside other traps.
TRAPDEBUG
Executed after each command.
TRAPEXIT
Executed when the shell exits, or when the current function
exits if defined inside a function.
TRAPZER
Executed whenever a command has a non-zero exit status. How-
ever, 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
are equivalent.
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 to standard
error 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 `sus-
pended', 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 immedi-
ately 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 sus-
pended. This (intentionally) does not apply if the command is contin-
ued 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 nor-
mally 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. All such notifi-
cations are sent directly to the terminal, not to the standard output
or standard error.
When the monitor mode is on, each background job that completes trig-
gers 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 immedi-
ately 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 nohup(1)) or the disown builtin.
SIGNALS
The INT and QUIT signals for an invoked command are ignored if the com-
mand is followed by `&&' and the MONITOR option is not active. Other-
wise, signals have the values inherited by the shell from its parent
(but see the TRAPNAL special functions in the section `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 - $$(( 123456789001 ))'; 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 match-
ing `))' 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 val and returning a
zero status.
Integers can be in bases other than 10. A leading `00x' or `00X' 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 arith-
metical 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 arith-
metic 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 encoun-
tered 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##400', the rightmost value in the given output base, and
then `8##400 16##200', because y has been explicitly declared to have out-
put base 16, while x (assuming it does not already exist) is implicitly
typed by the arithmetic evaluation, where it acquires the output base
8.
If the CBASES option is set, hexadecimal numbers in the standard C
format, for example 00xF instead of the usual `16##F'. If the option
OCTALZEROES is also set (it is not by default), octal numbers will be
treated similarly and hence appear as `0077' instead of `8##77'. This
option has no effect on the output of bases other than hexadecimal and
octal, and these formats are always understood on input.
When an output base is specified using the `[##base]' syntax, an appro-
priate base prefix will be output if necessary, so that the value out-
put 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 sup-
ported (listed in decreasing order of precedence):
] - !! ~~ ] --
unary plus/minus, logical NOT, complement, {pre,post}{in,de}cre-
ment
<<<< >>>> 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 evalu-
ated. 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/math-
func may be loaded with the zmodload builtin to provide standard float-
ing point mathematical functions.
An expression of the form `####x' where x is any character sequence such
as `a', `^^A', or `\\-\\C-x' gives the ASCI value of this character and
an expression of the form `##foo' gives the ASCI value of the first
character of the value of the parameter foo. Note that this is differ-
ent 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 speci-
fied 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 neces-
sary. 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 == 00;; f << 1;; f ]== 00.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 ]== 00.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 ==
00.00'. It is therefore best to declare numeric variables with explicit
types.
CONDITIONAL EXPRESIONS
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 expres-
sions:
-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 char-
acter, in which case it is a single letter option name. (See
the section `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 ASCI value of
their characters.
string1 >> string2
true if string1 comes after string2 based on ASCI 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 sin-
gle 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 zshexpn(1), 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 PROMPTSUBST option is set, the prompt string is first subjected
to parameter expansion, command substitution and arithmetic expansion.
See zshexpn(1).
Certain escape sequences may be recognised in the prompt string.
If the PROMPTBANG option is set, a `!!' in the prompt is replaced by
the current history event number. A literal `!!' may then be repre-
sented as `!!!!'.
If the PROMPTPERCENT 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:
Special characters
%%%% A `%%'.
%%) A `)'.
Login information
%%l The line (tty) the user is logged in on, without `/dev/' prefix.
If the name starts with `/dev/tty', that prefix is stripped.
%%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.
%%n $$USERNAME.
%%y The line (tty) the user is logged in on, without `/dev/' prefix.
This does not treat `/dev/tty' names specially.
Shell state
%%## 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.
%%?? 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.
%%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.
%%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.
%%j The number of jobs.
%%L The current value of $$SHLVL.
%%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 $$00. An inte-
ger may follow the `%%' to specify a number of trailing path com-
ponents to show; zero means the full path. A negative integer
specifies leading components.
%%c
%%.
%%C Trailing component of $$PWD. An integer may follow the `%%' to
get more than one component. Unless `%%C' is used, tilde con-
traction is performed first. These are deprecated as %%c and %%C
are equivalent to %%1~~ and %%1/, respectively, while explicit pos-
itive integers have the same effect as for the latter two
sequences.
Date and time
%%D The date in yy-mm-dd format.
%%T Current time of day, in 24-hour format.
%%t
%%@@ Current time of day, in 12-hour, am/pm format.
%%** Current time of day in 24-hour format, with seconds.
%%w The date in day-dd format.
%%W The date in mm/dd/yy format.
%%D{{string}}
string is formatted using the strftime function. See strf-
time(3) for more details. Three additional codes are available:
%%f prints the day of the month, like %%e but without any preced-
ing 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.
Visual effects
%%B (%%b)
Start (stop) boldface mode.
%%E Clear to end of line.
%%U (%%u)
Start (stop) underline mode.
%%S (%%s)
Start (stop) standout mode.
%%{{...%%}}
Include a string as a literal escape sequence. The string
within the braces should not change the cursor position. Brace
pairs can nest.
Conditional substrings
%%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.
%%(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 fol-
lowing:
!! True if the shell is running with privileges.
## True if the effective uid of the current process is n.
?? True if the exit status of the last command was n.
True if at least n shell constructs were started.
C
/ True if the current absolute path has at least n elements
relative to the root directory, hence / is counted as 0
elements.
c
.
~~ True if the current path, with prefix replacement, has at
least n elements relative to the root directory, hence /
is counted as 0 elements.
D True if the month is equal to n (January = 0).
d True if the day of the month is equal to n.
g True if the effective gid of the current process is n.
j True if the number of jobs is at least n.
L True if the SHLVL parameter is at least n.
l True if at least n characters have already been printed
on the current line.
S True if the SECONDS parameter is at least n.
T True if the time in hours is equal to n.
t True if the time in minutes is equal to n.
v True if the array psvar has at least n elements.
w True if the day of the week is equal to n (Sunday = 0).
%%<>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 dis-
played 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 exam-
ple, if the current directory is `/home/pike', the prompt
`%%8<<..<<%%/' will expand to `..e/pike'. In this string, the ter-
minating character (`<<', `>>' or `]'), or in fact any character,
may be quoted by a preceding `\\'; note when using print -P, how-
ever, 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 sepa-
rate), 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.
ZSHEXPN(1) ZSHEXPN(1)
NAME
zshexpn - zsh expansion and substitution
DESCRIPTION
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 under Aliasing in zshmisc(1).
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 charac-
ters `\\', `''' and `""' are removed.
Filename Expansion
If the SHFILEXPANSION 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 expan-
sion, 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 correc-
tions and the repetition of complicated commands or arguments. Immedi-
ately 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 in zshmisc(1)) 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 com-
mand 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 the section
`Event Designators') and then an optional word designator (the section
`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 previ-
ous command. However, if the option CSHJUNKIEHISTORY 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
CSHJUNKIEHISTORY set, then `!!::1' and `!!$$' function in the same manner
as `!!!!::1' and `!!!!$$', respectively. Conversely, if CSHJUNKIEHISTORY
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 previ-
ous 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, replac-
ing the string foo with bar. More precisely, the sequence `^^foo^^bar^^'
is synonymous with `!!!!::s^^foo^^bar^^', hence other modifiers (see the sec-
tion `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
zshmisc(1)) 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 sup-
port is provided by the fc builtin.
Event Designators
An event designator is a reference to a command-line entry in the his-
tory 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, new-
line, `==' or `('. If followed immediately by a word designator
(see the section `Word Designators'), this forms a history ref-
erence with no event designator (see the section `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 modi-
fier 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 neces-
sary).
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:
00 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 00.
** 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.
odifiers
After the optional word designator, you can add a sequence of one or
more of the following modifiers, each preceded by a `::'. These modi-
fiers 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 immedi-
ately 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 sub-
stitutions 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 immedi-
ately 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 expan-
sion 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 evalu-
ates 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.
PROCES 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.
If ==(...) is used instead of <<(...), then the file passed as an argu-
ment 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 lseek(2)) on the input file.
The == form is useful as both the /dev/fd and the named pipe implementa-
tion of <<(...) 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 sub-
shell attempting to read from or write to the pipe will (in a typical
implementation, different operating systems may have different behav-
iour) block for ever and have to be killed explicitly. In both cases,
the shell actually supplies the information using a pipe, so that pro-
grammes that expect to lseek (see lseek(2)) on the file will not work.
Also note that the previous example can be more compactly and effi-
ciently 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.
There is an additional problem with >>(process); when this is attached
to an external command, the parent shell does not wait for process to
finish and hence an immediately following command cannot rely on the
results being complete. The problem and solution are the same as
described in the section MULTIOS in zshmisc(1). Hence in a simplified
version of the example above:
paste <<(cut -f1 file1) <<(cut -f3 file2) >> >>(process)
(note that no MULTIOS are involved), process will be run asyn-
chronously. The workaround is:
{{ paste <<(cut -f1 file1) <<(cut -f3 file2) }} >> >>(process)
The extra processes here are spawned from the parent shell which will
wait for their completion.
PARAMETER EXPANSION
The character `$$' is used to introduce parameter expansions. See zsh-
param(1) for a description of parameters, including arrays, associative
arrays, and subscript notation to access individual array elements.
Note in particular the fact that words of unquoted parameters are not
automatically split on whitespace unless the option SHWORDSPLIT is
set; see references to this option below for more details. This is an
important difference from other shells.
In the expansions discussed below that require a pattern, the form of
the pattern is the same as that used for filename generation; see the
section `Filename Generation'. Note that these patterns, along with
the replacement text of any substitutions, are themselves subject to
parameter expansion, command substitution, and arithmetic expansion.
In addition to the following operations, the colon modifiers described
in the section `Modifiers' in the section `History Expansion' can be
applied: for example, $${{i::s/foo/bar/}} performs string substitution on
the expansion of parameter $$i.
$${{name}}
The value, if any, of the parameter name is substituted. The
braces are required if the expansion is to be followed by a let-
ter, digit, or underscore that is not to be interpreted as part
of name. In addition, more complicated forms of substitution
usually require the braces to be present; exceptions, which only
apply if the option KSHARAYS is not set, are a single sub-
script or any colon modifiers appearing after the name, or any
of the characters `^^', `==', `~~', `##' or `]' appearing before the
name, all of which work with or without braces.
If name is an array parameter, and the KSHARAYS option is not
set, then the value of each element of name is substituted, one
element per word. Otherwise, the expansion results in one word
only; with KSHARAYS, this is the first element of an array.
No field splitting is done on the result unless the
SHWORDSPLIT option is set.
$${{]name}}
If name is the name of a set parameter `1' is substituted, oth-
erwise `00' is substituted.
$${{name::-word}}
If name is set and is non-null then substitute its value; other-
wise substitute word. If name is missing, substitute word.
$${{name::==word}}
$${{name::::==word}}
In the first form, if name is unset or is null then set it to
word; in the second form, unconditionally set name to word. In
both forms, the value of the parameter is then substituted.
$${{name::??word}}
If name is set and is non-null then substitute its value; other-
wise, print word and exit from the shell. Interactive shells
instead return to the prompt. If word is omitted, then a stan-
dard message is printed.
$${{name::]word}}
If name is set and is non-null then substitute word; otherwise
substitute nothing.
If the colon is omitted from one of the above expressions containing a
colon, then the shell only checks whether name is set, not whether its
value is null.
In the following expressions, when name is an array and the substitu-
tion is not quoted, or if the `(@@)' flag or the name[@@] syntax is used,
matching and replacement is performed on each array element separately.
$${{name##pattern}}
$${{name####pattern}}
If the pattern matches the beginning of the value of name, then
substitute the value of name with the matched portion deleted;
otherwise, just substitute the value of name. In the first
form, the smallest matching pattern is preferred; in the second
form, the largest matching pattern is preferred.
$${{name%%pattern}}
$${{name%%%%pattern}}
If the pattern matches the end of the value of name, then sub-
stitute the value of name with the matched portion deleted; oth-
erwise, just substitute the value of name. In the first form,
the smallest matching pattern is preferred; in the second form,
the largest matching pattern is preferred.
$${{name::##pattern}}
If the pattern matches the value of name, then substitute the
empty string; otherwise, just substitute the value of name. If
name is an array the matching array elements are removed (use
the `()' flag to remove the non-matched elements).
$${{name/pattern/repl}}
$${{name//pattern/repl}}
Replace the longest possible match of pattern in the expansion
of parameter name by string repl. The first form replaces just
the first occurrence, the second form all occurrences. Both
pattern and repl are subject to double-quoted substitution, so
that expressions like $${{name/$$opat/$$npat}} will work, but note
the usual rule that pattern characters in $$opat are not treated
specially unless either the option GLOBSUBST is set, or $$opat
is instead substituted as $${{~~opat}}.
The pattern may begin with a `##', in which case the pattern must
match at the start of the string, or `%%', in which case it must
match at the end of the string. The repl may be an empty
string, in which case the final `/' may also be omitted. To
quote the final `/' in other cases it should be preceded by a
single backslash; this is not necessary if the `/' occurs inside
a substituted parameter. Note also that the `##' and `%%' are not
active if they occur inside a substituted parameter, even at the
start.
The first `/' may be preceded by a `::', in which case the match
will only succeed if it matches the entire word. Note also the
effect of the I and S parameter expansion flags below; however,
the flags M, R, B, E and N are not useful.
For example,
foo==""twinkle twinkle little star"" sub==""t**e"" rep==""spy""
print $${{foo//$${{~~sub}}/$$rep}}
print $${{(S)foo//$${{~~sub}}/$$rep}}
Here, the `~~' ensures that the text of $$sub is treated as a pat-
tern rather than a plain string. In the first case, the longest
match for t**e is substituted and the result is `spy star', while
in the second case, the shortest matches are taken and the
result is `spy spy lispy star'.
$${{##spec}}
If spec is one of the above substitutions, substitute the length
in characters of the result instead of the result itself. If
spec is an array expression, substitute the number of elements
of the result. Note that `^^', `==', and `~~', below, must appear
to the left of `##' when these forms are combined.
$${{^^spec}}
Turn on the RCEXPANDPARAM option for the evaluation of spec;
if the `^^' is doubled, turn it off. When this option is set,
array expansions of the form foo$${{xx}}bar, where the parameter xx
is set to (a b c), are substituted with `fooabar foobbar
foocbar' instead of the default `fooa b cbar'.
Internally, each such expansion is converted into the equivalent
list for brace expansion. E.g., $${{^^var}} becomes
{{$$var[1],,$$var[2],,...}}, and is processed as described in the sec-
tion `Brace Expansion' below. If word splitting is also in
effect the $$var[N] may themselves be split into different list
elements.
$${{==spec}}
Perform word splitting using the rules for SHWORDSPLIT during
the evaluation of spec, but regardless of whether the parameter
appears in double quotes; if the `==' is doubled, turn it off.
This forces parameter expansions to be split into separate words
before substitution, using IFS as a delimiter. This is done by
default in most other shells.
Note that splitting is applied to word in the assignment forms
of spec before the assignment to name is performed. This
affects the result of array assignments with the A flag.
$${{~~spec}}
Turn on the GLOBSUBST option for the evaluation of spec; if the
`~~' is doubled, turn it off. When this option is set, the
string resulting from the expansion will be interpreted as a
pattern anywhere that is possible, such as in filename expansion
and filename generation and pattern-matching contexts like the
right hand side of the `==' and `!!==' operators in conditions.
If a $${{...}} type parameter expression or a $$(...) type command substi-
tution is used in place of name above, it is expanded first and the
result is used as if it were the value of name. Thus it is possible to
perform nested operations: $${{$${{foo##head}}%%tail}} substitutes the value
of $$foo with both `head' and `tail' deleted. The form with $$(...) is
often useful in combination with the flags described next; see the
examples below. Each name or nested $${{...}} in a parameter expansion
may also be followed by a subscript expression as described in Array
Parameters in zshparam(1).
Note that double quotes may appear around nested expressions, in which
case only the part inside is treated as quoted; for example,
$${{(f)""$$(foo)""}} quotes the result of $$(foo), but the flag `(f)' (see
below) is applied using the rules for unquoted expansions. Note fur-
ther that quotes are themselves nested in this context; for example, in
""$${{(@@f)""$$(foo)""}}"", there are two sets of quotes, one surrounding the
whole expression, the other (redundant) surrounding the $$(foo) as
before.
Parameter Expansion Flags
If the opening brace is directly followed by an opening parenthesis,
the string up to the matching closing parenthesis will be taken as a
list of flags. In cases where repeating a flag is meaningful, the rep-
etitions need not be consecutive; for example, `(q%%q%%q)' means the same
thing as the more readable `(%%%%qqq)'. The following flags are sup-
ported:
%% Expand all %% escapes in the resulting words in the same way as
in in prompts (see the section `Prompt Expansion'). If this flag
is given twice, full prompt expansion is done on the resulting
words, depending on the setting of the PROMPTPERCENT,
PROMPTSUBST and PROMPTBANG options.
@@ In double quotes, array elements are put into separate words.
E.g., `""$${{(@@)foo}}""' is equivalent to `""$${{foo[@@]}}""' and
`""$${{(@@)foo[1,,2]}}""' is the same as `""$$foo[1]"" ""$$foo[2]""'. This
is distinct from field splitting by the the f, s or z flags,
which still applies within each array element.
A Create an array parameter with `$${{...==...}}', `$${{...::==...}}' or
`$${{...::::==...}}'. If this flag is repeated (as in `A'), create
an associative array parameter. Assignment is made before sort-
ing or padding. The name part may be a subscripted range for
ordinary arrays; the word part must be converted to an array,
for example by using `$${{(A)==name==...}}' to activate field split-
ting, when creating an associative array.
a With o or O, sort in array index order. Note that `oa' is there-
fore equivalent to the default but `Oa' is useful for obtaining
an array's elements in reverse order.
c With $${{##name}}, count the total number of characters in an array,
as if the elements were concatenated with spaces between them.
C Capitalize the resulting words. `Words' in this case refers to
sequences of alphanumeric characters separated by non-alphanu-
merics, not to words that result from field splitting.
e Perform parameter expansion, command substitution and arithmetic
expansion on the result. Such expansions can be nested but too
deep recursion may have unpredictable effects.
f Split the result of the expansion to lines. This is a shorthand
for `ps::\\n::'.
F Join the words of arrays together using newline as a separator.
This is a shorthand for `pj::\\n::'.
i With o or O, sort case-independently.
k If name refers to an associative array, substitute the keys
(element names) rather than the values of the elements. Used
with subscripts (including ordinary arrays), force indices or
keys to be substituted even if the subscript form refers to val-
ues. However, this flag may not be combined with subscript
ranges.
L Convert all letters in the result to lower case.
n With o or O, sort numerically.
o Sort the resulting words in ascending order.
O Sort the resulting words in descending order.
P This forces the value of the parameter name to be interpreted as
a further parameter name, whose value will be used where appro-
priate. If used with a nested parameter or command substitution,
the result of that will be taken as a parameter name in the same
way. For example, if you have `foo==bar' and `bar==baz', the
strings $${{(P)foo}}, $${{(P)$${{foo}}}}, and $${{(P)$$(echo bar)}} will be
expanded to `baz'.
q Quote the resulting words with backslashes. If this flag is
given twice, the resulting words are quoted in single quotes and
if it is given three times, the words are quoted in double
quotes. If it is given four times, the words are quoted in sin-
gle quotes preceded by a $$.
Q Remove one level of quotes from the resulting words.
t Use a string describing the type of the parameter where the
value of the parameter would usually appear. This string con-
sists of keywords separated by hyphens (`-'). The first keyword
in the string describes the main type, it can be one of
`scalar', `array', `integer', `float' or `association'. The
other keywords describe the type in more detail:
local for local parameters
left for left justified parameters
rightblanks
for right justified parameters with leading blanks
rightzeros
for right justified parameters with leading zeros
lower for parameters whose value is converted to all lower case
when it is expanded
upper for parameters whose value is converted to all upper case
when it is expanded
readonly
for readonly parameters
tag for tagged parameters
export for exported parameters
unique for arrays which keep only the first occurrence of dupli-
cated values
hide for parameters with the `hide' flag
special
for special parameters defined by the shell
u Expand only the first occurrence of each unique word.
U Convert all letters in the result to upper case.
v Used with k, substitute (as two consecutive words) both the key
and the value of each associative array element. Used with sub-
scripts, force values to be substituted even if the subscript
form refers to indices or keys.
V Make any special characters in the resulting words visible.
w With $${{##name}}, count words in arrays or strings; the s flag may
be used to set a word delimiter.
W Similar to w with the difference that empty words between
repeated delimiters are also counted.
X With this flag parsing errors occurring with the Q and e flags
or the pattern matching forms such as `$${{name##pattern}}' are
reported. Without the flag they are silently ignored.
z Split the result of the expansion into words using shell parsing
to find the words, i.e. taking into account any quoting in the
value.
Note that this is done very late, as for the `(s)' flag. So to
access single words in the result, one has to use nested expan-
sions as in `$${{$${{(z)foo}}[2]}}'. Likewise, to remove the quotes in
the resulting words one would do: `$${{(Q)$${{(z)foo}}}}'.
The following flags (except p) are followed by one or more arguments as
shown. Any character, or the matching pairs `(...)', `{{...}}', `[...]',
or `<<...>>', may be used in place of a colon as delimiters, but note
that when a flag takes more than one argument, a matched pair of delim-
iters must surround each argument.
p Recognize the same escape sequences as the print builtin in
string arguments to any of the flags described below.
j::string::
Join the words of arrays together using string as a separator.
Note that this occurs before field splitting by the
SHWORDSPLIT option.
l::expr::::string1::::string2::
Pad the resulting words on the left. Each word will be trun-
cated if required and placed in a field expr characters wide.
The space to the left will be filled with string1 (concatenated
as often as needed) or spaces if string1 is not given. If both
string1 and string2 are given, this string is inserted once
directly to the left of each word, before padding.
r::expr::::string1::::string2::
As l, but pad the words on the right and insert string2 on the
right.
s::string::
Force field splitting (see the option SHWORDSPLIT) at the sep-
arator string. Note that a string of two or more characters
means all must all match in sequence; this differs from the
treatment of two or more characters in the IFS parameter.
The following flags are meaningful with the $${{...##...}} or $${{...%%...}}
forms. The S and I flags may also be used with the $${{.../...}} forms.
S Search substrings as well as beginnings or ends; with ## start
from the beginning and with %% start from the end of the string.
With substitution via $${{.../...}} or $${{...//...}}, specifies
non-greedy matching, i.e. that the shortest instead of the long-
est match should be replaced.
I::expr::
Search the exprth match (where expr evaluates to a number).
This only applies when searching for substrings, either with the
S flag, or with $${{.../...}} (only the exprth match is substi-
tuted) or $${{...//...}} (all matches from the exprth on are sub-
stituted). The default is to take the first match.
The exprth match is counted such that there is either one or
zero matches from each starting position in the string, although
for global substitution matches overlapping previous replace-
ments are ignored. With the $${{...%%...}} and $${{...%%%%...}} forms,
the starting position for the match moves backwards from the end
as the index increases, while with the other forms it moves for-
ward from the start.
Hence with the string
which switch is the right switch for Ipswich??
substitutions of the form $${{(SI::N::)string##w**ch}} as N increases
from 1 will match and remove `which', `witch', `witch' and
`wich'; the form using `####' will match and remove `which switch
is the right switch for Ipswich', `witch is the right switch for
Ipswich', `witch for Ipswich' and `wich'. The form using `%%'
will remove the same matches as for `##', but in reverse order,
and the form using `%%%%' will remove the same matches as for `####'
in reverse order.
B Include the index of the beginning of the match in the result.
E Include the index of the end of the match in the result.
M Include the matched portion in the result.
N Include the length of the match in the result.
R Include the unmatched portion in the result (the Rest).
Rules
Here is a summary of the rules for substitution; this assumes that
braces are present around the substitution, i.e. $${{...}}. Some particu-
lar examples are given below. Note that the Zsh Development Group
accepts no responsibility for any brain damage which may occur during
the reading of the following rules.
1. Nested Substitution
If multiple nested $${{...}} forms are present, substitution is
performed from the inside outwards. At each level, the substi-
tution takes account of whether the current value is a scalar or
an array, whether the whole substitution is in double quotes,
and what flags are supplied to the current level of substitu-
tion, just as if the nested substitution were the outermost.
The flags are not propagated up to enclosing substitutions; the
nested substitution will return either a scalar or an array as
determined by the flags, possibly adjusted for quoting. All the
following steps take place where applicable at all levels of
substitution. Note that, unless the `(P)' flag is present, the
flags and any subscripts apply directly to the value of the
nested substitution; for example, the expansion $${{$${{foo}}}}
behaves exactly the same as $${{foo}}.
2. Parameter Subscripting
If the value is a raw parameter reference with a subscript, such
as $${{var[3]}}, the effect of subscripting is applied directly to
the parameter. Subscripts are evaluated left to right; subse-
quent subscripts apply to the scalar or array value yielded by
the previous subscript. Thus if var is an array, $${{var[1][2]}}
is the second character of the first word, but $${{var[2,,4][2]}} is
the entire third word (the second word of the range of words two
through four of the original array). Any number of subscripts
may appear.
3. Parameter Name Replacement
The effect of any (P) flag, which treats the value so far as a
parameter name and replaces it with the corresponding value, is
applied.
4. Double-Quoted Joining
If the value after this process is an array, and the substitu-
tion appears in double quotes, and no (@@) flag is present at the
current level, the words of the value are joined with the first
character of the parameter $$IFS, by default a space, between
each word (single word arrays are not modified). If the (j)
flag is present, that is used for joining instead of $$IFS.
5. Nested Subscripting
Any remaining subscripts (i.e. of a nested substitution) are
evaluated at this point, based on whether the value is an array
or a scalar. As with 2., multiple subscripts can appear. Note
that $${{foo[2,,4][2]}} is thus equivalent to $${{$${{foo[2,,4]}}[2]}} and
also to ""$${{$${{(@@)foo[2,,4]}}[2]}}"" (the nested substitution returns
an array in both cases), but not to ""$${{$${{foo[2,,4]}}[2]}}"" (the
nested substitution returns a scalar because of the quotes).
6. Modifiers
Any modifiers, as specified by a trailing `##', `%%', `/' (possi-
bly doubled) or by a set of modifiers of the form ::... (see the
section `Modifiers' in the section `History Expansion'), are
applied to the words of the value at this level.
7. Forced Joining
If the `(j)' flag is present, or no `(j)' flag is present but
the string is to be split as given by rules 8. or 9., and join-
ing did not take place at step 4., any words in the value are
joined together using the given string or the first character of
$$IFS if none. Note that the `(F)' flag implicitly supplies a
string for joining in this manner.
8. Forced Splitting
If one of the `(s)', `(f)' or `(z)' flags are present, or the
`==' specifier was present (e.g. $${{==var}}), the word is split on
occurrences of the specified string, or (for == with neither of
the two flags present) any of the characters in $$IFS.
9. Shell Word Splitting
If no `(s)', `(f)' or `==' was given, but the word is not quoted
and the option SHWORDSPLIT is set, the word is split on occur-
rences of any of the characters in $$IFS. Note this step, too,
takes place at all levels of a nested substitution.
100. Re-Evaluation
Any `(e)' flag is applied to the value, forcing it to be
re-examined for new parameter substitutions, but also for com-
mand and arithmetic substitutions.
11. Padding
Any padding of the value by the `(l.fill.)' or `(r.fill.)' flags
is applied.
12. Semantic Joining
In contexts where expansion semantics requires a single word to
result, all words are rejoined with the first character of IFS
between. So in `$${{(P)$${{(f)lines}}}}' the value of $${{lines}} is
split at newlines, but then must be joined again before the P
flag can be applied.
If a single word is not required, this rule is skipped.
Examples
The flag f is useful to split a double-quoted substitution line by
line. For example, $${{(f)""$$(<>
Matches any number in the range x to y, inclusive. Either of
the numbers may be omitted to make the range open-ended; hence
`<<->>' matches any number. To match individual digits, the [...]
form is more efficient.
Be careful when using other wildcards adjacent to patterns of
this form; for example, <<00-9>>** will actually match any number
whatsoever at the start of the string, since the `<<00-9>>' will
match the first digit, and the `**' will match any others. This
is a trap for the unwary, but is in fact an inevitable conse-
quence of the rule that the longest possible match always suc-
ceeds. Expressions such as `<<00-9>>[^^[::digit::]**' can be used
instead.
(...) Matches the enclosed pattern. This is used for grouping. If
the KSHGLOB option is set, then a `@@', `**', `]', `??' or `!!'
immediately preceding the `(' is treated specially, as detailed
below. The option SHGLOB prevents bare parentheses from being
used in this way, though the KSHGLOB option is still available.
Note that grouping cannot extend over multiple directories: it
is an error to have a `/' within a group (this only applies for
patterns used in filename generation). There is one exception:
a group of the form (pat/)## appearing as a complete path segment
can match a sequence of directories. For example, foo/(a**/)##bar
matches foo/bar, foo/any/bar, foo/any/anyother/bar, and so on.
xy Matches either x or y. This operator has lower precedence than
any other. The `' character must be within parentheses, to
avoid interpretation as a pipeline.
^^x (Requires EXTENDEDGLOB to be set.) Matches anything except the
pattern x. This has a higher precedence than `/', so `^^foo/bar'
will search directories in `.' except `./foo' for a file named
`bar'.
x~~y (Requires EXTENDEDGLOB to be set.) Match anything that matches
the pattern x but does not match y. This has lower precedence
than any operator except `', so `**/**~~foo/bar' will search for
all files in all directories in `.' and then exclude `foo/bar'
if there was such a match. Multiple patterns can be excluded by
`foo~~bar~~baz'. In the exclusion pattern (y), `/' and `.' are
not treated specially the way they usually are in globbing.
x## (Requires EXTENDEDGLOB to be set.) Matches zero or more occur-
rences of the pattern x. This operator has high precedence;
`12##' is equivalent to `1(2##)', rather than `(12)##'. It is an
error for an unquoted `##' to follow something which cannot be
repeated; this includes an empty string, a pattern already fol-
lowed by `####', or parentheses when part of a KSHGLOB pattern
(for example, `!!(foo)##' is invalid and must be replaced by
`**(!!(foo))').
x#### (Requires EXTENDEDGLOB to be set.) Matches one or more occur-
rences of the pattern x. This operator has high precedence;
`12####' is equivalent to `1(2####)', rather than `(12)####'. No more
than two active `##' characters may appear together.
ksh-like Glob Operators
If the KSHGLOB option is set, the effects of parentheses can be modi-
fied by a preceding `@@', `**', `]', `??' or `!!'. This character need not
be unquoted to have special effects, but the `(' must be.
@@(...) Match the pattern in the parentheses. (Like `(...)'.)
**(...) Match any number of occurrences. (Like `(...)##'.)
](...) Match at least one occurrence. (Like `(...)####'.)
??(...) Match zero or one occurrence. (Like `(...)'.)
!!(...) Match anything but the expression in parentheses. (Like
`(^^(...))'.)
Precedence
The precedence of the operators given above is (highest) `^^', `/', `~~',
`' (lowest); the remaining operators are simply treated from left to
right as part of a string, with `##' and `####' applying to the shortest
possible preceding unit (i.e. a character, `??', `[...]', `<<...>>', or a
parenthesised expression). As mentioned above, a `/' used as a direc-
tory separator may not appear inside parentheses, while a `' must do
so; in patterns used in other contexts than filename generation (for
example, in case statements and tests within `[...]'), a `/' is not
special; and `/' is also not special after a `~~' appearing outside
parentheses in a filename pattern.
Globbing Flags
There are various flags which affect any text to their right up to the
end of the enclosing group or to the end of the pattern; they require
the EXTENDEDGLOB option. All take the form (##X) where X may have one
of the following forms:
i Case insensitive: upper or lower case characters in the pattern
match upper or lower case characters.
l Lower case characters in the pattern match upper or lower case
characters; upper case characters in the pattern still only
match upper case characters.
I Case sensitive: locally negates the effect of i or l from that
point on.
b Activate backreferences for parenthesised groups in the pattern;
this does not work in filename generation. When a pattern with
a set of active parentheses is matched, the strings matched by
the groups are stored in the array $$match, the indices of the
beginning of the matched parentheses in the array $$mbegin, and
the indices of the end in the array $$mend, with the first ele-
ment of each array corresponding to the first parenthesised
group, and so on. These arrays are not otherwise special to the
shell. The indices use the same convention as does parameter
substitution, so that elements of $$mend and $$mbegin may be used
in subscripts; the KSHARAYS option is respected. Sets of
globbing flags are not considered parenthesised groups; only the
first nine active parentheses can be referenced.
For example,
foo==""a string with a message""
if [ $$foo == (aan)'' ''(##b)(**)'' ''** ];; then
print $${{foo[$$mbegin[1],,$$mend[1]}}
fi
prints `string with a'. Note that the first parenthesis is
before the (##b) and does not create a backreference.
Backreferences work with all forms of pattern matching other
than filename generation, but note that when performing matches
on an entire array, such as $${{array##pattern}}, or a global sub-
stitution, such as $${{param//pat/repl}}, only the data for the
last match remains available. In the case of global replace-
ments this may still be useful. See the example for the m flag
below.
The numbering of backreferences strictly follows the order of
the opening parentheses from left to right in the pattern
string, although sets of parentheses may be nested. There are
special rules for parentheses followed by `##' or `####'. Only the
last match of the parenthesis is remembered: for example, in `[
abab == (##b)([ab])## ]', only the final `b' is stored in
match[1]. Thus extra parentheses may be necessary to match the
complete segment: for example, use `X((abcd)##)Y' to match a
whole string of either `ab' or `cd' between `X' and `Y', using
the value of $$match[1] rather than $$match[2].
If the match fails none of the parameters is altered, so in some
cases it may be necessary to initialise them beforehand. If
some of the backreferences fail to match --- which happens if
they are in an alternate branch which fails to match, or if they
are followed by ## and matched zero times --- then the matched
string is set to the empty string, and the start and end indices
are set to -1.
Pattern matching with backreferences is slightly slower than
without.
B Deactivate backreferences, negating the effect of the b flag
from that point on.
m Set references to the match data for the entire string matched;
this is similar to backreferencing and does not work in filename
generation. The flag must be in effect at the end of the pat-
tern, i.e. not local to a group. The parameters $$MATCH, $$MBEGIN
and $$MEND will be set to the string matched and to the indices
of the beginning and end of the string, respectively. This is
most useful in parameter substitutions, as otherwise the string
matched is obvious.
For example,
arr==(veldt jynx grimps waqf zho buck)
print $${{arr//(##m)[aeiou]/$${{(U)MATCH}}}}
forces all the matches (i.e. all vowels) into uppercase, print-
ing `vEldt jynx grImps wAqf zhO bUck'.
Unlike backreferences, there is no speed penalty for using match
references, other than the extra substitutions required for the
replacement strings in cases such as the example shown.
M Deactivate the m flag, hence no references to match data will be
created.
anum Approximate matching: num errors are allowed in the string
matched by the pattern. The rules for this are described in the
next subsection.
s, e Unlike the other flags, these have only a local effect, and each
must appear on its own: `(##s)' and `(##e)' are the only valid
forms. The `(##s)' flag succeeds only at the start of the test
string, and the `(##e)' flag succeeds only at the end of the test
string; they correspond to `^^' and `$$' in standard regular
expressions. They are useful for matching path segments in pat-
terns other than those in filename generation (where path seg-
ments are in any case treated separately). For example,
`**((##s)/)test((##e)/)**' matches a path segment `test' in any of
the following strings: test, test/at/start, at/end/test,
in/test/middle.
Another use is in parameter substitution; for example
`$${{array/(##s)A**Z(##e)}}' will remove only elements of an array
which match the complete pattern `A**Z'. There are other ways of
performing many operations of this type, however the combination
of the substitution operations `/' and `//' with the `(##s)' and
`(##e)' flags provides a single simple and memorable method.
Note that assertions of the form `(^^(##s))' also work, i.e. match
anywhere except at the start of the string, although this actu-
ally means `anything except a zero-length portion at the start
of the string'; you need to use `(""""~~(##s))' to match a
zero-length portion of the string not at the start.
q A `q' and everything up to the closing parenthesis of the glob-
bing flags are ignored by the pattern matching code. This is
intended to support the use of glob qualifiers, see below. The
result is that the pattern `(##b)(**).c(##q.)' can be used both for
globbing and for matching against a string. In the former case,
the `(##q.)' will be treated as a glob qualifier and the `(##b)'
will not be useful, while in the latter case the `(##b)' is use-
ful for backreferences and the `(##q.)' will be ignored. Note
that colon modifiers in the glob qualifiers are also not applied
in ordinary pattern matching.
For example, the test string fooxx can be matched by the pattern
(##i)FOX, but not by (##l)FOX, (##i)FO(##I)X or ((##i)FOX)X. The
string (##ia2)readme specifies case-insensitive matching of readme with
up to two errors.
When using the ksh syntax for grouping both KSHGLOB and EXTENDEDGLOB
must be set and the left parenthesis should be preceded by @@. Note
also that the flags do not affect letters inside [...] groups, in other
words (##i)[a-z] still matches only lowercase letters. Finally, note
that when examining whole paths case-insensitively every directory must
be searched for all files which match, so that a pattern of the form
(##i)/foo/bar/... is potentially slow.
Approximate atching
When matching approximately, the shell keeps a count of the errors
found, which cannot exceed the number specified in the (##anum) flags.
Four types of error are recognised:
1. Different characters, as in fooxbar and fooybar.
2. Transposition of characters, as in banana and abnana.
3. A character missing in the target string, as with the pattern
road and target string rod.
4. An extra character appearing in the target string, as with stove
and strove.
Thus, the pattern (##a3)abcd matches dcba, with the errors occurring by
using the first rule twice and the second once, grouping the string as
[d][cb][a] and [a][bc][d].
Non-literal parts of the pattern must match exactly, including charac-
ters in character ranges: hence (##a1)?????? matches strings of length
four, by applying rule 4 to an empty part of the pattern, but not
strings of length two, since all the ?? must match. Other characters
which must match exactly are initial dots in filenames (unless the
GLOBDOTS option is set), and all slashes in filenames, so that a/bc is
two errors from ab/c (the slash cannot be transposed with another char-
acter). Similarly, errors are counted separately for non-contiguous
strings in the pattern, so that (abcd)ef is two errors from aebf.
When using exclusion via the ~~ operator, approximate matching is
treated entirely separately for the excluded part and must be activated
separately. Thus, (##a1)README~~README matches READ.ME but not README,
as the trailing README is matched without approximation. However,
(##a1)README~~(##a1)README does not match any pattern of the form READ?ME
as all such forms are now excluded.
Apart from exclusions, there is only one overall error count; however,
the maximum errors allowed may be altered locally, and this can be
delimited by grouping. For example, (##a1)cat((##a00)dog)fox allows one
error in total, which may not occur in the dog section, and the pattern
(##a1)cat(##a00)dog(##a1)fox is equivalent. Note that the point at which
an error is first found is the crucial one for establishing whether to
use approximation; for example, (##a1)abc(##a00)xyz will not match
abcdxyz, because the error occurs at the `x', where approximation is
turned off.
Entire path segments may be matched approximately, so that
`(##a1)/foo/d/is/available/at/the/bar' allows one error in any path seg-
ment. This is much less efficient than without the (##a1), however,
since every directory in the path must be scanned for a possible
approximate match. It is best to place the (##a1) after any path seg-
ments which are known to be correct.
Recursive Globbing
A pathname component of the form `(foo/)##' matches a path consisting of
zero or more directories matching the pattern foo.
As a shorthand, `****/' is equivalent to `(**/)##'; note that this there-
fore matches files in the current directory as well as subdirectories.
Thus:
ls (**/)##bar
or
ls ****/bar
does a recursive directory search for files named `bar' (potentially
including the file `bar' in the current directory). This form does not
follow symbolic links; the alternative form `******/' does, but is other-
wise identical. Neither of these can be combined with other forms of
globbing within the same path segment; in that case, the `**' operators
revert to their usual effect.
Glob Qualifiers
Patterns used for filename generation may end in a list of qualifiers
enclosed in parentheses. The qualifiers specify which filenames that
otherwise match the given pattern will be inserted in the argument
list.
If the option BAREGLOBQUAL is set, then a trailing set of parentheses
containing no `' or `(' characters (or `~~' if it is special) is taken
as a set of glob qualifiers. A glob subexpression that would normally
be taken as glob qualifiers, for example `(^^x)', can be forced to be
treated as part of the glob pattern by doubling the parentheses, in
this case producing `((^^x))'.
If the option EXTENDEDGLOB is set, a different syntax for glob quali-
fiers is available, namely `(##qx)' where x is any of the same glob
qualifiers used in the other format. The qualifiers must still appear
at the end of the pattern. However, with this syntax multiple glob
qualifiers may be chained together. They are treated as a logical AND
of the individual sets of flags. Also, as the syntax is unambiguous,
the expression will be treated as glob qualifiers just as long any
parentheses contained within it are balanced; appearance of `', `(' or
`~~' does not negate the effect. Note that qualifiers will be recog-
nised in this form even if a bare glob qualifier exists at the end of
the pattern, for example `**(##q**)(.)' will recognise executable regular
files if both options are set; however, mixed syntax should probably be
avoided for the sake of clarity.
A qualifier may be any one of the following:
/ directories
F `full' (i.e. non-empty) directories. Note that the opposite
sense (^^F) expands to empty directories and all non-directories.
Use (/^^F) for empty directories
. plain files
@@ symbolic links
== sockets
p named pipes (FIFOs)
** executable plain files (0100)
%% device files (character or block special)
%%b block special files
%%c character special files
r owner-readable files (0400)
w owner-writable files (0200)
x owner-executable files (0100)
A group-readable files (0040)
I group-writable files (0020)
E group-executable files (0010)
R world-readable files (0004)
W world-writable files (0002)
X world-executable files (0001)
s setuid files (04000)
S setgid files (02000)
t files with the sticky bit (01000)
fspec files with access rights matching spec. This spec may be a octal
number optionally preceded by a `==', a `]', or a `-'. If none of
these characters is given, the behavior is the same as for `=='.
The octal number describes the mode bits to be expected, if com-
bined with a `==', the value given must match the file-modes
exactly, with a `]', at least the bits in the given number must
be set in the file-modes, and with a `-', the bits in the number
must not be set. Giving a `??' instead of a octal digit anywhere
in the number ensures that the corresponding bits in the
file-modes are not checked, this is only useful in combination
with `=='.
If the qualifier `f' is followed by any other character anything
up to the next matching character (`[', `{{', and `<<' match `]',
`}}', and `>>' respectively, any other character matches itself)
is taken as a list of comma-separated sub-specs. Each sub-spec
may be either an octal number as described above or a list of
any of the characters `u', `g', `o', and `a', followed by a `==',
a `]', or a `-', followed by a list of any of the characters
`r', `w', `x', `s', and `t', or an octal digit. The first list
of characters specify which access rights are to be checked. If
a `u' is given, those for the owner of the file are used, if a
`g' is given, those of the group are checked, a `o' means to
test those of other users, and the `a' says to test all three
groups. The `==', `]', and `-' again says how the modes are to be
checked and have the same meaning as described for the first
form above. The second list of characters finally says which
access rights are to be expected: `r' for read access, `w' for
write access, `x' for the right to execute the file (or to
search a directory), `s' for the setuid and setgid bits, and `t'
for the sticky bit.
Thus, `**(f700??)' gives the files for which the owner has read,
write, and execute permission, and for which other group members
have no rights, independent of the permissions for other users.
The pattern `**(f-10000)' gives all files for which the owner does
not have execute permission, and `**(f::gu]w,,o-rx::)' gives the
files for which the owner and the other members of the group
have at least write permission, and for which other users don't
have read or execute permission.
estring
]cmd The string will be executed as shell code. The filename will be
included in the list if and only if the code returns a zero sta-
tus (usually the status of the last command). The first charac-
ter after the `e' will be used as a separator and anything up to
the next matching separator will be taken as the string; `[',
`{{', and `<<' match `]', `}}', and `>>', respectively, while any
other character matches itself. Note that expansions must be
quoted in the string to prevent them from being expanded before
globbing is done.
During the execution of string the filename currently being
tested is available in the parameter REPLY; the parameter may be
altered to a string to be inserted into the list instead of the
original filename. In addition, the parameter reply may be set
to an array or a string, which overrides the value of REPLY. If
set to an array, the latter is inserted into the command line
word by word.
For example, suppose a directory contains a single file
`lonely'. Then the expression `**(e::''reply==($${{REPLY}}{{1,,2}})''::)'
will cause the words `lonely1 lonely2' to be inserted into the
command line. Note the quotation marks.
The form ]cmd has the same effect, but no delimiters appear
around cmd. Instead, cmd is taken as the longest sequence of
characters following the ] that are alphanumeric or underscore.
Typically cmd will be the name of a shell function that contains
the appropriate test. For example,
nt() {{ [ $$REPLY -nt $$NTREF ] }}
NTREF==reffile
ls -l **(]nt)
lists all files in the directory that have been modified more
recently than reffile.
ddev files on the device dev
l[-]ct
files having a link count less than ct (-), greater than ct (]),
or equal to ct
U files owned by the effective user ID
G files owned by the effective group ID
uid files owned by user ID id if it is a number, if not, than the
character after the `u' will be used as a separator and the
string between it and the next matching separator (`[', `{{', and
`<<' match `]', `}}', and `>>' respectively, any other character
matches itself) will be taken as a user name, and the user ID of
this user will be taken (e.g. `u::foo::' or `u[foo]' for user
`foo')
gid like uid but with group IDs or names
a[whms][-]n
files accessed exactly n days ago. Files accessed within the
last n days are selected using a negative value for n (-n).
Files accessed more than n days ago are selected by a positive n
value (]n). Optional unit specifiers `M', `w', `h', `m' or `s'
(e.g. `ah5') cause the check to be performed with months (of 30
days), weeks, hours, minutes or seconds instead of days, respec-
tively. For instance, `echo **(ah-5)' would echo files accessed
within the last five hours.
m[whms][-]n
like the file access qualifier, except that it uses the file
modification time.
c[whms][-]n
like the file access qualifier, except that it uses the file
inode change time.
L[]-]n
files less than n bytes (-), more than n bytes (]), or exactly n
bytes in length. If this flag is directly followed by a `k'
(`K'), `m' (`M'), or `p' (`P') (e.g. `Lk-500') the check is per-
formed with kilobytes, megabytes, or blocks (of 512 bytes)
instead.
^^ negates all qualifiers following it
- toggles between making the qualifiers work on symbolic links
(the default) and the files they point to
M sets the MARKDIRS option for the current pattern
T appends a trailing qualifier mark to the filenames, analogous to
the LISTYPES option, for the current pattern (overrides M)
N sets the NULGLOB option for the current pattern
D sets the GLOBDOTS option for the current pattern
n sets the NUMERICGLOBSORT option for the current pattern
oc specifies how the names of the files should be sorted. If c is n
they are sorted by name (the default); if it is L they are
sorted depending on the size (length) of the files; if l they
are sorted by the number of links; if a, m, or c they are sorted
by the time of the last access, modification, or inode change
respectively; if d, files in subdirectories appear before those
in the current directory at each level of the search --- this is
best combined with other criteria, for example `odon' to sort on
names for files within the same directory. Note that a, m, and
c compare the age against the current time, hence the first name
in the list is the youngest file. Also note that the modifiers ^^
and - are used, so `**(^^-oL)' gives a list of all files sorted by
file size in descending order, following any symbolic links.
Oc like `o', but sorts in descending order; i.e. `**(^^oc)' is the
same as `**(Oc)' and `**(^^Oc)' is the same as `**(oc)'; `Od' puts
files in the current directory before those in subdirectories at
each level of the search.
[beg[,,end]
specifies which of the matched filenames should be included in
the returned list. The syntax is the same as for array sub-
scripts. beg and the optional end may be mathematical expres-
sions. As in parameter subscripting they may be negative to make
them count from the last match backward. E.g.: `**(-OL[1,,3])'
gives a list of the names of the three largest files.
More than one of these lists can be combined, separated by commas. The
whole list matches if at least one of the sublists matches (they are
`or'ed, the qualifiers in the sublists are `and'ed). Some qualifiers,
however, affect all matches generated, independent of the sublist in
which they are given. These are the qualifiers `M', `T', `N', `D',
`n', `o', `O' and the subscripts given in brackets (`[...]').
If a `::' appears in a qualifier list, the remainder of the expression
in parenthesis is interpreted as a modifier (see the section `Modi-
fiers' in the section `History Expansion'). Note that each modifier
must be introduced by a separate `::'. Note also that the result after
modification does not have to be an existing file. The name of any
existing file can be followed by a modifier of the form `(::..)' even if
no actual filename generation is performed. Thus:
ls **(-/)
lists all directories and symbolic links that point to directories, and
ls **(%%W)
lists all world-writable device files in the current directory, and
ls **(W,,X)
lists all files in the current directory that are world-writable or
world-executable, and
echo /tmp/foo**(u00^^@@::t)
outputs the basename of all root-owned files beginning with the string
`foo' in /tmp, ignoring symlinks, and
ls **.**~~(lexparse).[ch](^^D^^l1)
lists all files having a link count of one whose names contain a dot
(but not those starting with a dot, since GLOBDOTS is explicitly
switched off) except for lex.c, lex.h, parse.c and parse.h.
print b**.pro(##q::s/pro/shmo/)(##q.::s/builtin/shmiltin/)
demonstrates how colon modifiers and other qualifiers may be chained
together. The ordinary qualifier `.' is applied first, then the colon
modifiers in order from left to right. So if EXTENDEDGLOB is set and
the base pattern matches the regular file builtin.pro, the shell will
print `shmiltin.shmo'.
ZSHPARAM(1) ZSHPARAM(1)
NAME
zshparam - zsh parameters
DESCRIPTION
A parameter has a name, a value, and a number of attributes. A name
may be any sequence of alphanumeric characters and underscores, or the
single characters `**', `@@', `##', `??', `-', `$$', or `!!'. The value may
be a scalar (a string), an integer, an array (indexed numerically), or
an associative array (an unordered set of name-value pairs, indexed by
name). To declare the type of a parameter, or to assign a scalar or
integer value to a parameter, use the typeset builtin.
The value of a scalar or integer parameter may also be assigned by
writing:
name==value
If the integer attribute, -i, is set for name, the value is subject to
arithmetic evaluation. Furthermore, by replacing `==' with `]==', a
parameter can be added or appended to. See the section `Array Parame-
ters' for additional forms of assignment.
To refer to the value of a parameter, write `$$name' or `$${{name}}'. See
Parameter Expansion in zshexpn(1) for complete details.
In the parameter lists that follow, the mark `' indicates that the
parameter is special. Special parameters cannot have their type
changed or their readonly attribute turned off, and if a special param-
eter is unset, then later recreated, the special properties will be
retained. `' indicates that the parameter does not exist when the
shell initializes in sh or ksh emulation mode.
ARAY PARAMETERS
To assign an array value, write one of:
set -A name value ...
name==(value ...)
If no parameter name exists, an ordinary array parameter is created.
If the parameter name exists and is a scalar, it is replaced by a new
array. Ordinary array parameters may also be explicitly declared with:
typeset -a name
Associative arrays must be declared before assignment, by using:
typeset -A name
When name refers to an associative array, the list in an assignment is
interpreted as alternating keys and values:
set -A name key value ...
name==(key value ...)
Every key must have a value in this case. Note that this assigns to
the entire array, deleting any elements that do not appear in the list.
To create an empty array (including associative arrays), use one of:
set -A name
name==()
Array Subscripts
Individual elements of an array may be selected using a subscript. A
subscript of the form `[exp]' selects the single element exp, where exp
is an arithmetic expression which will be subject to arithmetic expan-
sion as if it were surrounded by `$$((...))'. The elements are numbered
beginning with 1, unless the KSHARAYS option is set in which case
they are numbered from zero.
Subscripts may be used inside braces used to delimit a parameter name,
thus `$${{foo[2]}}' is equivalent to `$$foo[2]'. If the KSHARAYS option
is set, the braced form is the only one that works, as bracketed
expressions otherwise are not treated as subscripts.
The same subscripting syntax is used for associative arrays, except
that no arithmetic expansion is applied to exp. However, the parsing
rules for arithmetic expressions still apply, which affects the way
that certain special characters must be protected from interpretation.
See Subscript Parsing below for details.
A subscript of the form `[**]' or `[@@]' evaluates to all elements of an
array; there is no difference between the two except when they appear
within double quotes. `""$$foo[**]""' evaluates to `""$$foo[1] $$foo[2]
...""', whereas `""$$foo[@@]""' evaluates to `""$$foo[1]"" ""$$foo[2]"" ...'. For
associative arrays, `[**]' or `[@@]' evaluate to all the values, in no
particular order. Note that this does not substitute the keys; see the
documentation for the `k' flag under Parameter Expansion Flags in zsh-
expn(1) for complete details. When an array parameter is referenced as
`$$name' (with no subscript) it evaluates to `$$name[**]', unless the
KSHARAYS option is set in which case it evaluates to `$${{name[00]}}'
(for an associative array, this means the value of the key `00', which
may not exist even if there are values for other keys).
A subscript of the form `[exp1,,exp2]' selects all elements in the range
exp1 to exp2, inclusive. (Associative arrays are unordered, and so do
not support ranges.) If one of the subscripts evaluates to a negative
number, say -n, then the nth element from the end of the array is used.
Thus `$$foo[-3]' is the third element from the end of the array foo, and
`$$foo[1,,-1]' is the same as `$$foo[**]'.
Subscripting may also be performed on non-array values, in which case
the subscripts specify a substring to be extracted. For example, if
FO is set to `foobar', then `echo $$FO[2,,5]' prints `ooba'.
Array Element Assignment
A subscript may be used on the left side of an assignment like so:
name[exp]==value
In this form of assignment the element or range specified by exp is
replaced by the expression on the right side. An array (but not an
associative array) may be created by assignment to a range or element.
Arrays do not nest, so assigning a parenthesized list of values to an
element or range changes the number of elements in the array, shifting
the other elements to accommodate the new values. (This is not sup-
ported for associative arrays.)
This syntax also works as an argument to the typeset command:
typeset ""name[exp]""==value
The value may not be a parenthesized list in this case; only sin-
gle-element assignments may be made with typeset. Note that quotes are
necessary in this case to prevent the brackets from being interpreted
as filename generation operators. The noglob precommand modifier could
be used instead.
To delete an element of an ordinary array, assign `()' to that element.
To delete an element of an associative array, use the unset command:
unset ""name[exp]""
Subscript Flags
If the opening bracket, or the comma in a range, in any subscript
expression is directly followed by an opening parenthesis, the string
up to the matching closing one is considered to be a list of flags, as
in `name[(flags)exp]'. The flags currently understood are:
w If the parameter subscripted is a scalar than this flag makes
subscripting work on words instead of characters. The default
word separator is whitespace.
s::string::
This gives the string that separates words (for use with the w
flag).
p Recognize the same escape sequences as the print builtin in the
string argument of a subsequent `s' flag.
f If the parameter subscripted is a scalar than this flag makes
subscripting work on lines instead of characters, i.e. with ele-
ments separated by newlines. This is a shorthand for `pws::\\n::'.
r Reverse subscripting: if this flag is given, the exp is taken as
a pattern and the result is the first matching array element,
substring or word (if the parameter is an array, if it is a
scalar, or if it is a scalar and the `w' flag is given, respec-
tively). The subscript used is the number of the matching ele-
ment, so that pairs of subscripts such as `$$foo[(r)??,,3]' and
`$$foo[(r)??,,(r)f**]' are possible if the parameter is not an
associative array. If the parameter is an associative array,
only the value part of each pair is compared to the pattern, and
the result is that value.
R Like `r', but gives the last match. For associative arrays,
gives all possible matches. May be used for assigning to ordi-
nary array elements, but not for assigning to associative
arrays.
i Like `r', but gives the index of the match instead; this may not
be combined with a second argument. On the left side of an
assignment, behaves like `r'. For associative arrays, the key
part of each pair is compared to the pattern, and the first
matching key found is the result.
I Like `i', but gives the index of the last match, or all possible
matching keys in an associative array.
k If used in a subscript on an associative array, this flag causes
the keys to be interpreted as patterns, and returns the value
for the first key found where exp is matched by the key. This
flag does not work on the left side of an assignment to an asso-
ciative array element. If used on another type of parameter,
this behaves like `r'.
K On an associative array this is like `k' but returns all values
where exp is matched by the keys. On other types of parameters
this has the same effect as `R'.
n::expr::
If combined with `r', `R', `i' or `I', makes them give the nth
or nth last match (if expr evaluates to n). This flag is
ignored when the array is associative.
b::expr::
If combined with `r', `R', `i' or `I', makes them begin at the
nth or nth last element, word, or character (if expr evaluates
to n). This flag is ignored when the array is associative.
e This flag has no effect and for ordinary arrays is retained for
backward compatibility only. For associative arrays, this flag
can be used to force ** or @@ to be interpreted as a single key
rather than as a reference to all values. This flag may be used
on the left side of an assignment.
See Parameter Expansion Flags (zshexpn(1)) for additional ways to
manipulate the results of array subscripting.
Subscript Parsing
This discussion applies mainly to associative array key strings and to
patterns used for reverse subscripting (the `r', `R', `i', etc. flags),
but it may also affect parameter substitutions that appear as part of
an arithmetic expression in an ordinary subscript.
It is possible to avoid the use of subscripts in assignments to asso-
ciative array elements by using the syntax:
aa]==(''key with ""**strange**"" characters'' ''value string'')
This adds a new key/value pair if the key is not already present, and
replaces the value for the existing key if it is.
The basic rule to remember when writing a subscript expression is that
all text between the opening `[' and the closing `]' is interpreted as
if it were in double quotes (see zshmisc(1)). However, unlike double
quotes which normally cannot nest, subscript expressions may appear
inside double-quoted strings or inside other subscript expressions (or
both!), so the rules have two important differences.
The first difference is that brackets (`[' and `]') must appear as bal-
anced pairs in a subscript expression unless they are preceded by a
backslash (`\\'). Therefore, within a subscript expression (and unlike
true double-quoting) the sequence `\\[' becomes `[', and similarly `\\]'
becomes `]'. This applies even in cases where a backslash is not nor-
mally required; for example, the pattern `[^^[]' (to match any character
other than an open bracket) should be written `[^^\\[]' in a reverse-sub-
script pattern. However, note that `\\[^^\\[\\]' and even `\\[^^[]' mean the
same thing, because backslashes are always stripped when they appear
before brackets!
The same rule applies to parentheses (`(' and `)') and braces (`{{' and
`}}'): they must appear either in balanced pairs or preceded by a back-
slash, and backslashes that protect parentheses or braces are removed
during parsing. This is because parameter expansions may be surrounded
balanced braces, and subscript flags are introduced by balanced paren-
thesis.
The second difference is that a double-quote (`""') may appear as part
of a subscript expression without being preceded by a backslash, and
therefore that the two characters `\\""' remain as two characters in the
subscript (in true double-quoting, `\\""' becomes `""'). However, because
of the standard shell quoting rules, any double-quotes that appear must
occur in balanced pairs unless preceded by a backslash. This makes it
more difficult to write a subscript expression that contains an odd
number of double-quote characters, but the reason for this difference
is so that when a subscript expression appears inside true dou-
ble-quotes, one can still write `\\""' (rather than `\\\\\\""') for `""'.
To use an odd number of double quotes as a key in an assignment, use
the typeset builtin and an enclosing pair of double quotes; to refer to
the value of that key, again use double quotes:
typeset -A aa
typeset ""aa[one\\""two\\""three\\""quotes]""==Q
print ""$$aa[one\\""two\\""three\\""quotes]""
It is important to note that the quoting rules do not change when a
parameter expansion with a subscript is nested inside another subscript
expression. That is, it is not necessary to use additional backslashes
within the inner subscript expression; they are removed only once, from
the innermost subscript outwards. Parameters are also expanded from
the innermost subscript first, as each expansion is encountered left to
right in the outer expression.
A further complication arises from a way in which subscript parsing is
not different from double quote parsing. As in true double-quoting,
the sequences `\\**', and `\\@@' remain as two characters when they appear
in a subscript expression. To use a literal `**' or `@@' as an associa-
tive array key, the `e' flag must be used:
typeset -A aa
aa[(e)**]==star
print $$aa[(e)**]
A last detail must be considered when reverse subscripting is per-
formed. Parameters appearing in the subscript expression are first
expanded and then the complete expression is interpreted as a pattern.
This has two effects: first, parameters behave as if GLOBSUBST were on
(and it cannot be turned off); second, backslashes are interpreted
twice, once when parsing the array subscript and again when parsing the
pattern. In a reverse subscript, it's necessary to use four back-
slashes to cause a single backslash to match literally in the pattern.
For complex patterns, it is often easiest to assign the desired pattern
to a parameter and then refer to that parameter in the subscript,
because then the backslashes, brackets, parentheses, etc., are seen
only when the complete expression is converted to a pattern. To match
the value of a parameter literally in a reverse subscript, rather than
as a pattern, use `$${{(q)name}}' (see zshexpn(1)) to quote the expanded
value.
Note that the `k' and `K' flags are reverse subscripting for an ordi-
nary array, but are not reverse subscripting for an associative array!
(For an associative array, the keys in the array itself are interpreted
as patterns by those flags; the subscript is a plain string in that
case.)
One final note, not directly related to subscripting: the numeric names
of positional parameters (described below) are parsed specially, so for
example `$$2foo' is equivalent to `$${{2}}foo'. Therefore, to use sub-
script syntax to extract a substring from a positional parameter, the
expansion must be surrounded by braces; for example, `$${{2[3,,5]}}' evalu-
ates to the third through fifth characters of the second positional
parameter, but `$$2[3,,5]' is the entire second parameter concatenated
with the filename generation pattern `[3,,5]'.
POSITIONAL PARAMETERS
The positional parameters provide access to the command-line arguments
of a shell function, shell script, or the shell itself; see the section
`Invocation', and also the section `Functions'. The parameter n, where
n is a number, is the nth positional parameter. The parameters **, @@
and argv are arrays containing all the positional parameters; thus
`$$argv[n]', etc., is equivalent to simply `$$n'.
Positional parameters may be changed after the shell or function starts
by using the set builtin, by assigning to the argv array, or by direct
assignment of the form `n==value' where n is the number of the posi-
tional parameter to be changed. This also creates (with empty values)
any of the positions from 1 to n that do not already have values. Note
that, because the positional parameters form an array, an array assign-
ment of the form `n==(value ...)' is allowed, and has the effect of
shifting all the values at positions greater than n by as many posi-
tions as necessary to accommodate the new values.
LOCAL PARAMETERS
Shell function executions delimit scopes for shell parameters. (Param-
eters are dynamically scoped.) The typeset builtin, and its alterna-
tive forms declare, integer, local and readonly (but not export), can
be used to declare a parameter as being local to the innermost scope.
When a parameter is read or assigned to, the innermost existing parame-
ter of that name is used. (That is, the local parameter hides any
less-local parameter.) However, assigning to a non-existent parameter,
or declaring a new parameter with export, causes it to be created in
the outermost scope.
Local parameters disappear when their scope ends. unset can be used to
delete a parameter while it is still in scope; any outer parameter of
the same name remains hidden.
Special parameters may also be made local; they retain their special
attributes unless either the existing or the newly-created parameter
has the -h (hide) attribute. This may have unexpected effects: there
is no default value, so if there is no assignment at the point the
variable is made local, it will be set to an empty value (or zero in
the case of integers). The following:
typeset PATH==/new/directory::$$PATH
is valid for temporarily allowing the shell or programmes called from
it to find the programs in /new/directory inside a function.
Note that the restriction in older versions of zsh that local parame-
ters were never exported has been removed.
PARAMETERS SET BY THE SHEL
The following parameters are automatically set by the shell:
!! The process ID of the last background command invoked.
## The number of positional parameters in decimal. Note that some
confusion may occur with the syntax $$##param which substitutes
the length of param. Use $${{##}} to resolve ambiguities. In par-
ticular, the sequence `$$##-...' in an arithmetic expression is
interpreted as the length of the parameter -, q.v.
ARGC
Same as ##.
$$ The process ID of this shell.
- Flags supplied to the shell on invocation or by the set or
setopt commands.
** An array containing the positional parameters.
argv
Same as **. Assigning to argv changes the local positional
parameters, but argv is not itself a local parameter. Deleting
argv with unset in any function deletes it everywhere, although
only the innermost positional parameter array is deleted (so **
and @@ in other scopes are not affected).
@@ Same as argv[@@], even when argv is not set.
?? The exit value returned by the last command.
00 The name used to invoke the current shell. If the FUNC-
TIONARGZERO option is set, this is set temporarily within a
shell function to the name of the function, and within a sourced
script to the name of the script.
status
Same as ??.
pipestatus
An array containing the exit values returned by all commands in
the last pipeline.
The last argument of the previous command. Also, this parameter
is set in the environment of every command executed to the full
pathname of the command.
CPUTYPE
The machine type (microprocessor class or machine model), as
determined at run time.
EGID
The effective group ID of the shell process. If you have suffi-
cient privileges, you may change the effective group ID of the
shell process by assigning to this parameter. Also (assuming
sufficient privileges), you may start a single command with a
different effective group ID by `(EGID==gid;; command)'
EUID
The effective user ID of the shell process. If you have suffi-
cient privileges, you may change the effective user ID of the
shell process by assigning to this parameter. Also (assuming
sufficient privileges), you may start a single command with a
different effective user ID by `(EUID==uid;; command)'
ERNO
The value of errno (see errno(3)) as set by the most recently
failed system call. This value is system dependent and is
intended for debugging purposes. It is also useful with the
zsh/system module which allows the number to be turned into a
name or message.
GID
The real group ID of the shell process. If you have sufficient
privileges, you may change the group ID of the shell process by
assigning to this parameter. Also (assuming sufficient privi-
leges), you may start a single command under a different group
ID by `(GID==gid;; command)'
HISTCMD
The current history line number in an interactive shell, in
other words the line number for the command that caused $$HISTCMD
to be read.
HOST The current hostname.
LINENO
The line number of the current line within the current script,
sourced file, or shell function being executed, whichever was
started most recently. Note that in the case of shell functions
the line number refers to the function as it appeared in the
original definition, not necessarily as displayed by the func-
tions builtin.
LOGNAME
If the corresponding variable is not set in the environment of
the shell, it is initialized to the login name corresponding to
the current login session. This parameter is exported by default
but this can be disabled using the typeset builtin.
MACHTYPE
The machine type (microprocessor class or machine model), as
determined at compile time.
OLDPWD The previous working directory. This is set when the shell ini-
tializes and whenever the directory changes.
OPTARG
The value of the last option argument processed by the getopts
command.
OPTIND
The index of the last option argument processed by the getopts
command.
OSTYPE The operating system, as determined at compile time.
PID
The process ID of the parent of the shell.
PWD The present working directory. This is set when the shell ini-
tializes and whenever the directory changes.
RANDOM
A pseudo-random integer from 0 to 32767, newly generated each
time this parameter is referenced. The random number generator
can be seeded by assigning a numeric value to RANDOM.
The values of RANDOM form an intentionally-repeatable
pseudo-random sequence; subshells that reference RANDOM will
result in identical pseudo-random values unless the value of
RANDOM is referenced or seeded in the parent shell in between
subshell invocations.
SECONDS
The number of seconds since shell invocation. If this parameter
is assigned a value, then the value returned upon reference will
be the value that was assigned plus the number of seconds since
the assignment.
Unlike other special parameters, the type of the SECONDS parame-
ter can be changed using the typeset command. Only integer and
one of the floating point types are allowed. For example,
`typeset -F SECONDS' causes the value to be reported as a float-
ing point number. The precision is six decimal places, although
not all places may be useful.
SHLVL
Incremented by one each time a new shell is started.
signals
An array containing the names of the signals.
TRYBLOCKEROR
In an always block, indicates whether the preceding list of code
caused an error. The value is 1 to indicate an error, 0 other-
wise. It may be reset, clearing the error condition. See Com-
plex Commands in zshmisc(1)
TY The name of the tty associated with the shell, if any.
TYIDLE
The idle time of the tty associated with the shell in seconds or
-1 if there is no such tty.
UID
The real user ID of the shell process. If you have sufficient
privileges, you may change the user ID of the shell by assigning
to this parameter. Also (assuming sufficient privileges), you
may start a single command under a different user ID by
`(UID==uid;; command)'
USERNAME
The username corresponding to the real user ID of the shell
process. If you have sufficient privileges, you may change the
username (and also the user ID and group ID) of the shell by
assigning to this parameter. Also (assuming sufficient privi-
leges), you may start a single command under a different user-
name (and user ID and group ID) by `(USERNAME==username;; com-
mand)'
VENDOR The vendor, as determined at compile time.
ZSHNAME
Expands to the basename of the command used to invoke this
instance of zsh.
ZSHVERSION
The version number of this zsh.
PARAMETERS USED BY THE SHEL
The following parameters are used by the shell.
In cases where there are two parameters with an upper- and lowercase
form of the same name, such as path and PATH, the lowercase form is an
array and the uppercase form is a scalar with the elements of the array
joined together by colons. These are similar to tied parameters cre-
ated via `typeset -T'. The normal use for the colon-separated form is
for exporting to the environment, while the array form is easier to
manipulate within the shell. Note that unsetting either of the pair
will unset the other; they retain their special properties when recre-
ated, and recreating one of the pair will recreate the other.
ARGV00 If exported, its value is used as the argv[00] of external com-
mands. Usually used in constructs like `ARGV00==emacs nethack'.
BAUD The baud rate of the current connection. Used by the line edi-
tor update mechanism to compensate for a slow terminal by delay-
ing updates until necessary. This may be profitably set to a
lower value in some circumstances, e.g. for slow modems dialing
into a communications server which is connected to a host via a
fast link; in this case, this variable would be set by default
to the speed of the fast link, and not the modem. This parame-
ter should be set to the baud rate of the slowest part of the
link for best performance. The compensation mechanism can be
turned off by setting the variable to zero.
cdpath (CDPATH )
An array (colon-separated list) of directories specifying the
search path for the cd command.
COLUMNS
The number of columns for this terminal session. Used for
printing select lists and for the line editor.
DIRSTACKSIZE
The maximum size of the directory stack. If the stack gets
larger than this, it will be truncated automatically. This is
useful with the AUTOPUSHD option.
ENV If the ENV environment variable is set when zsh is invoked as sh
or ksh, $$ENV is sourced after the profile scripts. The value of
ENV is subjected to parameter expansion, command substitution,
and arithmetic expansion before being interpreted as a pathname.
Note that ENV is not used unless zsh is emulating sh or ksh.
FCEDIT The default editor for the fc builtin.
fignore (FIGNORE )
An array (colon separated list) containing the suffixes of files
to be ignored during filename completion. However, if comple-
tion only generates files with suffixes in this list, then these
files are completed anyway.
fpath (FPATH )
An array (colon separated list) of directories specifying the
search path for function definitions. This path is searched
when a function with the -u attribute is referenced. If an exe-
cutable file is found, then it is read and executed in the cur-
rent environment.
histchars
Three characters used by the shell's history and lexical analy-
sis mechanism. The first character signals the start of a his-
tory expansion (default `!!'). The second character signals the
start of a quick history substitution (default `^^'). The third
character is the comment character (default `##').
HISTCHARS
Same as histchars. (Deprecated.)
HISTFILE
The file to save the history in when an interactive shell exits.
If unset, the history is not saved.
HISTSIZE
The maximum number of events stored in the internal history
list. If you use the HISTEXPIREDUPSFIRST option, setting
this value larger than the SAVEHIST size will give you the dif-
ference as a cushion for saving duplicated history events.
HOME
The default argument for the cd command.
IFS
Internal field separators (by default space, tab, newline and
NUL), that are used to separate words which result from command
or parameter expansion and words read by the read builtin. Any
characters from the set space, tab and newline that appear in
the IFS are called IFS white space. One or more IFS white space
characters or one non-IFS white space character together with
any adjacent IFS white space character delimit a field. If an
IFS white space character appears twice consecutively in the
IFS, this character is treated as if it were not an IFS white
space character.
KEYTIMEOUT
The time the shell waits, in hundredths of seconds, for another
key to be pressed when reading bound multi-character sequences.
LANG
This variable determines the locale category for any category
not specifically selected via a variable starting with `LC'.
LCAL
This variable overrides the value of the `LANG' variable and the
value of any of the other variables starting with `LC'.
LCOLATE
This variable determines the locale category for character col-
lation information within ranges in glob brackets and for sort-
ing.
LCTYPE
This variable determines the locale category for character han-
dling functions.
LCMESAGES
This variable determines the language in which messages should
be written. Note that zsh does not use message catalogs.
LCNUMERIC
This variable affects the decimal point character and thousands
separator character for the formatted input/output functions and
string conversion functions. Note that zsh ignores this setting
when parsing floating point mathematical expressions.
LCTIME
This variable determines the locale category for date and time
formatting in prompt escape sequences.
LINES
The number of lines for this terminal session. Used for print-
ing select lists and for the line editor.
LISTMAX
In the line editor, the number of matches to list without asking
first. If the value is negative, the list will be shown if it
spans at most as many lines as given by the absolute value. If
set to zero, the shell asks only if the top of the listing would
scroll off the screen.
LOGCHECK
The interval in seconds between checks for login/logout activity
using the watch parameter.
MAIL If this parameter is set and mailpath is not set, the shell
looks for mail in the specified file.
MAILCHECK
The interval in seconds between checks for new mail.
mailpath (MAILPATH )
An array (colon-separated list) of filenames to check for new
mail. Each filename can be followed by a `??' and a message that
will be printed. The message will undergo parameter expansion,
command substitution and arithmetic expansion with the variable
$$ defined as the name of the file that has changed. The
default message is `You have new mail'. If an element is a
directory instead of a file the shell will recursively check
every file in every subdirectory of the element.
manpath (MANPATH )
An array (colon-separated list) whose value is not used by the
shell. The manpath array can be useful, however, since setting
it also sets MANPATH, and vice versa.
modulepath (MODULEPATH )
An array (colon-separated list) of directories that zmodload
searches for dynamically loadable modules. This is initialized
to a standard pathname, usually `/usr/local/lib/zsh/$$ZSHVER-
SION'. (The `/usr/local/lib' part varies from installation to
installation.) For security reasons, any value set in the envi-
ronment when the shell is started will be ignored.
These parameters only exist if the installation supports dynamic
module loading.
NULCMD
The command name to assume if a redirection is specified with no
command. Defaults to cat. For sh/ksh behavior, change this to
::. For csh-like behavior, unset this parameter; the shell will
print an error message if null commands are entered.
path (PATH )
An array (colon-separated list) of directories to search for
commands. When this parameter is set, each directory is scanned
and all files found are put in a hash table.
POSTEDIT
This string is output whenever the line editor exits. It usu-
ally contains termcap strings to reset the terminal.
PROMPT
PROMPT2
PROMPT3
PROMPT4
Same as PS1, PS2, PS3 and PS4, respectively.
prompt
Same as PS1.
PS1
The primary prompt string, printed before a command is read.
the default is `%%m%%## '. It undergoes a special form of expan-
sion before being displayed; see the section `Prompt Expansion'.
PS2
The secondary prompt, printed when the shell needs more informa-
tion to complete a command. It is expanded in the same way as
PS1. The default is `%%>> ', which displays any shell constructs
or quotation marks which are currently being processed.
PS3
Selection prompt used within a select loop. It is expanded in
the same way as PS1. The default is `??## '.
PS4
The execution trace prompt. Default is `]%%N::%%i>> ', which dis-
plays the name of the current shell structure and the line num-
ber within it. In sh or ksh emulation, the default is `] '.
psvar (PSVAR )
An array (colon-separated list) whose first nine values can be
used in PROMPT strings. Setting psvar also sets PSVAR, and vice
versa.
READNULCMD
The command name to assume if a single input redirection is
specified with no command. Defaults to more.
REPORTIME
If nonnegative, commands whose combined user and system execu-
tion times (measured in seconds) are greater than this value
have timing statistics printed for them.
REPLY This parameter is reserved by convention to pass string values
between shell scripts and shell builtins in situations where a
function call or redirection are impossible or undesirable. The
read builtin and the select complex command may set REPLY, and
filename generation both sets and examines its value when evalu-
ating certain expressions. Some modules also employ REPLY for
similar purposes.
reply As REPLY, but for array values rather than strings.
RPROMPT
RPS1
This prompt is displayed on the right-hand side of the screen
when the primary prompt is being displayed on the left. This
does not work if the SINGLELINEZLE option is set. It is
expanded in the same way as PS1.
RPROMPT2
RPS2
This prompt is displayed on the right-hand side of the screen
when the secondary prompt is being displayed on the left. This
does not work if the SINGLELINEZLE option is set. It is
expanded in the same way as PS2.
SAVEHIST
The maximum number of history events to save in the history
file.
SPROMPT
The prompt used for spelling correction. The sequence `%%R'
expands to the string which presumably needs spelling correc-
tion, and `%%r' expands to the proposed correction. All other
prompt escapes are also allowed.
STY If this parameter is set in a command's environment, the shell
runs the stty command with the value of this parameter as argu-
ments in order to set up the terminal before executing the com-
mand. The modes apply only to the command, and are reset when it
finishes or is suspended. If the command is suspended and con-
tinued later with the fg or wait builtins it will see the modes
specified by STY, as if it were not suspended. This (inten-
tionally) does not apply if the command is continued via `kill
-CONT'. STY is ignored if the command is run in the back-
ground, or if it is in the environment of the shell but not
explicitly assigned to in the input line. This avoids running
stty at every external command by accidentally exporting it.
Also note that STY should not be used for window size specifi-
cations; these will not be local to the command.
TERM
The type of terminal in use. This is used when looking up term-
cap sequences. An assignment to TERM causes zsh to re-initial-
ize the terminal, even if the value does not change (e.g.,
`TERM==$$TERM'). It is necessary to make such an assignment upon
any change to the terminal definition database or terminal type
in order for the new settings to take effect.
TIMEFMT
The format of process time reports with the time keyword. The
default is `%%E real %%U user %%S system %%P %%J'. Recognizes the
following escape sequences, although not all may be available on
all systems, and some that are available may not be useful:
%%%% A `%%'.
%%U CPU seconds spent in user mode.
%%S CPU seconds spent in kernel mode.
%%E Elapsed time in seconds.
%%P The CPU percentage, computed as (100*%%U]%%S)/%%E.
%%W Number of times the process was swapped.
%%X The average amount in (shared) text space used in Kbytes.
%%D The average amount in (unshared) data/stack space used in
Kbytes.
%%K The total space used (%X]%D) in Kbytes.
%%M The maximum memory the process had in use at any time in
Kbytes.
%%F The number of major page faults (page needed to be
brought from disk).
%%R The number of minor page faults.
%%I The number of input operations.
%%O The number of output operations.
%%r The number of socket messages received.
%%s The number of socket messages sent.
%%k The number of signals received.
%%w Number of voluntary context switches (waits).
%%c Number of involuntary context switches.
%%J The name of this job.
A star may be inserted between the percent sign and flags print-
ing time. This cause the time to be printed in `hh::mm::ss.ttt'
format (hours and minutes are only printed if they are not
zero).
TMOUT If this parameter is nonzero, the shell will receive an ALRM
signal if a command is not entered within the specified number
of seconds after issuing a prompt. If there is a trap on
SIGALRM, it will be executed and a new alarm is scheduled using
the value of the TMOUT parameter after executing the trap. If
no trap is set, and the idle time of the terminal is not less
than the value of the TMOUT parameter, zsh terminates. Other-
wise a new alarm is scheduled to TMOUT seconds after the last
keypress.
TMPREFIX
A pathname prefix which the shell will use for all temporary
files. Note that this should include an initial part for the
file name as well as any directory names. The default is
`/tmp/zsh'.
watch (WATCH )
An array (colon-separated list) of login/logout events to
report. If it contains the single word `all', then all
login/logout events are reported. If it contains the single
word `notme', then all events are reported as with `all' except
$$USERNAME. An entry in this list may consist of a username, an
`@@' followed by a remote hostname, and a `%%' followed by a line
(tty). Any or all of these components may be present in an
entry; if a login/logout event matches all of them, it is
reported.
WATCHFMT
The format of login/logout reports if the watch parameter is
set. Default is `%%n has %%a %%l from %%m'. Recognizes the follow-
ing escape sequences:
%%n The name of the user that logged in/out.
%%a The observed action, i.e. "logged on" or "logged off".
%%l The line (tty) the user is logged in on.
%%M The full hostname of the remote host.
%%m The hostname up to the first `.'. If only the IP address
is available or the utmp field contains the name of an
X-windows display, the whole name is printed.
NOTE: The `%%m' and `%%M' escapes will work only if there
is a host name field in the utmp on your machine. Other-
wise they are treated as ordinary strings.
%%S (%%s)
Start (stop) standout mode.
%%U (%%u)
Start (stop) underline mode.
%%B (%%b)
Start (stop) boldface mode.
%%t
%%@@ The time, in 12-hour, am/pm format.
%%T The time, in 24-hour format.
%%w The date in `day-dd' format.
%%W The date in `mm/dd/yy' format.
%%D The date in `yy-mm-dd' format.
%%(x::true-text::false-text)
Specifies a ternary expression. The character following
the x is arbitrary; the same character is used to sepa-
rate the text for the "true" result from that for the
"false" result. Both the separator and the right paren-
thesis may be escaped with a backslash. Ternary expres-
sions may be nested.
The test character x may be any one of `l', `n', `m' or
`M', which indicate a `true' result if the corresponding
escape sequence would return a non-empty value; or it may
be `a', which indicates a `true' result if the watched
user has logged in, or `false' if he has logged out.
Other characters evaluate to neither true nor false; the
entire expression is omitted in this case.
If the result is `true', then the true-text is formatted
according to the rules above and printed, and the
false-text is skipped. If `false', the true-text is
skipped and the false-text is formatted and printed.
Either or both of the branches may be empty, but both
separators must be present in any case.
WORDCHARS
A list of non-alphanumeric characters considered part of a word
by the line editor.
ZBEP If set, this gives a string of characters, which can use all the
same codes as the bindkey command as described in the zsh/zle
module entry in zshmodules(1), that will be output to the termi-
nal instead of beeping. This may have a visible instead of an
audible effect; for example, the string `\\e[??5h\\e[??5l' on a
vt100 or xterm will have the effect of flashing reverse video on
and off (if you usually use reverse video, you should use the
string `\\e[??5l\\e[??5h' instead). This takes precedence over the
NOBEP option.
ZDOTDIR
The directory to search for shell startup files (.zshrc, etc),
if not $$HOME.
ZSHOPTIONS(1) ZSHOPTIONS(1)
NAME
zshoptions - zsh options
SPECIFYING OPTIONS
Options are primarily referred to by name. These names are case insen-
sitive and underscores are ignored. For example, `allexport' is equiv-
alent to `AlleXPort'.
The sense of an option name may be inverted by preceding it with `no',
so `setopt NoBeep' is equivalent to `unsetopt beep'. This inversion
can only be done once, so `nonobeep' is not a synonym for `beep'. Sim-
ilarly, `tify' is not a synonym for `nonotify' (the inversion of
`notify').
Some options also have one or more single letter names. There are two
sets of single letter options: one used by default, and another used to
emulate sh/ksh (used when the SHOPTIONLETERS option is set). The
single letter options can be used on the shell command line, or with
the set, setopt and unsetopt builtins, as normal Unix options preceded
by `-'.
The sense of the single letter options may be inverted by using `]'
instead of `-'. Some of the single letter option names refer to an
option being off, in which case the inversion of that name refers to
the option being on. For example, `]n' is the short name of `exec',
and `-n' is the short name of its inversion, `noexec'.
In strings of single letter options supplied to the shell at startup,
trailing whitespace will be ignored; for example the string `-f '
will be treated just as `-f', but the string `-f i' is an error. This
is because many systems which implement the `##!!' mechanism for calling
scripts do not strip trailing whitespace.
DESCRIPTION OF OPTIONS
In the following list, options set by default in all emulations are
marked ; those set by default only in csh, ksh, sh, or zsh emula-
tions are marked , , , as appropriate. When listing
options (by `setopt', `unsetopt', `set -o' or `set ]o'), those turned
on by default appear in the list prefixed with `no'. Hence (unless
KSHOPTIONPRINT is set), `setopt' shows all options whose settings are
changed from the default.
Changing Directories
AUTOCD (-J)
If a command is issued that can't be executed as a normal com-
mand, and the command is the name of a directory, perform the cd
command to that directory.
AUTOPUSHD (-N)
Make cd push the old directory onto the directory stack.
CDABLEVARS (-T)
If the argument to a cd command (or an implied cd with the
AUTOCD option set) is not a directory, and does not begin with
a slash, try to expand the expression as if it were preceded by
a `~~' (see the section `Filename Expansion').
CHASEDOTS
When changing to a directory containing a path segment `..'
which would otherwise be treated as canceling the previous seg-
ment in the path (in other words, `foo/..' would be removed from
the path, or if `..' is the first part of the path, the last
part of $$PWD would be deleted), instead resolve the path to the
physical directory. This option is overridden by CHASELINKS.
For example, suppose /foo/bar is a link to the directory
/alt/rod. Without this option set, `cd /foo/bar/..' changes to
/foo; with it set, it changes to /alt. The same applies if the
current directory is /foo/bar and `cd ..' is used. Note that
all other symbolic links in the path will also be resolved.
CHASELINKS (-w)
Resolve symbolic links to their true values when changing direc-
tory. This also has the effect of CHASEDOTS, i.e. a `..' path
segment will be treated as referring to the physical parent,
even if the preceding path segment is a symbolic link.
PUSHDIGNOREDUPS
Don't push multiple copies of the same directory onto the direc-
tory stack.
PUSHDMINUS
Exchanges the meanings of `]' and `-' when used with a number to
specify a directory in the stack.
PUSHDSILENT (-E)
Do not print the directory stack after pushd or popd.
PUSHDTOHOME (-D)
Have pushd with no arguments act like `pushd $$HOME'.
Completion
ALWAYSLASTPROMPT
If unset, key functions that list completions try to return to
the last prompt if given a numeric argument. If set these func-
tions try to return to the last prompt if given no numeric argu-
ment.
ALWAYSTOEND
If a completion is performed with the cursor within a word, and
a full completion is inserted, the cursor is moved to the end of
the word. That is, the cursor is moved to the end of the word
if either a single match is inserted or menu completion is per-
formed.
AUTOLIST (-9)
Automatically list choices on an ambiguous completion.
AUTOMENU
Automatically use menu completion after the second consecutive
request for completion, for example by pressing the tab key
repeatedly. This option is overridden by MENUCOMPLETE.
AUTONAMEDIRS
Any parameter that is set to the absolute name of a directory
immediately becomes a name for that directory, that will be used
by the `%%~~' and related prompt sequences, and will be available
when completion is performed on a word starting with `~~'. (Oth-
erwise, the parameter must be used in the form `~~param' first.)
AUTOPARAMKEYS
If a parameter name was completed and a following character
(normally a space) automatically inserted, and the next charac-
ter typed is one of those that have to come directly after the
name (like `}}', `::', etc.), the automatically added character is
deleted, so that the character typed comes immediately after the
parameter name. Completion in a brace expansion is affected
similarly: the added character is a `,,', which will be removed
if `}}' is typed next.
AUTOPARAMSLASH
If a parameter is completed whose content is the name of a
directory, then add a trailing slash instead of a space.
AUTOREMOVESLASH
When the last character resulting from a completion is a slash
and the next character typed is a word delimiter, a slash, or a
character that ends a command (such as a semicolon or an amper-
sand), remove the slash.
BASHAUTOLIST
On an ambiguous completion, automatically list choices when the
completion function is called twice in succession. This takes
precedence over AUTOLIST. The setting of LISTAMBIGUOUS is
respected. If AUTOMENU is set, the menu behaviour will then
start with the third press. Note that this will not work with
MENUCOMPLETE, since repeated completion calls immediately cycle
through the list in that case.
COMPLETEALIASES
Prevents aliases on the command line from being internally sub-
stituted before completion is attempted. The effect is to make
the alias a distinct command for completion purposes.
COMPLETEINWORD
If unset, the cursor is set to the end of the word if completion
is started. Otherwise it stays there and completion is done from
both ends.
GLOBCOMPLETE
When the current word has a glob pattern, do not insert all the
words resulting from the expansion but generate matches as for
completion and cycle through them like MENUCOMPLETE. The
matches are generated as if a `**' was added to the end of the
word, or inserted at the cursor when COMPLETEINWORD is set.
This actually uses pattern matching, not globbing, so it works
not only for files but for any completion, such as options, user
names, etc.
Note that when the pattern matcher is used, matching control
(for example, case-insensitive or anchored matching) cannot be
used. This limitation only applies when the current word con-
tains a pattern; simply turning on the GLOBCOMPLETE option does
not have this effect.
HASHLISTAL
Whenever a command completion is attempted, make sure the entire
command path is hashed first. This makes the first completion
slower.
LISTAMBIGUOUS
This option works when AUTOLIST or BASHAUTOLIST is also set.
If there is an unambiguous prefix to insert on the command line,
that is done without a completion list being displayed; in other
words, auto-listing behaviour only takes place when nothing
would be inserted. In the case of BASHAUTOLIST, this means
that the list will be delayed to the third call of the function.
LISTBEP
Beep on an ambiguous completion. More accurately, this forces
the completion widgets to return status 1 on an ambiguous com-
pletion, which causes the shell to beep if the option BEP is
also set; this may be modified if completion is called from a
user-defined widget.
LISTPACKED
Try to make the completion list smaller (occupying less lines)
by printing the matches in columns with different widths.
LISTROWSFIRST
Lay out the matches in completion lists sorted horizontally,
that is, the second match is to the right of the first one, not
under it as usual.
LISTYPES (-X)
When listing files that are possible completions, show the type
of each file with a trailing identifying mark.
MENUCOMPLETE (-Y)
On an ambiguous completion, instead of listing possibilities or
beeping, insert the first match immediately. Then when comple-
tion is requested again, remove the first match and insert the
second match, etc. When there are no more matches, go back to
the first one again. reverse-menu-complete may be used to loop
through the list in the other direction. This option overrides
AUTOMENU.
RECEXACT (-S)
In completion, recognize exact matches even if they are ambigu-
ous.
Expansion and Globbing
BADPATERN (]2)
If a pattern for filename generation is badly formed, print an
error message. (If this option is unset, the pattern will be
left unchanged.)
BAREGLOBQUAL
In a glob pattern, treat a trailing set of parentheses as a
qualifier list, if it contains no `', `(' or (if special) `~~'
characters. See the section `Filename Generation'.
BRACECL
Expand expressions in braces which would not otherwise undergo
brace expansion to a lexically ordered list of all the charac-
ters. See the section `Brace Expansion'.
CASEGLOB
Make globbing (filename generation) sensitive to case. Note
that other uses of patterns are always sensitive to case. If
the option is unset, the presence of any character which is spe-
cial to filename generation will cause case-insensitive match-
ing. For example, cvs(/) can match the directory CVS owing to
the presence of the globbing flag (unless the option
BAREGLOBQUAL is unset).
CSHNULGLOB
If a pattern for filename generation has no matches, delete the
pattern from the argument list; do not report an error unless
all the patterns in a command have no matches. Overrides
NOMATCH.
EQUALS
Perform == filename expansion. (See the section `Filename Expan-
sion'.)
EXTENDEDGLOB
Treat the `##', `~~' and `^^' characters as part of patterns for
filename generation, etc. (An initial unquoted `~~' always pro-
duces named directory expansion.)
GLOB (]F, ksh: ]f)
Perform filename generation (globbing). (See the section `File-
name Generation'.)
GLOBASIGN
If this option is set, filename generation (globbing) is per-
formed on the right hand side of scalar parameter assignments of
the form `name==pattern (e.g. `foo==**'). If the result has more
than one word the parameter will become an array with those
words as arguments. This option is provided for backwards com-
patibility only: globbing is always performed on the right hand
side of array assignments of the form `name==(value)' (e.g.
`foo==(**)') and this form is recommended for clarity; with this
option set, it is not possible to predict whether the result
will be an array or a scalar.
GLOBDOTS (-4)
Do not require a leading `.' in a filename to be matched explic-
itly.
GLOBSUBST
Treat any characters resulting from parameter expansion as being
eligible for file expansion and filename generation, and any
characters resulting from command substitution as being eligible
for filename generation. Braces (and commas in between) do not
become eligible for expansion.
IGNOREBRACES (-I)
Do not perform brace expansion.
KSHGLOB
In pattern matching, the interpretation of parentheses is
affected by a preceding `@@', `**', `]', `??' or `!!'. See the sec-
tion `Filename Generation'.
MAGICEQUALSUBST
All unquoted arguments of the form `anything==expression' appear-
ing after the command name have filename expansion (that is,
where expression has a leading `~~' or `==') performed on expres-
sion as if it were a parameter assignment. The argument is not
otherwise treated specially; it is passed to the command as a
single argument, and not used as an actual parameter assignment.
For example, in echo foo==~~/bar::~~/rod, both occurrences of ~~
would be replaced. Note that this happens anyway with typeset
and similar statements.
This option respects the setting of the KSHTYPESET option. In
other words, if both options are in effect, arguments looking
like assignments will not undergo wordsplitting.
MARKDIRS (-8, ksh: -X)
Append a trailing `/' to all directory names resulting from
filename generation (globbing).
NOMATCH (]3)
If a pattern for filename generation has no matches, print an
error, instead of leaving it unchanged in the argument list.
This also applies to file expansion of an initial `~~' or `=='.
NULGLOB (-G)
If a pattern for filename generation has no matches, delete the
pattern from the argument list instead of reporting an error.
Overrides NOMATCH.
NUMERICGLOBSORT
If numeric filenames are matched by a filename generation pat-
tern, sort the filenames numerically rather than lexicographi-
cally.
RCEXPANDPARAM (-P)
Array expansions of the form `foo$${{xx}}bar', where the parameter
xx is set to (a b c), are substituted with `fooabar foobbar
foocbar' instead of the default `fooa b cbar'.
SHGLOB
Disables the special meaning of `(', `', `)' and '<<' for glob-
bing the result of parameter and command substitutions, and in
some other places where the shell accepts patterns. This option
is set by default if zsh is invoked as sh or ksh.
UNSET (]u, ksh: ]u)
Treat unset parameters as if they were empty when substituting.
Otherwise they are treated as an error.
History
APENDHISTORY
If this is set, zsh sessions will append their history list to
the history file, rather than overwrite it. Thus, multiple par-
allel zsh sessions will all have their history lists added to
the history file, in the order they are killed.
BANGHIST (]K)
Perform textual history expansion, csh-style, treating the char-
acter `!!' specially.
EXTENDEDHISTORY
Save each command's beginning timestamp (in seconds since the
epoch) and the duration (in seconds) to the history file. The
format of this prefixed data is:
`::::::'.
HISTALOWCLOBER
Add `' to output redirections in the history. This allows his-
tory references to clobber files even when CLOBER is unset.
HISTBEP
Beep when an attempt is made to access a history entry which
isn't there.
HISTEXPIREDUPSFIRST
If the internal history needs to be trimmed to add the current
command line, setting this option will cause the oldest history
event that has a duplicate to be lost before losing a unique
event from the list. You should be sure to set the value of
HISTSIZE to a larger number than SAVEHIST in order to give you
some room for the duplicated events, otherwise this option will
behave just like HISTIGNOREALDUPS once the history fills up
with unique events.
HISTFINDNODUPS
When searching for history entries in the line editor, do not
display duplicates of a line previously found, even if the
duplicates are not contiguous.
HISTIGNOREALDUPS
If a new command line being added to the history list duplicates
an older one, the older command is removed from the list (even
if it is not the previous event).
HISTIGNOREDUPS (-h)
Do not enter command lines into the history list if they are
duplicates of the previous event.
HISTIGNORESPACE (-g)
Remove command lines from the history list when the first char-
acter on the line is a space, or when one of the expanded
aliases contains a leading space. Note that the command lingers
in the internal history until the next command is entered before
it vanishes, allowing you to briefly reuse or edit the line. If
you want to make it vanish right away without entering another
command, type a space and press return.
HISTNOFUNCTIONS
Remove function definitions from the history list. Note that
the function lingers in the internal history until the next com-
mand is entered before it vanishes, allowing you to briefly re-
use or edit the definition.
HISTNOSTORE
Remove the history (fc -l) command from the history list when
invoked. Note that the command lingers in the internal history
until the next command is entered before it vanishes, allowing
you to briefly reuse or edit the line.
HISTREDUCEBLANKS
Remove superfluous blanks from each command line being added to
the history list.
HISTSAVENODUPS
When writing out the history file, older commands that duplicate
newer ones are omitted.
HISTVERIFY
Whenever the user enters a line with history expansion, don't
execute the line directly; instead, perform history expansion
and reload the line into the editing buffer.
INCAPENDHISTORY
This options works like APENDHISTORY except that new history
lines are added to the $$HISTFILE incrementally (as soon as they
are entered), rather than waiting until the shell is killed.
The file is periodically trimmed to the number of lines speci-
fied by $$SAVEHIST, but can exceed this value between trimmings.
SHAREHISTORY
This option both imports new commands from the history file, and
also causes your typed commands to be appended to the history
file (the latter is like specifying INCAPENDHISTORY). The
history lines are also output with timestamps ala EXTENDEDHIS-
TORY (which makes it easier to find the spot where we left off
reading the file after it gets re-written).
By default, history movement commands visit the imported lines
as well as the local lines, but you can toggle this on and off
with the set-local-history zle binding. It is also possible to
create a zle widget that will make some commands ignore imported
commands, and some include them.
If you find that you want more control over when commands get
imported, you may wish to turn SHAREHISTORY off,
INCAPENDHISTORY on, and then manually import commands when-
ever you need them using `fc -RI'.
Initialisation
ALEXPORT (-a, ksh: -a)
All parameters subsequently defined are automatically exported.
GLOBALEXPORT (<>)
If this option is set, passing the -x flag to the builtins
declare, float, integer, readonly and typeset (but not local)
will also set the -g flag; hence parameters exported to the
environment will not be made local to the enclosing function,
unless they were already or the flag ]g is given explicitly. If
the option is unset, exported parameters will be made local in
just the same way as any other parameter.
This option is set by default for backward compatibility; it is
not recommended that its behaviour be relied upon. Note that
the builtin export always sets both the -x and -g flags, and
hence its effect extends beyond the scope of the enclosing func-
tion; this is the most portable way to achieve this behaviour.
GLOBALRCS (-d)
If this option is unset, the startup files /etc/zprofile,
/etc/zshrc, /etc/zlogin and /etc/zlogout will not be run. It
can be disabled and re-enabled at any time, including inside
local startup files (.zshrc, etc.).
RCS (]f)
After /etc/zshenv is sourced on startup, source the .zshenv,
/etc/zprofile, .zprofile, /etc/zshrc, .zshrc, /etc/zlogin, .zlo-
gin, and .zlogout files, as described in the section `Files'.
If this option is unset, the /etc/zshenv file is still sourced,
but any of the others will not be; it can be set at any time to
prevent the remaining startup files after the currently execut-
ing one from being sourced.
Input/Output
ALIASES
Expand aliases.
CLOBER (]C, ksh: ]C)
Allows `>>' redirection to truncate existing files, and `>>>>' to
create files. Otherwise `>>!!' or `>>' must be used to truncate a
file, and `>>>>!!' or `>>>>' to create a file.
CORECT (-00)
Try to correct the spelling of commands. Note that, when the
HASHLISTAL option is not set or when some directories in the
path are not readable, this may falsely report spelling errors
the first time some commands are used.
CORECTAL (-O)
Try to correct the spelling of all arguments in a line.
DVORAK Use the Dvorak keyboard instead of the standard qwerty keyboard
as a basis for examining spelling mistakes for the CORECT and
CORECTAL options and the spell-word editor command.
FLOWCONTROL
If this option is unset, output flow control via start/stop
characters (usually assigned to ^S/^Q) is disabled in the
shell's editor.
IGNOREOF (-7)
Do not exit on end-of-file. Require the use of exit or logout
instead. However, ten consecutive EOFs will cause the shell to
exit anyway, to avoid the shell hanging if its tty goes away.
Also, if this option is set and the Zsh Line Editor is used,
widgets implemented by shell functions can be bound to EOF (nor-
mally Control-D) without printing the normal warning message.
This works only for normal widgets, not for completion widgets.
INTERACTIVECOMENTS (-k)
Allow comments even in interactive shells.
HASHCMDS
Note the location of each command the first time it is executed.
Subsequent invocations of the same command will use the saved
location, avoiding a path search. If this option is unset, no
path hashing is done at all. However, when CORECT is set, com-
mands whose names do not appear in the functions or aliases hash
tables are hashed in order to avoid reporting them as spelling
errors.
HASHDIRS
Whenever a command name is hashed, hash the directory containing
it, as well as all directories that occur earlier in the path.
Has no effect if neither HASHCMDS nor CORECT is set.
MAILWARNING (-U)
Print a warning message if a mail file has been accessed since
the shell last checked.
PATHDIRS (-Q)
Perform a path search even on command names with slashes in
them. Thus if `/usr/local/bin' is in the user's path, and he or
she types `X11/xinit', the command `/usr/local/bin/X11/xinit'
will be executed (assuming it exists). Commands explicitly
beginning with `/', `./' or `../' are not subject to the path
search. This also applies to the . builtin.
Note that subdirectories of the current directory are always
searched for executables specified in this form. This takes
place before any search indicated by this option, and regardless
of whether `.' or the current directory appear in the command
search path.
PRINTEIGHTBIT
Print eight bit characters literally in completion lists, etc.
This option is not necessary if your system correctly returns
the printability of eight bit characters (see ctype(3)).
PRINTEXITVALUE (-1)
Print the exit value of programs with non-zero exit status.
RCQUOTES
Allow the character sequence `''''' to signify a single quote
within singly quoted strings. Note this does not apply in
quoted strings using the format $$''...'', where a backslashed sin-
gle quote can be used.
RMSTARSILENT (-H)
Do not query the user before executing `rm **' or `rm path/**'.
RMSTARWAIT
If querying the user before executing `rm **' or `rm path/**',
first wait ten seconds and ignore anything typed in that time.
This avoids the problem of reflexively answering `yes' to the
query when one didn't really mean it. The wait and query can
always be avoided by expanding the `**' in ZLE (with tab).
SHORTLOPS
Allow the short forms of for, repeat, select, if, and function
constructs.
SUNKEYBOARDHACK (-L)
If a line ends with a backquote, and there are an odd number of
backquotes on the line, ignore the trailing backquote. This is
useful on some keyboards where the return key is too small, and
the backquote key lies annoyingly close to it.
Job Control
AUTOCONTINUE
With this option set, stopped jobs that are removed from the job
table with the disown builtin command are automatically sent a
CONT signal to make them running.
AUTORESUME (-W)
Treat single word simple commands without redirection as candi-
dates for resumption of an existing job.
BGNICE (-6)
Run all background jobs at a lower priority. This option is set
by default.
CHECKJOBS
Report the status of background and suspended jobs before exit-
ing a shell with job control; a second attempt to exit the shell
will succeed. NOCHECKJOBS is best used only in combination
with NOHUP, else such jobs will be killed automatically.
The check is omitted if the commands run from the previous com-
mand line included a `jobs' command, since it is assumed the
user is aware that there are background or suspended jobs. A
`jobs' command run from the precmd function is not counted for
this purpose.
HUP
Send the HUP signal to running jobs when the shell exits.
LONGLISTJOBS (-R)
List jobs in the long format by default.
MONITOR (-m, ksh: -m)
Allow job control. Set by default in interactive shells.
NOTIFY (-5, ksh: -b)
Report the status of background jobs immediately, rather than
waiting until just before printing a prompt.
Prompting
PROMPTBANG
If set, `!!' is treated specially in prompt expansion. See the
section `Prompt Expansion'.
PROMPTCR (]V)
Print a carriage return just before printing a prompt in the
line editor. This is on by default as multi-line editing is
only possible if the editor knows where the start of the line
appears.
PROMPTPERCENT
If set, `%%' is treated specially in prompt expansion. See the
section `Prompt Expansion'.
PROMPTSUBST
If set, parameter expansion, command substitution and arithmetic
expansion are performed in prompts. Substitutions within
prompts do not affect the command status.
TRANSIENTRPROMPT
Remove any right prompt from display when accepting a command
line. This may be useful with terminals with other cut/paste
methods.
Scripts and Functions
CBASES
Output hexadecimal numbers in the standard C format, for example
`00xF' instead of the usual `16##F'. If the option OCTALZEROES
is also set (it is not by default), octal numbers will be
treated similarly and hence appear as `0077' instead of `8##77'.
This option has no effect on the choice of the output base, nor
on the output of bases other than hexadecimal and octal. Note
that these formats will be understood on input irrespective of
the setting of CBASES.
EREXIT (-e, ksh: -e)
If a command has a non-zero exit status, execute the ZER trap,
if set, and exit. This is disabled while running initialization
scripts.
ERETURN
If a command has a non-zero exit status, return immediately from
the enclosing function. The logic is identical to that for
EREXIT, except that an implicit return statement is executed
instead of an exit. This will trigger an exit at the outermost
level of a non-interactive script.
EVALINENO
If set, line numbers of expressions evaluated using the builtin
eval are tracked separately of the enclosing environment. This
applies both to the parameter LINENO and the line number output
by the prompt escape %%i. If the option is set, the prompt
escape %%N will output the string `(eval)' instead of the script
or function name as an indication. (The two prompt escapes are
typically used in the parameter PS4 to be output when the option
XTRACE is set.) If EVALINENO is unset, the line number of the
surrounding script or function is retained during the evalua-
tion.
EXEC (]n, ksh: ]n)
Do execute commands. Without this option, commands are read and
checked for syntax errors, but not executed. This option cannot
be turned off in an interactive shell, except when `-n' is sup-
plied to the shell at startup.
FUNCTIONARGZERO
When executing a shell function or sourcing a script, set $$00
temporarily to the name of the function/script.
LOCALOPTIONS
If this option is set at the point of return from a shell func-
tion, all the options (including this one) which were in force
upon entry to the function are restored. Otherwise, only this
option and the XTRACE and PRINTEXITVALUE options are restored.
Hence if this is explicitly unset by a shell function the other
options in force at the point of return will remain so. A shell
function can also guarantee itself a known shell configuration
with a formulation like `emulate -L zsh'; the -L activates
LOCALOPTIONS.
LOCALTRAPS
If this option is set when a signal trap is set inside a func-
tion, then the previous status of the trap for that signal will
be restored when the function exits. Note that this option must
be set prior to altering the trap behaviour in a function;
unlike LOCALOPTIONS, the value on exit from the function is
irrelevant. However, it does not need to be set before any
global trap for that to be correctly restored by a function.
For example,
unsetopt localtraps
trap - INT
fn() {{ setopt localtraps;; trap '''' INT;; sleep 3;; }}
will restore normally handling of SIGINT after the function
exits.
MULTIOS
Perform implicit tees or cats when multiple redirections are
attempted (see the section `Redirection').
OCTALZEROES
Interpret any integer constant beginning with a 0 as octal, per
IE Std 1003.2-1992 (ISO 9945-2:1993). This is not enabled by
default as it causes problems with parsing of, for example, date
and time strings with leading zeroes.
TYPESETSILENT
If this is unset, executing any of the `typeset' family of com-
mands with no options and a list of parameters that have no val-
ues to be assigned but already exist will display the value of
the parameter. If the option is set, they will only be shown
when parameters are selected with the `-m' option. The option
`-p' is available whether or not the option is set.
VERBOSE (-v, ksh: -v)
Print shell input lines as they are read.
XTRACE (-x, ksh: -x)
Print commands and their arguments as they are executed.
Shell Emulation
BSDECHO
Make the echo builtin compatible with the BSD echo(1) command.
This disables backslashed escape sequences in echo strings
unless the -e option is specified.
CSHJUNKIEHISTORY
A history reference without an event specifier will always refer
to the previous command. Without this option, such a history
reference refers to the same event as the previous history ref-
erence, defaulting to the previous command.
CSHJUNKIELOPS
Allow loop bodies to take the form `list; end' instead of `do
list; done'.
CSHJUNKIEQUOTES
Changes the rules for single- and double-quoted text to match
that of csh. These require that embedded newlines be preceded
by a backslash; unescaped newlines will cause an error message.
In double-quoted strings, it is made impossible to escape `$$',
```' or `""' (and `\\' itself no longer needs escaping). Command
substitutions are only expanded once, and cannot be nested.
CSHNULCMD
Do not use the values of NULCMD and READNULCMD when running
redirections with no command. This make such redirections fail
(see the section `Redirection').
KSHARAYS
Emulate ksh array handling as closely as possible. If this
option is set, array elements are numbered from zero, an array
parameter without subscript refers to the first element instead
of the whole array, and braces are required to delimit a sub-
script (`$${{path[2]}}' rather than just `$$path[2]').
KSHAUTOLOAD
Emulate ksh function autoloading. This means that when a func-
tion is autoloaded, the corresponding file is merely executed,
and must define the function itself. (By default, the function
is defined to the contents of the file. However, the most com-
mon ksh-style case - of the file containing only a simple defi-
nition of the function - is always handled in the ksh-compatible
manner.)
KSHOPTIONPRINT
Alters the way options settings are printed: instead of separate
lists of set and unset options, all options are shown, marked
`on' if they are in the non-default state, `off' otherwise.
KSHTYPESET
Alters the way arguments to the typeset family of commands,
including declare, export, float, integer, local and readonly,
are processed. Without this option, zsh will perform normal
word splitting after command and parameter expansion in argu-
ments of an assignment; with it, word splitting does not take
place in those cases.
POSIXBUILTINS
When this option is set the command builtin can be used to exe-
cute shell builtin commands. Parameter assignments specified
before shell functions and special builtins are kept after the
command completes unless the special builtin is prefixed with
the command builtin. Special builtins are ., ::, break, con-
tinue, declare, eval, exit, export, integer, local, readonly,
return, set, shift, source, times, trap and unset.
SHFILEXPANSION
Perform filename expansion (e.g., ~ expansion) before parameter
expansion, command substitution, arithmetic expansion and brace
expansion. If this option is unset, it is performed after brace
expansion, so things like `~~$$USERNAME' and `~~{{pfalstad,,rc}}' will
work.
SHNULCMD
Do not use the values of NULCMD and READNULCMD when doing
redirections, use `::' instead (see the section `Redirection').
SHOPTIONLETERS
If this option is set the shell tries to interpret single letter
options (which are used with set and setopt) like ksh does.
This also affects the value of the - special parameter.
SHWORDSPLIT (-y)
Causes field splitting to be performed on unquoted parameter
expansions. Note that this option has nothing to do with word
splitting. (See the section `Parameter Expansion'.)
TRAPSASYNC
While waiting for a program to exit, handle signals and run
traps immediately. Otherwise the trap is run after a child
process has exited. Note this does not affect the point at
which traps are run for any case other than when the shell is
waiting for a child process.
Shell State
INTERACTIVE (-i, ksh: -i)
This is an interactive shell. This option is set upon initiali-
sation if the standard input is a tty and commands are being
read from standard input. (See the discussion of SHINSTDIN.)
This heuristic may be overridden by specifying a state for this
option on the command line. The value of this option cannot be
changed anywhere other than the command line.
LOGIN (-l, ksh: -l)
This is a login shell. If this option is not explicitly set,
the shell is a login shell if the first character of the argv[00]
passed to the shell is a `-'.
PRIVILEGED (-p, ksh: -p)
Turn on privileged mode. This is enabled automatically on
startup if the effective user (group) ID is not equal to the
real user (group) ID. Turning this option off causes the effec-
tive user and group IDs to be set to the real user and group
IDs. This option disables sourcing user startup files. If zsh
is invoked as `sh' or `ksh' with this option set, /etc/suidpro-
file is sourced (after /etc/profile on interactive shells).
Sourcing ~~/.profile is disabled and the contents of the ENV
variable is ignored. This option cannot be changed using the -m
option of setopt and unsetopt, and changing it inside a function
always changes it globally regardless of the LOCALOPTIONS
option.
RESTRICTED (-r)
Enables restricted mode. This option cannot be changed using
unsetopt, and setting it inside a function always changes it
globally regardless of the LOCALOPTIONS option. See the sec-
tion `Restricted Shell'.
SHINSTDIN (-s, ksh: -s)
Commands are being read from the standard input. Commands are
read from standard input if no command is specified with -c and
no file of commands is specified. If SHINSTDIN is set explic-
itly on the command line, any argument that would otherwise have
been taken as a file to run will instead be treated as a normal
positional parameter. Note that setting or unsetting this
option on the command line does not necessarily affect the state
the option will have while the shell is running - that is purely
an indicator of whether on not commands are actually being read
from standard input. The value of this option cannot be changed
anywhere other than the command line.
SINGLECOMAND (-t, ksh: -t)
If the shell is reading from standard input, it exits after a
single command has been executed. This also makes the shell
non-interactive, unless the INTERACTIVE option is explicitly set
on the command line. The value of this option cannot be changed
anywhere other than the command line.
Zle
BEP (]B)
Beep on error in ZLE.
EMACS If ZLE is loaded, turning on this option has the equivalent
effect of `bindkey -e'. In addition, the VI option is unset.
Turning it off has no effect. The option setting is not guaran-
teed to reflect the current keymap. This option is provided for
compatibility; bindkey is the recommended interface.
OVERSTRIKE
Start up the line editor in overstrike mode.
SINGLELINEZLE (-M)
Use single-line command line editing instead of multi-line.
VI If ZLE is loaded, turning on this option has the equivalent
effect of `bindkey -v'. In addition, the EMACS option is unset.
Turning it off has no effect. The option setting is not guaran-
teed to reflect the current keymap. This option is provided for
compatibility; bindkey is the recommended interface.
ZLE (-Z)
Use the zsh line editor. Set by default in interactive shells
connected to a terminal.
OPTION ALIASES
Some options have alternative names. These aliases are never used for
output, but can be used just like normal option names when specifying
options to the shell.
BRACEXPAND
NOIGNOREBRACES (ksh and bash compatibility)
DOTGLOB
GLOBDOTS (bash compatibility)
HASHAL
HASHCMDS (bash compatibility)
HISTAPEND
APENDHISTORY (bash compatibility)
HISTEXPAND
BANGHIST (bash compatibility)
LOG NOHISTNOFUNCTIONS (ksh compatibility)
MAILWARN
MAILWARNING (bash compatibility)
ONECMD
SINGLECOMAND (bash compatibility)
PHYSICAL
CHASELINKS (ksh and bash compatibility)
PROMPTVARS
PROMPTSUBST (bash compatibility)
STDIN SHINSTDIN (ksh compatibility)
TRACKAL
HASHCMDS (ksh compatibility)
SINGLE LETER OPTIONS
Default set
-00 CORECT
-1 PRINTEXITVALUE
-2 NOBADPATERN
-3 NONOMATCH
-4 GLOBDOTS
-5 NOTIFY
-6 BGNICE
-7 IGNOREOF
-8 MARKDIRS
-9 AUTOLIST
-B NOBEP
-C NOCLOBER
-D PUSHDTOHOME
-E PUSHDSILENT
-F NOGLOB
-G NULGLOB
-H RMSTARSILENT
-I IGNOREBRACES
-J AUTOCD
-K NOBANGHIST
-L SUNKEYBOARDHACK
-M SINGLELINEZLE
-N AUTOPUSHD
-O CORECTAL
-P RCEXPANDPARAM
-Q PATHDIRS
-R LONGLISTJOBS
-S RECEXACT
-T CDABLEVARS
-U MAILWARNING
-V NOPROMPTCR
-W AUTORESUME
-X LISTYPES
-Y MENUCOMPLETE
-Z ZLE
-a ALEXPORT
-e EREXIT
-f NORCS
-g HISTIGNORESPACE
-h HISTIGNOREDUPS
-i INTERACTIVE
-k INTERACTIVECOMENTS
-l LOGIN
-m MONITOR
-n NOEXEC
-p PRIVILEGED
-r RESTRICTED
-s SHINSTDIN
-t SINGLECOMAND
-u NOUNSET
-v VERBOSE
-w CHASELINKS
-x XTRACE
-y SHWORDSPLIT
sh/ksh emulation set
-C NOCLOBER
-T TRAPSASYNC
-X MARKDIRS
-a ALEXPORT
-b NOTIFY
-e EREXIT
-f NOGLOB
-i INTERACTIVE
-l LOGIN
-m MONITOR
-n NOEXEC
-p PRIVILEGED
-r RESTRICTED
-s SHINSTDIN
-t SINGLECOMAND
-u NOUNSET
-v VERBOSE
-x XTRACE
Also note
-A Used by set for setting arrays
-b Used on the command line to specify end of option processing
-c Used on the command line to specify a single command
-m Used by setopt for pattern-matching option setting
-o Used in all places to allow use of long option names
-s Used by set to sort positional parameters
ZSHBUILTINS(1) ZSHBUILTINS(1)
NAME
zshbuiltins - zsh built-in commands
SHEL BUILTIN COMANDS
- simple command
See the section `Precommand Modifiers'.
. file [ arg ... ]
Read commands from file and execute them in the current shell
environment.
If file does not contain a slash, or if PATHDIRS is set, the
shell looks in the components of $$path to find the directory
containing file. Files in the current directory are not read
unless `.' appears somewhere in $$path. If a file named
`file.zwc' is found, is newer than file, and is the compiled
form (created with the zcompile builtin) of file, then commands
are read from that file instead of file.
If any arguments arg are given, they become the positional
parameters; the old positional parameters are restored when the
file is done executing. The exit status is the exit status of
the last command executed.
:: [ arg ... ]
This command does nothing, although normal argument expansions
is performed which may have effects on shell parameters. A zero
exit code is returned.
alias [ {]-}}gmrsL ] [ name[==value] ... ]
For each name with a corresponding value, define an alias with
that value. A trailing space in value causes the next word to
be checked for alias expansion. If the -g flag is present,
define a global alias; global aliases are expanded even if they
do not occur in command position.
If the -s flags is present, define a suffix alias: if the com-
mand word on a command line is in the form `text.name', where
text is any non-empty string, it is replaced by the text `value
text.name'. Note that name is treated as a literal string, not
a pattern. A trailing space in value is not special in this
case. For example,
alias -s ps==gv
will cause the command `**.ps' to be expanded to `gv **.ps'. As
alias expansion is carried out earlier than globbing, the `**.ps'
will then be expanded. Suffix aliases constitute a different
name space from other aliases (so in the above example it is
still possible to create an alias for the command ps) and the
two sets are never listed together.
For each name with no value, print the value of name, if any.
With no arguments, print all currently defined aliases other
than suffix aliases. If the -m flag is given the arguments are
taken as patterns (they should be quoted to preserve them from
being interpreted as glob patterns), and the aliases matching
these patterns are printed. When printing aliases and one of
the -g, -r or -s flags is present, restrict the printing to
global, regular or suffix aliases, respectively; a regular alias
is one which is neither a global nor a suffix alias. Using `]'
instead of `-', or ending the option list with a single `]',
prevents the values of the aliases from being printed.
If the -L flag is present, then print each alias in a manner
suitable for putting in a startup script. The exit status is
nonzero if a name (with no value) is given for which no alias
has been defined.
autoload [ {]-}UXktz ] [ -w ] [ name ... ]
Equivalent to functions -u, with the exception of -X/]X and -w.
The flag -X may be used only inside a shell function, and may
not be followed by a name. It causes the calling function to be
marked for autoloading and then immediately loaded and executed,
with the current array of positional parameters as arguments.
This replaces the previous definition of the function. If no
function definition is found, an error is printed and the func-
tion remains undefined and marked for autoloading.
The flag ]X attempts to load each name as an autoloaded func-
tion, but does not execute it. The exit status is zero (suc-
cess) if the function was not previously defined and a defini-
tion for it was found. This does not replace any existing defi-
nition of the function. The exit status is nonzero (failure) if
the function was already defined or when no definition was
found. In the latter case the function remains undefined and
marked for autoloading. If ksh-style autoloading is enabled,
the function created will contain the contents of the file plus
a call to the function itself appended to it, thus giving normal
ksh autoloading behaviour on the first call to the function.
With the -w flag, the names are taken as names of files compiled
with the zcompile builtin, and all functions defined in them are
marked for autoloading.
bg [ job ... ]
job ... &&
Put each specified job in the background, or the current job if
none is specified.
bindkey
See the section `Zle Builtins' in zshzle(1).
break [ n ]
Exit from an enclosing for, while, until, select or repeat loop.
If n is specified, then break n levels instead of just one.
builtin name [ args ... ]
Executes the builtin name, with the given args.
bye Same as exit.
cap See the section `The zsh/cap Module' in zshmodules(1).
cd [ -sLP ] [ arg ]
cd [ -sLP ] old new
cd [ -sLP ] {]-}n
Change the current directory. In the first form, change the
current directory to arg, or to the value of $$HOME if arg is not
specified. If arg is `-', change to the value of $$OLDPWD, the
previous directory. Otherwise, if a directory named arg is not
found in the current directory and arg does not begin with a
slash, search each component of the shell parameter cdpath. If
no directory is found and the option CDABLEVARS is set, and a
parameter named arg exists whose value begins with a slash,
treat its value as the directory. In that case, the parameter
is added to the named directory hash table.
The second form of cd substitutes the string new for the string
old in the name of the current directory, and tries to change to
this new directory.
The third form of cd extracts an entry from the directory stack,
and changes to that directory. An argument of the form `]n'
identifies a stack entry by counting from the left of the list
shown by the dirs command, starting with zero. An argument of
the form `-n' counts from the right. If the PUSHDMINUS option
is set, the meanings of `]' and `-' in this context are swapped.
If the -s option is specified, cd refuses to change the current
directory if the given pathname contains symlinks. If the -P
option is given or the CHASELINKS option is set, symbolic links
are resolved to their true values. If the -L option is given
symbolic links are followed regardless of the state of the
CHASELINKS option.
chdir Same as cd.
clone See the section `The zsh/clone Module' in zshmodules(1).
command [ -pvV ] simple command
The simple command argument is taken as an external command
instead of a function or builtin and is executed. If the
POSIXBUILTINS option is set, builtins will also be executed but
certain special properties of them are suppressed. The -p flag
causes a default path to be searched instead of that in $$path.
With the -v flag, command is similar to whence and with -V, it
is equivalent to whence -v.
See also the section `Precommand Modifiers'.
comparguments
See the section `The zsh/computil Module' in zshmodules(1).
compcall
See the section `The zsh/compctl Module' in zshmodules(1).
compctl
See the section `The zsh/compctl Module' in zshmodules(1).
compdescribe
See the section `The zsh/computil Module' in zshmodules(1).
compfiles
See the section `The zsh/computil Module' in zshmodules(1).
compgroups
See the section `The zsh/computil Module' in zshmodules(1).
compquote
See the section `The zsh/computil Module' in zshmodules(1).
comptags
See the section `The zsh/computil Module' in zshmodules(1).
comptry
See the section `The zsh/computil Module' in zshmodules(1).
compvalues
See the section `The zsh/computil Module' in zshmodules(1).
continue [ n ]
Resume the next iteration of the enclosing for, while, until,
select or repeat loop. If n is specified, break out of n-1
loops and resume at the nth enclosing loop.
declare
Same as typeset.
dirs [ -c ] [ arg ... ]
dirs [ -lpv ]
With no arguments, print the contents of the directory stack.
Directories are added to this stack with the pushd command, and
removed with the cd or popd commands. If arguments are speci-
fied, load them onto the directory stack, replacing anything
that was there, and push the current directory onto the stack.
-c clear the directory stack.
-l print directory names in full instead of using of using ~~
expressions.
-p print directory entries one per line.
-v number the directories in the stack when printing.
disable [ -afmrs ] name ...
Temporarily disable the named hash table elements. The default
is to disable builtin commands. This allows you to use an
external command with the same name as a builtin command. The
-a option causes disable to act on regular or global aliases.
The -s option causes disable to act on suffix aliases. The -f
option causes disable to act on shell functions. The -r options
causes disable to act on reserved words. Without arguments all
disabled hash table elements from the corresponding hash table
are printed. With the -m flag the arguments are taken as pat-
terns (which should be quoted to prevent them from undergoing
filename expansion), and all hash table elements from the corre-
sponding hash table matching these patterns are disabled. Dis-
abled objects can be enabled with the enable command.
disown [ job ... ]
job ... &&
job ... &&!!
Remove the specified jobs from the job table; the shell will no
longer report their status, and will not complain if you try to
exit an interactive shell with them running or stopped. If no
job is specified, disown the current job.
If the jobs are currently stopped and the AUTOCONTINUE option
is not set, a warning is printed containing information about
how to make them running after they have been disowned. If one
of the latter two forms is used, the jobs will automatically be
made running, independent of the setting of the AUTOCONTINUE
option.
echo [ -neE ] [ arg ... ]
Write each arg on the standard output, with a space separating
each one. If the -n flag is not present, print a newline at the
end. echo recognizes the following escape sequences:
\\a bell character
\\b backspace
\\c suppress final newline
\\e escape
\\f form feed
\\n linefeed (newline)
\\r carriage return
\\t horizontal tab
\\v vertical tab
\\\\ backslash
\\00N character code in octal
\\xN character code in hexadecimal
\\uN unicode character code in hexadecimal
\\UN
unicode character code in hexadecimal
The -E flag, or the BSDECHO option, can be used to disable
these escape sequences. In the latter case, -e flag can be used
to enable them.
echotc See the section `The zsh/termcap Module' in zshmodules(1).
echoti See the section `The zsh/terminfo Module' in zshmodules(1).
emulate [ -LR ] {zshshkshcsh}
Set up zsh options to emulate the specified shell as much as
possible. csh will never be fully emulated. If the argument is
not one of the shells listed above, zsh will be used as a
default; more precisely, the tests performed on the argument are
the same as those used to determine the emulation at startup
based on the shell name, see the section `Compatibility' in zsh-
misc(1) . If the -R option is given, all options are reset to
their default value corresponding to the specified emulation
mode, except for certain options describing the interactive
environment; otherwise, only those options likely to cause
portability problems in scripts and functions are altered. If
the -L option is given, the options LOCALOPTIONS and
LOCALTRAPS will be set as well, causing the effects of the emu-
late command and any setopt and trap commands to be local to the
immediately surrounding shell function, if any; normally these
options are turned off in all emulation modes except ksh.
enable [ -afmrs ] name ...
Enable the named hash table elements, presumably disabled ear-
lier with disable. The default is to enable builtin commands.
The -a option causes enable to act on regular or global aliases.
The -s option causes enable to act on suffix aliases. The -f
option causes enable to act on shell functions. The -r option
causes enable to act on reserved words. Without arguments all
enabled hash table elements from the corresponding hash table
are printed. With the -m flag the arguments are taken as pat-
terns (should be quoted) and all hash table elements from the
corresponding hash table matching these patterns are enabled.
Enabled objects can be disabled with the disable builtin com-
mand.
eval [ arg ... ]
Read the arguments as input to the shell and execute the result-
ing command in the current shell process.
exec simple command
See the section `Precommand Modifiers'.
exit [ n ]
Exit the shell with the exit code specified by n; if none is
specified, use the exit code from the last command executed. An
EOF condition will also cause the shell to exit, unless the
IGNOREOF option is set.
export [ name[==value] ... ]
The specified names are marked for automatic export to the envi-
ronment of subsequently executed commands. Equivalent to type-
set -gx. If a parameter specified does not already exist, it is
created in the global scope.
false [ arg ... ]
Do nothing and return an exit code of 1.
fc [ -e ename ] [ -nlrdDfEim ] [ old==new ... ] [ first [ last ] ]
fc -p [ -a ] [ filename [ histsize [ savehistsize ] ] ]
fc -P
fc -ARWI [ filename ]
Select a range of commands from first to last from the history
list. The arguments first and last may be specified as a number
or as a string. A negative number is used as an offset to the
current history event number. A string specifies the most
recent event beginning with the given string. All substitutions
old==new, if any, are then performed on the commands.
If the -l flag is given, the resulting commands are listed on
standard output. If the -m flag is also given the first argu-
ment is taken as a pattern (should be quoted) and only the his-
tory events matching this pattern will be shown. Otherwise the
editor program ename is invoked on a file containing these his-
tory events. If ename is not given, the value of the parameter
FCEDIT is used. If ename is `-', no editor is invoked. When
editing is complete, the edited command is executed.
If first is not specified, it will be set to -1 (the most recent
event), or to -16 if the -l flag is given. If last is not spec-
ified, it will be set to first, or to -1 if the -l flag is
given.
The flag -r reverses the order of the commands and the flag -n
suppresses command numbers when listing. Also when listing, -d
prints timestamps for each command, and -f prints full time-date
stamps. Adding the -E flag causes the dates to be printed as
`dd.mm.yyyy', instead of the default `mm/dd/yyyy'. Adding the
-i flag causes the dates to be printed in ISO8601 `yyyy-mm-dd'
format. With the -D flag, fc prints elapsed times.
`fc -p' pushes the current history list onto a stack and
switches to a new history list. If the -a option is also speci-
fied, this history list will be automatically popped when the
current function scope is exited, which is a much better solu-
tion than creating a trap function to call `fc -P' manually. If
no arguments are specified, the history list is left empty,
$$HISTFILE is unset, and $$HISTSIZE & $$SAVEHIST are set to their
default values. If one argument is given, $$HISTFILE is set to
that filename, $$HISTSIZE & $$SAVEHIST are left unchanged, and the
history file is read in (if it exists) to initialize the new
list. If a second argument is specified, $$HISTSIZE & $$SAVEHIST
are instead set to the single specified numeric value. Finally,
if a third argument is specified, $$SAVEHIST is set to a separate
value from $$HISTSIZE. You are free to change these environment
values for the new history list however you desire in order to
manipulate the new history list.
`fc -P' pops the history list back to an older list saved by `fc
-p'. The current list is saved to its $$HISTFILE before it is
destroyed (assuming that $$HISTFILE and $$SAVEHIST are set appro-
priately, of course). The values of $$HISTFILE, $$HISTSIZE, and
$$SAVEHIST are restored to the values they had when `fc -p' was
called. Note that this restoration can conflict with making
these variables "local", so your best bet is to avoid local dec-
larations for these variables in functions that use `fc -p'.
The one other guaranteed-safe combination is declaring these
variables to be local at the top of your function and using the
automatic option (-a) with `fc -p'. Finally, note that it is
legal to manually pop a push marked for automatic popping if you
need to do so before the function exits.
`fc -R' reads the history from the given file, `fc -W' writes
the history out to the given file, and `fc -A' appends the his-
tory out to the given file. If no filename is specified, the
$$HISTFILE is assumed. If the -I option is added to -R, only
those events that are not already contained within the internal
history list are added. If the -I option is added to -A or -W,
only those events that are new since last incremental
append/write to the history file are appended/written. In any
case, the created file will have no more than $$SAVEHIST entries.
fg [ job ... ]
job ...
Bring each specified job in turn to the foreground. If no job
is specified, resume the current job.
float [ {]-}EFHghlprtux ] [ -LRZ [ n ] [ name[==value] ... ]
Equivalent to typeset -E, except that options irrelevant to
floating point numbers are not permitted.
functions [ {]-}UXkmtuz ] [ name ... ]
Equivalent to typeset -f.
getcap See the section `The zsh/cap Module' in zshmodules(1).
getln [ -AclneE ] name ...
Read the top value from the buffer stack and put it in the shell
parameter name. Equivalent to read -zr.
getopts optstring name [ arg ... ]
Checks the args for legal options. If the args are omitted, use
the positional parameters. A valid option argument begins with
a `]' or a `-'. An argument not beginning with a `]' or a `-',
or the argument `--', ends the options. Note that a single `-'
is not considered a valid option argument. optstring contains
the letters that getopts recognizes. If a letter is followed by
a `::', that option is expected to have an argument. The options
can be separated from the argument by blanks.
Each time it is invoked, getopts places the option letter it
finds in the shell parameter name, prepended with a `]' when arg
begins with a `]'. The index of the next arg is stored in
OPTIND. The option argument, if any, is stored in OPTARG.
The first option to be examined may be changed by explicitly
assigning to OPTIND. OPTIND has an initial value of 1, and is
normally reset to 1 upon exit from a shell function. OPTARG is
not reset and retains its value from the most recent call to
getopts. If either of OPTIND or OPTARG is explicitly unset, it
remains unset, and the index or option argument is not stored.
The option itself is still stored in name in this case.
A leading `::' in optstring causes getopts to store the letter of
any invalid option in OPTARG, and to set name to `??' for an
unknown option and to `::' when a required option is missing.
Otherwise, getopts sets name to `??' and prints an error message
when an option is invalid. The exit status is nonzero when
there are no more options.
hash [ -Ldfmrv ] [ name[==value] ] ...
hash can be used to directly modify the contents of the command
hash table, and the named directory hash table. Normally one
would modify these tables by modifying one's PATH (for the com-
mand hash table) or by creating appropriate shell parameters
(for the named directory hash table). The choice of hash table
to work on is determined by the -d option; without the option
the command hash table is used, and with the option the named
directory hash table is used.
Given no arguments, and neither the -r or -f options, the
selected hash table will be listed in full.
The -r option causes the selected hash table to be emptied. It
will be subsequently rebuilt in the normal fashion. The -f
option causes the selected hash table to be fully rebuilt imme-
diately. For the command hash table this hashes all the abso-
lute directories in the PATH, and for the named directory hash
table this adds all users' home directories. These two options
cannot be used with any arguments.
The -m option causes the arguments to be taken as patterns
(which should be quoted) and the elements of the hash table
matching those patterns are printed. This is the only way to
display a limited selection of hash table elements.
For each name with a corresponding value, put `name' in the
selected hash table, associating it with the pathname `value'.
In the command hash table, this means that whenever `name' is
used as a command argument, the shell will try to execute the
file given by `value'. In the named directory hash table, this
means that `value' may be referred to as `~~name'.
For each name with no corresponding value, attempt to add name
to the hash table, checking what the appropriate value is in the
normal manner for that hash table. If an appropriate value
can't be found, then the hash table will be unchanged.
The -v option causes hash table entries to be listed as they are
added by explicit specification. If has no effect if used with
-f.
If the -L flag is present, then each hash table entry is printed
in the form of a call to hash.
history
Same as fc -l.
integer [ {]-}Hghilprtux ] [ -LRZ [ n ] [ name[==value] ... ]
Equivalent to typeset -i, except that options irrelevant to
integers are not permitted.
jobs [ -dlprs ] [ job ... ]
jobs -Z string
Lists information about each given job, or all jobs if job is
omitted. The -l flag lists process IDs, and the -p flag lists
process groups. If the -r flag is specified only running jobs
will be listed and if the -s flag is given only stopped jobs are
shown. If the -d flag is given, the directory from which the
job was started (which may not be the current directory of the
job) will also be shown.
The -Z option replaces the shell's argument and environment
space with the given string, truncated if necessary to fit.
This will normally be visible in ps (ps(1)) listings. This fea-
ture is typically used by daemons, to indicate their state.
kill [ -s signalname -n signalnumber -sig ] job ...
kill -l [ sig ... ]
Sends either SIGTERM or the specified signal to the given jobs
or processes. Signals are given by number or by names, with or
without the `SIG' prefix. If the signal being sent is not
`KIL' or `CONT', then the job will be sent a `CONT' signal if
it is stopped. The argument job can be the process ID of a job
not in the job list. In the second form, kill -l, if sig is not
specified the signal names are listed. Otherwise, for each sig
that is a name, the corresponding signal number is listed. For
each sig that is a signal number or a number representing the
exit status of a process which was terminated or stopped by a
signal the name of the signal is printed.
On some systems, alternative signal names are allowed for a few
signals. Typical examples are SIGCHLD and SIGCLD or SIGPOL and
SIGIO, assuming they correspond to the same signal number. kill
-l will only list the preferred form, however kill -l alt will
show if the alternative form corresponds to a signal number.
For example, under Linux kill -l IO and kill -l POL both output
29, hence kill -IO and kill -POL have the same effect.
let arg ...
Evaluate each arg as an arithmetic expression. See the section
`Arithmetic Evaluation' for a description of arithmetic expres-
sions. The exit status is 0 if the value of the last expression
is nonzero, and 1 otherwise.
limit [ -hs ] [ resource [ limit ] ] ...
Set or display resource limits. Unless the -s flag is given,
the limit applies only the children of the shell. If -s is
given without other arguments, the resource limits of the cur-
rent shell is set to the previously set resource limits of the
children.
If limit is not specified, print the current limit placed on
resource, otherwise set the limit to the specified value. If
the -h flag is given, use hard limits instead of soft limits.
If no resource is given, print all limits.
When looping over multiple resources, the shell will abort imme-
diately if it detects a badly formed argument. However, if it
fails to set a limit for some other reason it will continue try-
ing to set the remaining limits.
resource can be one of:
addressspace
Maximum amount of address space used.
aiomemorylocked
Maximum amount of memory locked in RAM for AIO opera-
tions.
aiooperations
Maximum number of AIO operations.
cachedthreads
Maximum number of cached threads.
coredumpsize
Maximum size of a core dump.
cputime
Maximum CPU seconds per process.
datasize
Maximum data size (including stack) for each process.
descriptors
Maximum value for a file descriptor.
filesize
Largest single file allowed.
maxproc
Maximum number of processes.
maxpthreads
Maximum number of threads per process.
memorylocked
Maximum amount of memory locked in RAM.
memoryuse
Maximum resident set size.
resident
Maximum resident set size.
sockbufsize
Maximum size of all socket buffers.
stacksize
Maximum stack size for each process.
vmemorysize
Maximum amount of virtual memory.
Which of these resource limits are available depends on the sys-
tem. resource can be abbreviated to any unambiguous prefix. It
can also be an integer, which corresponds to the integer defined
for the resource by the operating system.
If argument corresponds to a number which is out of the range of
the resources configured into the shell, the shell will try to
read or write the limit anyway, and will report an error if this
fails. As the shell does not store such resources internally,
an attempt to set the limit will fail unless the -s option is
present.
limit is a number, with an optional scaling factor, as follows:
nh hours
nk kilobytes (default)
nm megabytes or minutes
[mm::]ss
minutes and seconds
local [ {]-}AEFHUahlprtux ] [ -LRZi [ n ] [ name[==value] ] ...
Same as typeset, except that the options -g, and -f are not per-
mitted. In this case the -x option does not force the use of
-g, i.e. exported variables will be local to functions.
log List all users currently logged in who are affected by the cur-
rent setting of the watch parameter.
logout [ n ]
Same as exit, except that it only works in a login shell.
noglob simple command
See the section `Precommand Modifiers'.
popd [ {]-}n ]
Remove an entry from the directory stack, and perform a cd to
the new top directory. With no argument, the current top entry
is removed. An argument of the form `]n' identifies a stack
entry by counting from the left of the list shown by the dirs
command, starting with zero. An argument of the form -n counts
from the right. If the PUSHDMINUS option is set, the meanings
of `]' and `-' in this context are swapped.
print [ -abcDilmnNoOpPrsz ] [ -u n ] [ -f format ] [ -C cols ]
[ -R [ -en ] [ arg ... ]
With the `-f' option the arguments are printed as described by
printf. With no flags or with the flag `-', the arguments are
printed on the standard output as described by echo, with the
following differences: the escape sequence `\\-x' metafies the
character x (sets the highest bit), `\\C-x' produces a control
character (`\\C-@@' and `\\C-??' give the characters NUL and
delete), and `\\E' is a synonym for `\\e'. Finally, if not in an
escape sequence, `\\' escapes the following character and is not
printed.
-a Print arguments with the column incrementing first. Only
useful with the -c and -C options.
-b Recognize all the escape sequences defined for the bind-
key command, see zshzle(1).
-c Print the arguments in columns. Unless -a is also given,
arguments are printed with the row incrementing first.
-C cols
Print the arguments in cols columns. Unless -a is also
given, arguments are printed with the row incrementing
first.
-D Treat the arguments as directory names, replacing pre-
fixes with ~~ expressions, as appropriate.
-i If given together with -o or -O, sorting is performed
case-independently.
-l Print the arguments separated by newlines instead of spa-
ces.
-m Take the first argument as a pattern (should be quoted),
and remove it from the argument list together with subse-
quent arguments that do not match this pattern.
-n Do not add a newline to the output.
-N Print the arguments separated and terminated by nulls.
-o Print the arguments sorted in ascending order.
-O Print the arguments sorted in descending order.
-p Print the arguments to the input of the coprocess.
-P Perform prompt expansion (see zshmisc(1)).
-r Ignore the escape conventions of echo.
-R Emulate the BSD echo command, which does not process
escape sequences unless the -e flag is given. The -n
flag suppresses the trailing newline. Only the -e and -n
flags are recognized after -R; all other arguments and
options are printed.
-s Place the results in the history list instead of on the
standard output.
-u n Print the arguments to file descriptor n.
-z Push the arguments onto the editing buffer stack, sepa-
rated by spaces.
If any of `-m', `-o' or `-O' are used in combination with `-f'
and there are no arguments (after the removal process in the
case of `-m') then nothing is printed.
printf format [ arg ... ]
Print the arguments according to the format specification. For-
matting rules are the same as used in C. The same escape
sequences as for echo are recognised in the format. All C con-
version specifications ending in one of csdiouxXeEfgGn are han-
dled. In addition to this, `%%b' can be used instead of `%%s' to
cause escape sequences in the argument to be recognised and `%%q'
can be used to quote the argument in such a way that allows it
to be reused as shell input. With the numeric format specifiers,
if the corresponding argument starts with a quote character, the
numeric value of the following character is used as the number
to print otherwise the argument is evaluated as an arithmetic
expression. See the section `Arithmetic Evaluation' for a
description of arithmetic expressions. With `%%n', the corre-
sponding argument is taken as an identifier which is created as
an integer parameter.
Normally, conversion specifications are applied to each argument
in order but they can explicitly specify the nth argument is to
be used by replacing `%%' by `%%n$$' and `**' by `**n$$'. It is rec-
ommended that you do not mix references of this explicit style
with the normal style and the handling of such mixed styles may
be subject to future change.
If arguments remain unused after formatting, the format string
is reused until all arguments have been consumed. With the print
builtin, this can be suppressed by using the -r option. If more
arguments are required by the format than have been specified,
the behaviour is as if zero or an empty string had been speci-
fied as the argument.
pushd [ -sLP ] [ arg ]
pushd [ -sLP ] old new
pushd [ -sLP ] {]-}n
Change the current directory, and push the old current directory
onto the directory stack. In the first form, change the current
directory to arg. If arg is not specified, change to the second
directory on the stack (that is, exchange the top two entries),
or change to $$HOME if the PUSHDTOHOME option is set or if
there is only one entry on the stack. Otherwise, arg is inter-
preted as it would be by cd. The meaning of old and new in the
second form is also the same as for cd.
The third form of pushd changes directory by rotating the direc-
tory list. An argument of the form `]n' identifies a stack
entry by counting from the left of the list shown by the dirs
command, starting with zero. An argument of the form `-n'
counts from the right. If the PUSHDMINUS option is set, the
meanings of `]' and `-' in this context are swapped.
If the option PUSHDSILENT is not set, the directory stack will
be printed after a pushd is performed.
The options -s, -L and -P have the same meanings as for the cd
builtin.
pushln [ arg ... ]
Equivalent to print -nz.
pwd [ -rLP ]
Print the absolute pathname of the current working directory.
If the -r or the -P flag is specified, or the CHASELINKS option
is set and the -L flag is not given, the printed path will not
contain symbolic links.
r Same as fc -e -.
read [ -rszpqAclneE ] [ -t [ num ] ] [ -k [ num ] ] [ -d delim ]
[ -u n ] [ name[??prompt] ] [ name ... ]
Read one line and break it into fields using the characters in
$$IFS as separators, except as noted below. The first field is
assigned to the first name, the second field to the second name,
etc., with leftover fields assigned to the last name. If name
is omitted then REPLY is used for scalars and reply for arrays.
-r Raw mode: a `\\' at the end of a line does not signify
line continuation and backslashes in the line don't quote
the following character and are not removed.
-s Don't echo back characters if reading from the terminal.
Currently does not work with the -q option.
-q Read only one character from the terminal and set name to
`y' if this character was `y' or `Y' and to `n' other-
wise. With this flag set the return value is zero only
if the character was `y' or `Y'. Note that this always
reads from the terminal, even if used with the -p or -u
or -z flags or with redirected input. This option may
also be used within zle widgets.
-k [ num ]
Read only one (or num) characters. All are assigned to
the first name, without word splitting. This flag is
ignored when -q is present. Input is read from the ter-
minal unless one of -u or -p is present. This option may
also be used within zle widgets.
-z Read one entry from the editor buffer stack and assign it
to the first name, without word splitting. Text is
pushed onto the stack with `print -z' or with push-line
from the line editor (see zshzle(1)). This flag is
ignored when the -k or -q flags are present.
-e
-E The input read is printed (echoed) to the standard out-
put. If the -e flag is used, no input is assigned to the
parameters.
-A The first name is taken as the name of an array and all
words are assigned to it.
-c
-l These flags are allowed only if called inside a function
used for completion (specified with the -K flag to com-
pctl). If the -c flag is given, the words of the current
command are read. If the -l flag is given, the whole line
is assigned as a scalar. If both flags are present, -l
is used and -c is ignored.
-n Together with -c, the number of the word the cursor is on
is read. With -l, the index of the character the cursor
is on is read. Note that the command name is word number
1, not word 0, and that when the cursor is at the end of
the line, its character index is the length of the line
plus one.
-u n Input is read from file descriptor n.
-p Input is read from the coprocess.
-d delim
Input is terminated by the first character of delim
instead of by newline.
-t [ num ]
Test if input is available before attempting to read. If
num is present, it must begin with a digit and will be
evaluated to give a number of seconds, which may be a
floating point number; in this case the read times out if
input is not available within this time. If num is not
present, it is taken to be zero, so that read returns
immediately if no input is available. If no input is
available, return status 1 and do not set any variables.
This option is not available when reading from the editor
buffer with -z, when called from within completion with
-c or -l, with -q which clears the input queue before
reading, or within zle where other mechanisms should be
used to test for input.
Note that read does not attempt to alter the input pro-
cessing mode. The default mode is canonical input, in
which an entire line is read at a time, so usually `read
-t' will not read anything until an entire line has been
typed. However, when reading from the terminal with -k
input is processed one key at a time; in this case, only
availability of the first character is tested, so that
e.g. `read -t -k 2' can still block on the second charac-
ter. Use two instances of `read -t -k' if this is not
what is wanted. If the first argument contains a `??',
the remainder of this word is used as a prompt on stan-
dard error when the shell is interactive.
The value (exit status) of read is 1 when an end-of-file is
encountered, or when -c or -l is present and the command is not
called from a compctl function, or as described for -q. Other-
wise the value is 0.
The behavior of some combinations of the -k, -p, -q, -u and -z
flags is undefined. Presently -q cancels all the others, -p
cancels -u, -k cancels -z, and otherwise -z cancels both -p and
-u.
The -c or -l flags cancel any and all of -kpquz.
readonly
Same as typeset -r.
rehash Same as hash -r.
return [ n ]
Causes a shell function or . script to return to the invoking
script with the return status specified by n. If n is omitted,
the return status is that of the last command executed.
If return was executed from a trap in a TRAPNAL function, the
effect is different for zero and non-zero return status. With
zero status (or after an implicit return at the end of the
trap), the shell will return to whatever it was previously pro-
cessing; with a non-zero status, the shell will behave as inter-
rupted except that the return status of the trap is retained.
Note that the numeric value of the signal which caused the trap
is passed as the first argument, so the statement `return
$$((128]$$1))' will return the same status as if the signal had
not been trapped.
sched See the section `The zsh/sched Module' in zshmodules(1).
set [ {]-}options {]-}o [ optionname ] ] ... [ {]-}A [ name ] ] [
arg ... ]
Set the options for the shell and/or set the positional parame-
ters, or declare and set an array. If the -s option is given,
it causes the specified arguments to be sorted before assigning
them to the positional parameters (or to the array name if -A is
used). With ]s sort arguments in descending order. For the
meaning of the other flags, see zshoptions(1). Flags may be
specified by name using the -o option. If no option name is sup-
plied with -o, the current option states are printed. With ]o
they are printed in a form that can be used as input to the
shell.
If the -A flag is specified, name is set to an array containing
the given args; if no name is specified, all arrays are printed
together with their values.
If ]A is used and name is an array, the given arguments will
replace the initial elements of that array; if no name is speci-
fied, all arrays are printed without their values.
The behaviour of arguments after -A name or ]A name depends on
whether the option KSHARAYS is set. If it is not set, all
arguments following name are treated as values for the array,
regardless of their form. If the option is set, normal option
processing continues at that point; only regular arguments are
treated as values for the array. This means that
set -A array -x -- foo
sets array to `-x -- foo' if KSHARAYS is not set, but sets the
array to foo and turns on the option `-x' if it is set.
If the -A flag is not present, but there are arguments beyond
the options, the positional parameters are set. If the option
list (if any) is terminated by `--', and there are no further
arguments, the positional parameters will be unset.
If no arguments and no `--' are given, then the names and values
of all parameters are printed on the standard output. If the
only argument is `]', the names of all parameters are printed.
setcap See the section `The zsh/cap Module' in zshmodules(1).
setopt [ {]-}options {]-}o optionname ] [ name ... ]
Set the options for the shell. All options specified either
with flags or by name are set. If no arguments are supplied,
the names of all options currently set are printed. If the -m
flag is given the arguments are taken as patterns (which should
be quoted to protect them from filename expansion), and all
options with names matching these patterns are set.
shift [ n ] [ name ... ]
The positional parameters $${{n]1}} ... are renamed to $$1 ...,
where n is an arithmetic expression that defaults to 1. If any
names are given then the arrays with these names are shifted
instead of the positional parameters.
source file [ arg ... ]
Same as ., except that the current directory is always searched
and is always searched first, before directories in $$path.
stat See the section `The zsh/stat Module' in zshmodules(1).
suspend [ -f ]
Suspend the execution of the shell (send it a SIGTSTP) until it
receives a SIGCONT. Unless the -f option is given, this will
refuse to suspend a login shell.
test [ arg ... ]
[ [ arg ... ] ]
Like the system version of test. Added for compatibility; use
conditional expressions instead (see the section `Conditional
Expressions'). The main differences between the conditional
expression syntax and the test and [ builtins are: these com-
mands are not handled syntactically, so for example an empty
variable expansion may cause an argument to be omitted; syntax
errors cause status 2 to be returned instead of a shell error;
and arithmetic operators expect integer arguments rather than
arithemetic expressions.
times Print the accumulated user and system times for the shell and
for processes run from the shell.
trap [ arg [ sig ... ] ]
arg is a series of commands (usually quoted to protect it from
immediate evaluation by the shell) to be read and executed when
the shell receives sig. Each sig can be given as a number or as
the name of a signal. If arg is `-', then all traps sig are
reset to their default values. If arg is the empty string, then
this signal is ignored by the shell and by the commands it
invokes.
If sig is ZER then arg will be executed after each command with
a nonzero exit status. If sig is DEBUG then arg will be exe-
cuted after each command. If sig is 00 or EXIT and the trap
statement is executed inside the body of a function, then the
command arg is executed after the function completes. If sig is
00 or EXIT and the trap statement is not executed inside the body
of a function, then the command arg is executed when the shell
terminates.
ZER, DEBUG and EXIT traps are not executed inside other traps.
The trap command with no arguments prints a list of commands
associated with each signal.
Note that traps defined with the trap builtin are slightly dif-
ferent from those defined as `TRAPNAL () { ... }', as the latter
have their own function environment (line numbers, local vari-
ables, etc.) while the former use the environment of the command
in which they were called. For example,
trap ''print $$LINENO'' DEBUG
will print the line number of a command executed after it has
run, while
TRAPDEBUG() {{ print $$LINENO;; }}
will always print the number zero.
Alternative signal names are allowed as described under kill
above. Defining a trap under either name causes any trap under
an alternative name to be removed. However, it is recommended
that for consistency users stick exclusively to one name or
another.
true [ arg ... ]
Do nothing and return an exit code of 0.
ttyctl -fu
The -f option freezes the tty, and -u unfreezes it. When the
tty is frozen, no changes made to the tty settings by external
programs will be honored by the shell, except for changes in the
size of the screen; the shell will simply reset the settings to
their previous values as soon as each command exits or is sus-
pended. Thus, stty and similar programs have no effect when the
tty is frozen. Without options it reports whether the terminal
is frozen or not.
type [ -wfpams ] name ...
Equivalent to whence -v.
typeset [ {]-}AEFHUafghklprtuxmz ] [ -LRZi [ n ] [ name[==value] ... ]
typeset -T [ {]-}}Urux ] [ -LRZ [ n ] SCALAR[==value] array [ sep ]
Set or display attributes and values for shell parameters.
A parameter is created for each name that does not already refer
to one. When inside a function, a new parameter is created for
every name (even those that already exist), and is unset again
when the function completes. See `Local Parameters' in zsh-
param(1). The same rules apply to special shell parameters,
which retain their special attributes when made local.
For each name==value assignment, the parameter name is set to
value. Note that arrays currently cannot be assigned in typeset
expressions, only scalars and integers.
If the shell option TYPESETSILENT is not set, for each remain-
ing name that refers to a parameter that is set, the name and
value of the parameter are printed in the form of an assignment.
Nothing is printed for newly-created parameters, or when any
attribute flags listed below are given along with the name.
Using `]' instead of minus to introduce an attribute turns it
off.
If the -p option is given, parameters and values are printed in
the form of a typeset comand and an assignment (which will be
printed separately for arrays and associative arrays), regard-
less of other flags and options. Note that the -h flag on
parameters is respected; no value will be shown for these param-
eters.
If the -T option is given, two or three arguments must be
present (an exception is that zero arguments are allowed to show
the list of parameters created in this fashion). The first two
are the name of a scalar and an array parameter (in that order)
that will be tied together in the manner of $$PATH and $$path.
The optional third argument is a single-character separator
which will be used to join the elements of the array to form the
scalar; if absent, a colon is used, as with $$PATH. Only the
first character of the separator is significant; any remaining
characters are ignored. Only the scalar parameter may be
assigned an initial value. Both the scalar and the array may
otherwise be manipulated as normal. If one is unset, the other
will automatically be unset too. There is no way of untying the
variables without unsetting them, or converting the type of one
of them with another typeset command; ]T does not work, assign-
ing an array to SCALAR is an error, and assigning a scalar to
array sets it to be a single-element array. Note that both
`typeset -xT ...' and `export -T ...' work, but only the scalar
will be marked for export. Setting the value using the scalar
version causes a split on all separators (which cannot be
quoted).
The -g (global) flag is treated specially: it means that any
resulting parameter will not be restricted to local scope. Note
that this does not necessarily mean that the parameter will be
global, as the flag will apply to any existing parameter (even
if unset) from an enclosing function. This flag does not affect
the parameter after creation, hence it has no effect when list-
ing existing parameters, nor does the flag ]g have any effect
except in combination with -m (see below).
If no name is present, the names and values of all parameters
are printed. In this case the attribute flags restrict the dis-
play to only those parameters that have the specified
attributes, and using `]' rather than `-' to introduce the flag
suppresses printing of the values of parameters when there is no
parameter name. Also, if the last option is the word `]', then
names are printed but values are not.
If the -m flag is given the name arguments are taken as patterns
(which should be quoted). With no attribute flags, all parame-
ters (or functions with the -f flag) with matching names are
printed (the shell option TYPESETSILENT is not used in this
case). Note that -m is ignored if no patterns are given. If
the ]g flag is combined with -m, a new local parameter is cre-
ated for every matching parameter that is not already local.
Otherwise -m applies all other flags or assignments to the
existing parameters. Except when assignments are made with
name==value, using ]m forces the matching parameters to be
printed, even inside a function.
If no attribute flags are given and either no -m flag is present
or the ]m form was used, each parameter name printed is preceded
by a list of the attributes of that parameter (array, associa-
tion, exported, integer, readonly). If ]m is used with
attribute flags, and all those flags are introduced with ], the
matching parameter names are printed but their values are not.
The following attribute flags may be specified:
-A The names refer to associative array parameters; see
`Array Parameters' in zshparam(1).
-L Left justify and remove leading blanks from value. If n
is nonzero, it defines the width of the field. If n is
zero, the width is determined by the width of the value
of the first assignment. In the case of numeric parame-
ters, the length of the complete value assigned to the
parameter is used to determine the width, not the value
that would be output. When the parameter is expanded, it
is filled on the right with blanks or truncated if neces-
sary to fit the field. Note truncation can lead to unex-
pected results with numeric parameters. Leading zeros
are removed if the -Z flag is also set.
-R Similar to -L, except that right justification is used;
when the parameter is expanded, the field is left filled
with blanks or truncated from the end. May not be com-
bined with the -Z flag.
-U For arrays (but not for associative arrays), keep only
the first occurrence of each duplicated value. This may
also be set for colon-separated special parameters like
PATH or FIGNORE, etc. This flag has a different meaning
when used with -f; see below.
-Z Specially handled if set along with the -L flag. Other-
wise, similar to -R, except that leading zeros are used
for padding instead of blanks if the first non-blank
character is a digit. Numeric parameters are specially
handled: they are always eligible for padding with
zeroes, and the zeroes are inserted at an appropriate
place in the output.
-a The names refer to array parameters. An array parameter
may be created this way, but it may not be assigned to in
the typeset statement. When displaying, both normal and
associative arrays are shown.
-f The names refer to functions rather than parameters. No
assignments can be made, and the only other valid flags
are -t, -k, -u, -U and -z. The flag -t turns on execu-
tion tracing for this function. The -u and -U flags
cause the function to be marked for autoloading; -U also
causes alias expansion to be suppressed when the function
is loaded. The fpath parameter will be searched to find
the function definition when the function is first refer-
enced; see the section `Functions'. The -k and -z flags
make the function be loaded using ksh-style or zsh-style
autoloading respectively. If neither is given, the set-
ting of the KSHAUTOLOAD option determines how the func-
tion is loaded.
-h Hide: only useful for special parameters (those marked
`' in the table in zshparams(1)), and for local param-
eters with the same name as a special parameter, though
harmless for others. A special parameter with this
attribute will not retain its special effect when made
local. Thus after `typeset -h PATH', a function contain-
ing `typeset PATH' will create an ordinary local parame-
ter without the usual behaviour of PATH. Alternatively,
the local parameter may itself be given this attribute;
hence inside a function `typeset -h PATH' creates an
ordinary local parameter and the special PATH parameter
is not altered in any way. It is also possible to create
a local parameter using `typeset ]h special', where the
local copy of special will retain its special properties
regardless of having the -h attribute. Global special
parameters loaded from shell modules (currently those in
zsh/mapfile and zsh/parameter) are automatically given
the -h attribute to avoid name clashes.
-H Hide value: specifies that typeset will not display the
value of the parameter when listing parameters; the dis-
play for such parameters is always as if the `]' flag had
been given. Use of the parameter is in other respects
normal, and the option does not apply if the parameter is
specified by name, or by pattern with the -m option.
This is on by default for the parameters in the
zsh/parameter and zsh/mapfile modules. Note, however,
that unlike the -h flag this is also useful for non-spe-
cial parameters.
-i Use an internal integer representation. If n is nonzero
it defines the output arithmetic base, otherwise it is
determined by the first assignment.
-E Use an internal double-precision floating point represen-
tation. On output the variable will be converted to sci-
entific notation. If n is nonzero it defines the number
of significant figures to display; the default is ten.
-F Use an internal double-precision floating point represen-
tation. On output the variable will be converted to
fixed-point decimal notation. If n is nonzero it defines
the number of digits to display after the decimal point;
the default is ten.
-l Convert the result to lower case whenever the parameter
is expanded. The value is not converted when assigned.
-r The given names are marked readonly. Note that if name
is a special parameter, the readonly attribute can be
turned on, but cannot then be turned off.
-t Tags the named parameters. Tags have no special meaning
to the shell. This flag has a different meaning when
used with -f; see above.
-u Convert the result to upper case whenever the parameter
is expanded. The value is not converted when assigned.
This flag has a different meaning when used with -f; see
above.
-x Mark for automatic export to the environment of subse-
quently executed commands. If the option GLOBALEXPORT
is set, this implies the option -g, unless ]g is also
explicitly given; in other words the parameter is not
made local to the enclosing function. This is for com-
patibility with previous versions of zsh.
ulimit [ [ -SHacdflmnpstv -N resource [ limit ] ... ]
Set or display resource limits of the shell and the processes
started by the shell. The value of limit can be a number in the
unit specified below or the value `unlimited'. By default, only
soft limits are manipulated. If the -H flag is given use hard
limits instead of soft limits. If the -S flag is given together
with the -H flag set both hard and soft limits. If no options
are used, the file size limit (-f) is assumed. If limit is
omitted the current value of the specified resources are
printed. When more than one resource values are printed the
limit name and unit is printed before each value.
When looping over multiple resources, the shell will abort imme-
diately if it detects a badly formed argument. However, if it
fails to set a limit for some other reson it will continue try-
ing to set the remaining limits.
-a Lists all of the current resource limits.
-c 512-byte blocks on the size of core dumps.
-d K-bytes on the size of the data segment.
-f 512-byte blocks on the size of files written.
-l K-bytes on the size of locked-in memory.
-m K-bytes on the size of physical memory.
-n open file descriptors.
-s K-bytes on the size of the stack.
-t CPU seconds to be used.
-u processes available to the user.
-v K-bytes on the size of virtual memory. On some systems
this refers to the limit called `address space'.
A resource may also be specified by integer in the form `-N
resource', where resource corresponds to the integer defined for
the resource by the operating system. This may be used to set
the limits for resources known to the shell which do not corre-
spond to option letters. Such limits will be shown by number in
the output of `ulimit -a'.
The number may alternatively be out of the range of limits com-
piled into the shell. The shell will try to read or write the
limit anyway, and will report an error if this fails.
umask [ -S ] [ mask ]
The umask is set to mask. mask can be either an octal number or
a symbolic value as described in chmod(1). If mask is omitted,
the current value is printed. The -S option causes the mask to
be printed as a symbolic value. Otherwise, the mask is printed
as an octal number. Note that in the symbolic form the permis-
sions you specify are those which are to be allowed (not denied)
to the users specified.
unalias
Same as unhash -a.
unfunction
Same as unhash -f.
unhash [ -adfms ] name ...
Remove the element named name from an internal hash table. The
default is remove elements from the command hash table. The -a
option causes unhash to remove regular or global aliases. The
-s option causes unhash to remove suffix aliases. The -f option
causes unhash to remove shell functions. The -d options causes
unhash to remove named directories. If the -m flag is given the
arguments are taken as patterns (should be quoted) and all ele-
ments of the corresponding hash table with matching names will
be removed.
unlimit [ -hs ] resource ...
The resource limit for each resource is set to the hard limit.
If the -h flag is given and the shell has appropriate privi-
leges, the hard resource limit for each resource is removed.
The resources of the shell process are only changed if the -s
flag is given.
unset [ -fmv ] name ...
Each named parameter is unset. Local parameters remain local
even if unset; they appear unset within scope, but the previous
value will still reappear when the scope ends.
Individual elements of associative array parameters may be unset
by using subscript syntax on name, which should be quoted (or
the entire command prefixed with noglob) to protect the sub-
script from filename generation.
If the -m flag is specified the arguments are taken as patterns
(should be quoted) and all parameters with matching names are
unset. Note that this cannot be used when unsetting associative
array elements, as the subscript will be treated as part of the
pattern.
The -v flag specifies that name refers to parameters. This is
the default behaviour.
unset -f is equivalent to unfunction.
unsetopt [ {]-}options {]-}o optionname ] [ name ... ]
Unset the options for the shell. All options specified either
with flags or by name are unset. If no arguments are supplied,
the names of all options currently unset are printed. If the -m
flag is given the arguments are taken as patterns (which should
be quoted to preserve them from being interpreted as glob pat-
terns), and all options with names matching these patterns are
unset.
vared See the section `Zle Builtins' in zshzle(1).
wait [ job ... ]
Wait for the specified jobs or processes. If job is not given
then all currently active child processes are waited for. Each
job can be either a job specification or the process ID of a job
in the job table. The exit status from this command is that of
the job waited for.
whence [ -vcwfpams ] name ...
For each name, indicate how it would be interpreted if used as a
command name.
-v Produce a more verbose report.
-c Print the results in a csh-like format. This takes
precedence over -v.
-w For each name, print `name:: word' where word is one of
alias, builtin, command, function, hashed, reserved or
none, according as name corresponds to an alias, a
built-in command, an external command, a shell function,
a command defined with the hash builtin, a reserved word,
or is not recognised. This takes precedence over -v and
-c.
-f Causes the contents of a shell function to be displayed,
which would otherwise not happen unless the -c flag were
used.
-p Do a path search for name even if it is an alias,
reserved word, shell function or builtin.
-a Do a search for all occurrences of name throughout the
command path. Normally only the first occurrence is
printed.
-m The arguments are taken as patterns (should be quoted),
and the information is displayed for each command match-
ing one of these patterns.
-s If a pathname contains symlinks, print the symlink-free
pathname as well.
where [ -wpms ] name ...
Equivalent to whence -ca.
which [ -wpams ] name ...
Equivalent to whence -c.
zcompile [ -U ] [ -z -k ] [ -R -M ] file [ name ... ]
zcompile -ca [ -m ] [ -R -M ] file [ name ... ]
zcompile -t file [ name ... ]
This builtin command can be used to compile functions or
scripts, storing the compiled form in a file, and to examine
files containing the compiled form. This allows faster
autoloading of functions and execution of scripts by avoiding
parsing of the text when the files are read.
The first form (without the -c, -a or -t options) creates a com-
piled file. If only the file argument is given, the output file
has the name `file.zwc' and will be placed in the same directory
as the file. The shell will load the compiled file instead of
the normal function file when the function is autoloaded; see
the section `Autoloading Functions' in zshfunc(1) for a descrip-
tion of how autoloaded functions are searched. The extension
.zwc stands for `zsh word code'.
If there is at least one name argument, all the named files are
compiled into the output file given as the first argument. If
file does not end in .zwc, this extension is automatically
appended. Files containing multiple compiled functions are
called `digest' files, and are intended to be used as elements
of the FPATH/fpath special array.
The second form, with the -c or -a options, writes the compiled
definitions for all the named functions into file. For -c, the
names must be functions currently defined in the shell, not
those marked for autoloading. Undefined functions that are
marked for autoloading may be written by using the -a option, in
which case the fpath is searched and the contents of the defini-
tion files for those functions, if found, are compiled into
file. If both -c and -a are given, names of both defined func-
tions and functions marked for autoloading may be given. In
either case, the functions in files written with the -c or -a
option will be autoloaded as if the KSHAUTOLOAD option were
unset.
The reason for handling loaded and not-yet-loaded functions with
different options is that some definition files for autoloading
define multiple functions, including the function with the same
name as the file, and, at the end, call that function. In such
cases the output of `zcompile -c' does not include the addi-
tional functions defined in the file, and any other initializa-
tion code in the file is lost. Using `zcompile -a' captures all
this extra information.
If the -m option is combined with -c or -a, the names are used
as patterns and all functions whose names match one of these
patterns will be written. If no name is given, the definitions
of all functions currently defined or marked as autoloaded will
be written.
The third form, with the -t option, examines an existing com-
piled file. Without further arguments, the names of the origi-
nal files compiled into it are listed. The first line of output
shows the version of the shell which compiled the file and how
the file will be used (i.e. by reading it directly or by mapping
it into memory). With arguments, nothing is output and the
return value is set to zero if definitions for all names were
found in the compiled file, and non-zero if the definition for
at least one name was not found.
Other options:
-U Aliases are not expanded when compiling the named files.
-R When the compiled file is read, its contents are copied
into the shell's memory, rather than memory-mapped (see
-M). This happens automatically on systems that do not
support memory mapping.
When compiling scripts instead of autoloadable functions,
it is often desirable to use this option; otherwise the
whole file, including the code to define functions which
have already been defined, will remain mapped, conse-
quently wasting memory.
-M The compiled file is mapped into the shell's memory when
read. This is done in such a way that multiple instances
of the shell running on the same host will share this
mapped file. If neither -R nor -M is given, the zcompile
builtin decides what to do based on the size of the com-
piled file.
-k
-z These options are used when the compiled file contains
functions which are to be autoloaded. If -z is given, the
function will be autoloaded as if the KSHAUTOLOAD option
is not set, even if it is set at the time the compiled
file is read, while if the -k is given, the function will
be loaded as if KSHAUTOLOAD is set. These options also
take precedence over any -k or -z options specified to
the autoload builtin. If neither of these options is
given, the function will be loaded as determined by the
setting of the KSHAUTOLOAD option at the time the com-
piled file is read.
These options may also appear as many times as necessary
between the listed names to specify the loading style of
all following functions, up to the next -k or -z.
The created file always contains two versions of the com-
piled format, one for big-endian machines and one for
small-endian machines. The upshot of this is that the
compiled file is machine independent and if it is read or
mapped, only one half of the file is actually used (and
mapped).
zformat
See the section `The zsh/zutil Module' in zshmodules(1).
zftp See the section `The zsh/zftp Module' in zshmodules(1).
zle See the section `Zle Builtins' in zshzle(1).
zmodload [ -dL ] [ ... ]
zmodload -e [ -A ] [ ... ]
zmodload [ -a [ -bcpf [ -I ] ] ] [ -iL ] ...
zmodload -u [ -abcdpf [ -I ] ] [ -iL ] ...
zmodload -A [ -L ] [ modalias[==module] ... ]
zmodload -R modalias ...
Performs operations relating to zsh's loadable modules. Loading
of modules while the shell is running (`dynamical loading') is
not available on all operating systems, or on all installations
on a particular operating system, although the zmodload command
itself is always available and can be used to manipulate modules
built into versions of the shell executable without dynamical
loading.
Without arguments the names of all currently loaded binary mod-
ules are printed. The -L option causes this list to be in the
form of a series of zmodload commands. Forms with arguments
are:
zmodload [ -i ] name ...
zmodload -u [ -i ] name ...
In the simplest case, zmodload loads a binary module.
The module must be in a file with a name consisting of
the specified name followed by a standard suffix, usually
`.so' (`.sl' on HPUX). If the module to be loaded is
already loaded and the -i option is given, the duplicate
module is ignored. Otherwise zmodload prints an error
message.
The named module is searched for in the same way a com-
mand is, using $$modulepath instead of $$path. However,
the path search is performed even when the module name
contains a `/', which it usually does. There is no way
to prevent the path search.
With -u, zmodload unloads modules. The same name must be
given that was given when the module was loaded, but it
is not necessary for the module to exist in the filesys-
tem. The -i option suppresses the error if the module is
already unloaded (or was never loaded).
Each module has a boot and a cleanup function. The mod-
ule will not be loaded if its boot function fails. Simi-
larly a module can only be unloaded if its cleanup func-
tion runs successfully.
zmodload -d [ -L ] [ name ]
zmodload -d name dep ...
zmodload -ud name [ dep ... ]
The -d option can be used to specify module dependencies.
The modules named in the second and subsequent arguments
will be loaded before the module named in the first argu-
ment.
With -d and one argument, all dependencies for that mod-
ule are listed. With -d and no arguments, all module
dependencies are listed. This listing is by default in a
Makefile-like format. The -L option changes this format
to a list of zmodload -d commands.
If -d and -u are both used, dependencies are removed. If
only one argument is given, all dependencies for that
module are removed.
zmodload -ab [ -L ]
zmodload -ab [ -i ] name [ builtin ... ]
zmodload -ub [ -i ] builtin ...
The -ab option defines autoloaded builtins. It defines
the specified builtins. When any of those builtins is
called, the module specified in the first argument is
loaded. If only the name is given, one builtin is
defined, with the same name as the module. -i suppresses
the error if the builtin is already defined or
autoloaded, regardless of which module it came from.
With -ab and no arguments, all autoloaded builtins are
listed, with the module name (if different) shown in
parentheses after the builtin name. The -L option
changes this format to a list of zmodload -a commands.
If -b is used together with the -u option, it removes
builtins previously defined with -ab. This is only pos-
sible if the builtin is not yet loaded. -i suppresses
the error if the builtin is already removed (or never
existed).
zmodload -ac [ -IL ]
zmodload -ac [ -iI ] name [ cond ... ]
zmodload -uc [ -iI ] cond ...
The -ac option is used to define autoloaded condition
codes. The cond strings give the names of the conditions
defined by the module. The optional -I option is used to
define infix condition names. Without this option prefix
condition names are defined.
If given no condition names, all defined names are listed
(as a series of zmodload commands if the -L option is
given).
The -uc option removes definitions for autoloaded condi-
tions.
zmodload -ap [ -L ]
zmodload -ap [ -i ] name [ parameter ... ]
zmodload -up [ -i ] parameter ...
The -p option is like the -b and -c options, but makes
zmodload work on autoloaded parameters instead.
zmodload -af [ -L ]
zmodload -af [ -i ] name [ function ... ]
zmodload -uf [ -i ] function ...
The -f option is like the -b, -p, and -c options, but
makes zmodload work on autoloaded math functions instead.
zmodload -a [ -L ]
zmodload -a [ -i ] name [ builtin ... ]
zmodload -ua [ -i ] builtin ...
Equivalent to -ab and -ub.
zmodload -e [ -A ] [ string ... ]
The -e option without arguments lists all loaded modules;
if the -A option is also given, module aliases corre-
sponding to loaded modules are also shown. With argu-
ments only the return status is set to zero if all
strings given as arguments are names of loaded modules
and to one if at least on string is not the name of a
loaded module. This can be used to test for the avail-
ability of things implemented by modules. In this case,
any aliases are automatically resolved and the -A flag is
not used.
zmodload -A [ -L ] [ modalias[==module] ... ]
For each argument, if both modalias and module are given,
define modalias to be an alias for the module module. If
the module modalias is ever subsequently requested,
either via a call to zmodload or implicitly, the shell
will attempt to load module instead. If module is not
given, show the definition of modalias. If no arguments
are given, list all defined module aliases. When list-
ing, if the -L flag was also given, list the definition
as a zmodload command to recreate the alias.
The existence of aliases for modules is completely inde-
pendent of whether the name resolved is actually loaded
as a module: while the alias exists, loading and unload-
ing the module under any alias has exactly the same
effect as using the resolved name, and does not affect
the connection between the alias and the resolved name
which can be removed either by zmodload -R or by redefin-
ing the alias. Chains of aliases (i.e. where the first
resolved name is itself an alias) are valid so long as
these are not circular. As the aliases take the same
format as module names, they may include path separators:
in this case, there is no requirement for any part of the
path named to exist as the alias will be resolved first.
For example, `any/old/alias' is always a valid alias.
Dependencies added to aliased modules are actually added
to the resolved module; these remain if the alias is
removed. It is valid to create an alias whose name is
one of the standard shell modules and which resolves to a
different module. However, if a module has dependencies,
it will not be possible to use the module name as an
alias as the module will already be marked as a loadable
module in its own right.
Apart from the above, aliases can be used in the zmodload
command anywhere module names are required. However,
aliases will not be shown in lists of loaded modules with
a bare `zmodload'.
zmodload -R modalias ...
For each modalias argument that was previously defined as
a module alias via zmodload -A, delete the alias. If any
was not defined, an error is caused and the remainder of
the line is ignored.
Note that zsh makes no distinction between modules that were
linked into the shell and modules that are loaded dynamically.
In both cases this builtin command has to be used to make avail-
able the builtins and other things defined by modules (unless
the module is autoloaded on these definitions). This is true
even for systems that don't support dynamic loading of modules.
zparseopts
See the section `The zsh/zutil Module' in zshmodules(1).
zprof See the section `The zsh/zprof Module' in zshmodules(1).
zpty See the section `The zsh/zpty Module' in zshmodules(1).
zregexparse
See the section `The zsh/zutil Module' in zshmodules(1).
zsocket
See the section `The zsh/net/socket Module' in zshmodules(1).
zstyle See the section `The zsh/zutil Module' in zshmodules(1).
ztcp See the section `The zsh/net/tcp Module' in zshmodules(1).
ZSHZLE(1) ZSHZLE(1)
NAME
zshzle - zsh command line editor
DESCRIPTION
If the ZLE option is set (which it is by default in interactive shells)
and the shell input is attached to the terminal, the user is able to
edit command lines.
There are two display modes. The first, multiline mode, is the
default. It only works if the TERM parameter is set to a valid termi-
nal type that can move the cursor up. The second, single line mode, is
used if TERM is invalid or incapable of moving the cursor up, or if the
SINGLELINEZLE option is set. This mode is similar to ksh, and uses
no termcap sequences. If TERM is "emacs", the ZLE option will be unset
by default.
The parameters BAUD, COLUMNS, and LINES are also used by the line edi-
tor. See Parameters Used By The Shell in zshparam(1).
KEYMAPS
A keymap in ZLE contains a set of bindings between key sequences and
ZLE commands. The empty key sequence cannot be bound.
There can be any number of keymaps at any time, and each keymap has one
or more names. If all of a keymap's names are deleted, it disappears.
bindkey can be used to manipulate keymap names.
Initially, there are four keymaps:
emacs EMACS emulation
viins vi emulation - insert mode
vicmd vi emulation - command mode
.safe fallback keymap
The `.safe' keymap is special. It can never be altered, and the name
can never be removed. However, it can be linked to other names, which
can be removed. In the future other special keymaps may be added;
users should avoid using names beginning with `.' for their own
keymaps.
In addition to these four names, either `emacs' or `viins' is also
linked to the name `main'. If one of the VISUAL or EDITOR environment
variables contain the string `vi' when the shell starts up then it will
be `viins', otherwise it will be `emacs'. bindkey's -e and -v options
provide a convenient way to override this default choice.
When the editor starts up, it will select the `main' keymap. If that
keymap doesn't exist, it will use `.safe' instead.
In the `.safe' keymap, each single key is bound to self-insert, except
for ^J (line feed) and ^M (return) which are bound to accept-line.
This is deliberately not pleasant to use; if you are using it, it means
you deleted the main keymap, and you should put it back.
Reading Commands
When ZLE is reading a command from the terminal, it may read a sequence
that is bound to some command and is also a prefix of a longer bound
string. In this case ZLE will wait a certain time to see if more char-
acters are typed, and if not (or they don't match any longer string) it
will execute the binding. This timeout is defined by the KEYTIMEOUT
parameter; its default is 0.4 sec. There is no timeout if the prefix
string is not itself bound to a command.
As well as ZLE commands, key sequences can be bound to other strings,
by using `bindkey -s'. When such a sequence is read, the replacement
string is pushed back as input, and the command reading process starts
again using these fake keystrokes. This input can itself invoke fur-
ther replacement strings, but in order to detect loops the process will
be stopped if there are twenty such replacements without a real command
being read.
ZLE BUILTINS
The ZLE module contains three related builtin commands. The bindkey
command manipulates keymaps and key bindings; the vared command invokes
ZLE on the value of a shell parameter; and the zle command manipulates
editing widgets and allows command line access to ZLE commands from
within shell functions.
bindkey [ options ] -l
bindkey [ options ] -d
bindkey [ options ] -D keymap ...
bindkey [ options ] -A old-keymap new-keymap
bindkey [ options ] -N new-keymap [ old-keymap ]
bindkey [ options ] -m
bindkey [ options ] -r in-string ...
bindkey [ options ] -s in-string out-string ...
bindkey [ options ] in-string command ...
bindkey [ options ] [ in-string ]
bindkey's options can be divided into three categories: keymap
selection, operation selection, and others. The keymap selec-
tion options are:
-e Selects keymap `emacs', and also links it to `main'.
-v Selects keymap `viins', and also links it to `main'.
-a Selects keymap `vicmd'.
-M keymap
The keymap specifies a keymap name.
If a keymap selection is required and none of the options above
are used, the `main' keymap is used. Some operations do not
permit a keymap to be selected, namely:
-l List all existing keymap names. If the -L option is also
used, list in the form of bindkey commands to create the
keymaps.
-d Delete all existing keymaps and reset to the default
state.
-D keymap ...
Delete the named keymaps.
-A old-keymap new-keymap
Make the new-keymap name an alias for old-keymap, so that
both names refer to the same keymap. The names have
equal standing; if either is deleted, the other remains.
If there is already a keymap with the new-keymap name, it
is deleted.
-N new-keymap [ old-keymap ]
Create a new keymap, named new-keymap. If a keymap
already has that name, it is deleted. If an old-keymap
name is given, the new keymap is initialized to be a
duplicate of it, otherwise the new keymap will be empty.
To use a newly created keymap, it should be linked to main.
Hence the sequence of commands to create and use a new keymap
`mymap' initialized from the emacs keymap (which remains
unchanged) is:
bindkey -N mymap emacs
bindkey -A mymap main
Note that while `bindkey -A newmap main' will work when newmap
is emacs or viins, it will not work for vicmd, as switching from
vi insert to command mode becomes impossible.
The following operations act on the `main' keymap if no keymap
selection option was given:
-m Add the built-in set of meta-key bindings to the selected
keymap. Only keys that are unbound or bound to
self-insert are affected.
-r in-string ...
Unbind the specified in-strings in the selected keymap.
This is exactly equivalent to binding the strings to
undefined-key.
When -R is also used, interpret the in-strings as ranges.
When -p is also used, the in-strings specify prefixes.
Any binding that has the given in-string as a prefix, not
including the binding for the in-string itself, if any,
will be removed. For example,
bindkey -rpM viins ''^^[''
will remove all bindings in the vi-insert keymap begin-
ning with an escape character (probably cursor keys), but
leave the binding for the escape character itself (proba-
bly vi-cmd-mode). This is incompatible with the option
-R.
-s in-string out-string ...
Bind each in-string to each out-string. When in-string
is typed, out-string will be pushed back and treated as
input to the line editor. When -R is also used, inter-
pret the in-strings as ranges.
in-string command ...
Bind each in-string to each command. When -R is used,
interpret the in-strings as ranges.
[ in-string ]
List key bindings. If an in-string is specified, the
binding of that string in the selected keymap is dis-
played. Otherwise, all key bindings in the selected
keymap are displayed. (As a special case, if the -e or
-v option is used alone, the keymap is not displayed -
the implicit linking of keymaps is the only thing that
happens.)
When the option -p is used, the in-string must be
present. The listing shows all bindings which have the
given key sequence as a prefix, not including any bind-
ings for the key sequence itself.
When the -L option is used, the list is in the form of
bindkey commands to create the key bindings.
When the -R option is used as noted above, a valid range consists of
two characters, with an optional `-' between them. All characters
between the two specified, inclusive, are bound as specified.
For either in-string or out-string, the following escape sequences are
recognised:
\\a bell character
\\b backspace
\\e, \\E escape
\\f form feed
\\n linefeed (newline)
\\r carriage return
\\t horizontal tab
\\v vertical tab
\\N character code in octal
\\xN character code in hexadecimal
\\M[-]X character with meta bit set
\\C[-]X control character
^^X control character
In all other cases, `\\' escapes the following character. Delete is
written as `^^??'. Note that `\\M^^??' and `^^\\M??' are not the same, and
that (unlike emacs), the bindings `\\-X' and `\\eX' are entirely dis-
tinct, although they are initialized to the same bindings by `bindkey
-m'.
vared [ -Aache ] [ -p prompt ] [ -r rprompt ]
[ -M main-keymap ] [ -m vicmd-keymap ] name
The value of the parameter name is loaded into the edit buffer,
and the line editor is invoked. When the editor exits, name is
set to the string value returned by the editor. When the -c
flag is given, the parameter is created if it doesn't already
exist. The -a flag may be given with -c to create an array
parameter, or the -A flag to create an associative array. If
the type of an existing parameter does not match the type to be
created, the parameter is unset and recreated.
If an array or array slice is being edited, separator characters
as defined in $$IFS will be shown quoted with a backslash, as
will backslashes themselves. Conversely, when the edited text
is split into an array, a backslash quotes an immediately fol-
lowing separator character or backslash; no other special han-
dling of backslashes, or any handling of quotes, is performed.
Individual elements of existing array or associative array
parameters may be edited by using subscript syntax on name. New
elements are created automatically, even without -c.
If the -p flag is given, the following string will be taken as
the prompt to display at the left. If the -r flag is given, the
following string gives the prompt to display at the right. If
the -h flag is specified, the history can be accessed from ZLE.
If the -e flag is given, typing ^^D (Control-D) on an empty line
causes vared to exit immediately with a non-zero return value.
The -M option gives a keymap to link to the main keymap during
editing, and the -m option gives a keymap to link to the vicmd
keymap during editing. For vi-style editing, this allows a pair
of keymaps to override viins and vicmd. For emacs-style edit-
ing, only -M is normally needed but the -m option may still be
used. On exit, the previous keymaps will be restored.
zle
zle -l [ -L -a ] [ string ... ]
zle -D widget ...
zle -A old-widget new-widget
zle -N widget [ function ]
zle -C widget completion-widget function
zle -R [ -c ] [ display-string ] [ string ... ]
zle -M string
zle -U string
zle -K keymap
zle -F [ -L ] [ fd [ handler ] ]
zle -I
zle widget [ -n num ] [ -N ] args ...
The zle builtin performs a number of different actions concern-
ing ZLE.
With no options and no arguments, only the return status will be
set. It is zero if ZLE is currently active and widgets could be
invoked using this builtin command and non-zero otherwise. Note
that even if non-zero status is returned, zle may still be
active as part of the completion system; this does not allow
direct calls to ZLE widgets.
Otherwise, which operation it performs depends on its options:
-l [ -L -a ]
List all existing user-defined widgets. If the -L option
is used, list in the form of zle commands to create the
widgets.
When combined with the -a option, all widget names are
listed, including the builtin ones. In this case the -L
option is ignored.
If at least one string is given, nothing will be printed
but the return status will be zero if all strings are
names of existing widgets (or of user-defined widgets if
the -a flag is not given) and non-zero if at least one
string is not a name of an defined widget.
-D widget ...
Delete the named widgets.
-A old-widget new-widget
Make the new-widget name an alias for old-widget, so that
both names refer to the same widget. The names have
equal standing; if either is deleted, the other remains.
If there is already a widget with the new-widget name, it
is deleted.
-N widget [ function ]
Create a user-defined widget. If there is already a wid-
get with the specified name, it is overwritten. When the
new widget is invoked from within the editor, the speci-
fied shell function is called. If no function name is
specified, it defaults to the same name as the widget.
For further information, see the section Widgets in zsh-
zle(1).
-C widget completion-widget function
Create a user-defined completion widget named widget. The
completion widget will behave like the built-in comple-
tion-widget whose name is given as completion-widget. To
generate the completions, the shell function function
will be called. For further information, see zshcomp-
wid(1).
-R [ -c ] [ display-string ] [ string ... ]
Redisplay the command line; this is to be called from
within a user-defined widget to allow changes to become
visible. If a display-string is given and not empty,
this is shown in the status line (immediately below the
line being edited).
If the optional strings are given they are listed below
the prompt in the same way as completion lists are
printed. If no strings are given but the -c option is
used such a list is cleared.
Note that this option is only useful for widgets that do
not exit immediately after using it because the strings
displayed will be erased immediately after return from
the widget.
This command can safely be called outside user defined
widgets; if zle is active, the display will be refreshed,
while if zle is not active, the command has no effect.
In this case there will usually be no other arguments.
The status is zero if zle was active, else one.
-M string
As with the -R option, the string will be displayed below
the command line; unlike the -R option, the string will
not be put into the status line but will instead be
printed normally below the prompt. This means that the
string will still be displayed after the widget returns
(until it is overwritten by subsequent commands).
-U string
This pushes the characters in the string onto the input
stack of ZLE. After the widget currently executed fin-
ishes ZLE will behave as if the characters in the string
were typed by the user.
As ZLE uses a stack, if this option is used repeatedly
the last string pushed onto the stack will be processed
first. However, the characters in each string will be
processed in the order in which they appear in the
string.
-K keymap
Selects the keymap named keymap. An error message will
be displayed if there is no such keymap.
This keymap selection affects the interpretation of fol-
lowing keystrokes within this invocation of ZLE. Any
following invocation (e.g., the next command line) will
start as usual with the `main' keymap selected.
-F [ -L ] [ fd [ handler ] ]
Only available if your system supports one of the `poll'
or `select' system calls; most modern systems do.
Installs handler (the name of a shell function) to handle
input from file descriptor fd. When zle is attempting to
read data, it will examine both the terminal and the list
of handled fd's. If data becomes available on a handled
fd, zle will call handler with the fd which is ready for
reading as the only argument. If the handler produces
output to the terminal, it should call `zle -I' before
doing so (see below). The handler should not attempt to
read from the terminal. Note that zle makes no attempt
to check whether this fd is actually readable when
installing the handler. The user must make their own
arrangements for handling the file descriptor when zle is
not active.
Any number of handlers for any number of readable file
descriptors may be installed. Installing a handler for
an fd which is already handled causes the existing han-
dler to be replaced.
If no handler is given, but an fd is present, any handler
for that fd is removed. If there is none, an error mes-
sage is printed and status 1 is returned.
If no arguments are given, or the -L option is supplied,
a list of handlers is printed in a form which can be
stored for later execution.
An fd (but not a handler) may optionally be given with
the -L option; in this case, the function will list the
handler if any, else silently return status 1.
Note that this feature should be used with care. Activ-
ity on one of the fd's which is not properly handled can
cause the terminal to become unusable.
Here is a simple example of using this feature. A con-
nection to a remote TCP port is created using the ztcp
command; see the description of the zsh/net/tcp module in
zshmodules(1). Then a handler is installed which simply
prints out any data which arrives on this connection.
Note that `select' will indicate that the file descriptor
needs handling if the remote side has closed the connec-
tion; we handle that by testing for a failed read.
if ztcp pwspc 2811;; then
tcpfd==$$REPLY
handler() {{
zle -I
local line
if !! read -r line <<&&$$1;; then
## select marks this fd if we reach EOF,,
## so handle this specially.
print ""[Read on fd $$1 failed,, removing.]"" >>&&2
zle -F $$1
return 1
fi
print -r - $$line
}}
zle -F $$tcpfd handler
fi
-I Unusually, this option is most useful outside ordinary
widget functions, though it may be used within if normal
output to the terminal is required. It invalidates the
current zle display in preparation for output; typically
this will be from a trap function. It has no effect if
zle is not active. When a trap exits, the shell checks
to see if the display needs restoring, hence the follow-
ing will print output in such a way as not to disturb the
line being edited:
TRAPUSR1() {{
## Invalidate zle display
[ -o zle ] &&&& zle -I
## Show output
print Hello
}}
In general, the trap function may need to test whether
zle is active before using this method (as shown in the
example), since the zsh/zle module may not even be
loaded; if it is not, the command can be skipped.
It is possible to call `zle -I' several times before con-
trol is returned to the editor; the display will only be
invalidated the first time to minimise disruption.
Note that there are normally better ways of manipulating
the display from within zle widgets; see, for example,
`zle -R' above.
The returned status is zero if zle was invalidated, even
though this may have been by a previous call to `zle -I'
or by a system notification. To test if a zle widget may
be called at this point, execute zle with no arguments
and examine the return status.
widget [ -n num ] [ -N ] args ...
Invoke the specified widget. This can only be done when
ZLE is active; normally this will be within a
user-defined widget.
With the options -n and -N, the current numerical argu-
ment will be saved and then restored after the call to
widget; `-n num' sets the numerical argument temporarily
to num, while `-N' sets it to the default, i.e. as if
there were none.
Any further arguments will be passed to the widget. If
it is a shell function, these are passed down as posi-
tional parameters; for builtin widgets it is up to the
widget in question what it does with them. Currently
arguments are only handled by the incremental-search com-
mands, the history-search-forward and -backward and the
corresponding functions prefixed by vi-, and by univer-
sal-argument. No error is flagged if the command does
not use the arguments, or only uses some of them.
The return status reflects the success or failure of the
operation carried out by the widget, or if it is a
user-defined widget the return status of the shell func-
tion.
A non-zero return status causes the shell to beep when
the widget exits, unless the BEP options was unset or
the widget was called via the zle command. Thus if a
user defined widget requires an immediate beep, it should
call the beep widget directly.
WIDGETS
All actions in the editor are performed by `widgets'. A widget's job
is simply to perform some small action. The ZLE commands that key
sequences in keymaps are bound to are in fact widgets. Widgets can be
user-defined or built in.
The standard widgets built in to ZLE are listed in Standard Widgets
below. Other built-in widgets can be defined by other modules (see
zshmodules(1)). Each built-in widget has two names: its normal canoni-
cal name, and the same name preceded by a `.'. The `.' name is spe-
cial: it can't be rebound to a different widget. This makes the widget
available even when its usual name has been redefined.
User-defined widgets are defined using `zle -N', and implemented as
shell functions. When the widget is executed, the corresponding shell
function is executed, and can perform editing (or other) actions. It
is recommended that user-defined widgets should not have names starting
with `.'.
USER-DEFINED WIDGETS
User-defined widgets, being implemented as shell functions, can execute
any normal shell command. They can also run other widgets (whether
built-in or user-defined) using the zle builtin command. The standard
input of the function is closed to prevent external commands from unin-
tentionally blocking ZLE by reading from the terminal, but read -k or
read -q can be used to read characters. Finally, they can examine and
edit the ZLE buffer being edited by reading and setting the special
parameters described below.
These special parameters are always available in widget functions, but
are not in any way special outside ZLE. If they have some normal value
outside ZLE, that value is temporarily inaccessible, but will return
when the widget function exits. These special parameters in fact have
local scope, like parameters created in a function using local.
Inside completion widgets and traps called while ZLE is active, these
parameters are available read-only.
BUFER (scalar)
The entire contents of the edit buffer. If it is written to,
the cursor remains at the same offset, unless that would put it
outside the buffer.
BUFERLINES (integer)
The number of screen lines needed for the edit buffer currently
displayed on screen (i.e. without any changes to the preceding
parameters done after the last redisplay); read-only.
CONTEXT (scalar)
The context in which zle was called to read a line; read-only.
One of the values:
start The start of a command line (at prompt PS1).
cont A continuation to a command line (at prompt PS2).
select In a select loop.
vared Editing a variable in vared.
CURSOR (integer)
The offset of the cursor, within the edit buffer. This is in
the range 0 to $$##BUFER, and is by definition equal to
$$##LBUFER. Attempts to move the cursor outside the buffer will
result in the cursor being moved to the appropriate end of the
buffer.
CUTBUFER (scalar)
The last item to be cut using one of the `kill-' commands; the
string which the next yank would insert in the line.
HISTNO (integer)
The current history number. Setting this has the same effect as
moving up or down in the history to the corresponding history
line. An attempt to set it is ignored if the line is not stored
in the history. Note this is not the same as the parameter
HISTCMD, which always gives the number of the history line being
added to the main shell's history. HISTNO refers to the line
being retrieved within zle.
KEYMAP (scalar)
The name of the currently selected keymap; read-only.
KEYS (scalar)
The keys typed to invoke this widget, as a literal string;
read-only.
killring (array)
The array of previously killed items, with the most recently
killed first. This gives the items that would be retrieved by a
yank-pop in the same order.
The default size for the kill ring is eight, however the length
may be changed by normal array operations. Any empty string in
the kill ring is ignored by the yank-pop command, hence the size
of the array effectively sets the maximum length of the kill
ring, while the number of non-zero strings gives the current
length, both as seen by the user at the command line.
LASTSEARCH (scalar)
The last search string used by an interactive search ;
read-only.
LASTWIDGET (scalar)
The name of the last widget that was executed; read-only.
LBUFER (scalar)
The part of the buffer that lies to the left of the cursor posi-
tion. If it is assigned to, only that part of the buffer is
replaced, and the cursor remains between the new $$LBUFER and
the old $$RBUFER.
MARK (integer)
Like CURSOR, but for the mark.
NUMERIC (integer)
The numeric argument. If no numeric argument was given, this
parameter is unset. When this is set inside a widget function,
builtin widgets called with the zle builtin command will use the
value assigned. If it is unset inside a widget function, builtin
widgets called behave as if no numeric argument was given.
PENDING (integer)
The number of bytes pending for input, i.e. the number of bytes
which have already been typed and can immediately be read. On
systems where the shell is not able to get this information,
this parameter will always have a value of zero. Read-only.
PREBUFER (scalar)
In a multi-line input at the secondary prompt, this read-only
parameter contains the contents of the lines before the one the
cursor is currently in.
PREDISPLAY (scalar)
Text to be displayed before the start of the editable text
buffer. This does not have to be a complete line; to display a
complete line, a newline must be appended explicitly. The
text is reset on each new invocation (but not recursive invoca-
tion) of zle.
POSTDISPLAY (scalar)
Text to be displayed after the end of the editable text buffer.
This does not have to be a complete line; to display a complete
line, a newline must be prepended explicitly. The text is reset
on each new invocation (but not recursive invocation) of zle.
RBUFER (scalar)
The part of the buffer that lies to the right of the cursor
position. If it is assigned to, only that part of the buffer is
replaced, and the cursor remains between the old $$LBUFER and
the new $$RBUFER.
WIDGET (scalar)
The name of the widget currently being executed; read-only.
WIDGETFUNC (scalar)
The name of the shell function that implements a widget defined
with either zle -N or zle -C. In the former case, this is the
second argument to the zle -N command that defined the widget,
or the first argument if there was no second argument. In the
latter case this is the the third argument to the zle -C command
that defined the widget. Read-only.
WIDGETSTYLE (scalar)
Describes the implementation behind the completion widget cur-
rently being executed; the second argument that followed zle -C
when the widget was defined. This is the name of a builtin com-
pletion widget. For widgets defined with zle -N this is set to
the empty string. Read-only.
Special Widget
There is one user-defined widget which is special to the shell. If it
does not exist, no special action is taken. The environment provided
is identical to that for any other editing widget.
zle-line-init
Executed every time the line editor is started to read a new
line of input. The following example puts the line editor into
vi command mode when it starts up.
zle-line-init() {{ zle -K vicmd;; }}
zle -N zle-line-init
(The command inside the function sets the keymap directly; it is
equivalent to zle vi-cmd-mode.)
STANDARD WIDGETS
The following is a list of all the standard widgets, and their default
bindings in emacs mode, vi command mode and vi insert mode (the
`emacs', `vicmd' and `viins' keymaps, respectively).
Note that cursor keys are bound to movement keys in all three keymaps;
the shell assumes that the cursor keys send the key sequences reported
by the terminal-handling library (termcap or terminfo). The key
sequences shown in the list are those based on the VT100, common on
many modern terminals, but in fact these are not necessarily bound. In
the case of the viins keymap, the initial escape character of the
sequences serves also to return to the vicmd keymap: whether this hap-
pens is determined by the KEYTIMEOUT parameter, see zshparam(1).
ovement
vi-backward-blank-word (unbound) (B) (unbound)
Move backward one word, where a word is defined as a series of
non-blank characters.
backward-char (^B ESC-[D) (unbound) (unbound)
Move backward one character.
vi-backward-char (unbound) (^H h ^?) (ESC-[D)
Move backward one character, without changing lines.
backward-word (ESC-B ESC-b) (unbound) (unbound)
Move to the beginning of the previous word.
emacs-backward-word
Move to the beginning of the previous word.
vi-backward-word (unbound) (b) (unbound)
Move to the beginning of the previous word, vi-style.
beginning-of-line (^A) (unbound) (unbound)
Move to the beginning of the line. If already at the beginning
of the line, move to the beginning of the previous line, if any.
vi-beginning-of-line
Move to the beginning of the line, without changing lines.
end-of-line (^E) (unbound) (unbound)
Move to the end of the line. If already at the end of the line,
move to the end of the next line, if any.
vi-end-of-line (unbound) ($) (unbound)
Move to the end of the line. If an argument is given to this
command, the cursor will be moved to the end of the line (argu-
ment - 1) lines down.
vi-forward-blank-word (unbound) (W) (unbound)
Move forward one word, where a word is defined as a series of
non-blank characters.
vi-forward-blank-word-end (unbound) (E) (unbound)
Move to the end of the current word, or, if at the end of the
current word, to the end of the next word, where a word is
defined as a series of non-blank characters.
forward-char (^F ESC-[C) (unbound) (unbound)
Move forward one character.
vi-forward-char (unbound) (space l) (ESC-[C)
Move forward one character.
vi-find-next-char (^X^F) (f) (unbound)
Read a character from the keyboard, and move to the next occur-
rence of it in the line.
vi-find-next-char-skip (unbound) (t) (unbound)
Read a character from the keyboard, and move to the position
just before the next occurrence of it in the line.
vi-find-prev-char (unbound) (F) (unbound)
Read a character from the keyboard, and move to the previous
occurrence of it in the line.
vi-find-prev-char-skip (unbound) (T) (unbound)
Read a character from the keyboard, and move to the position
just after the previous occurrence of it in the line.
vi-first-non-blank (unbound) (^) (unbound)
Move to the first non-blank character in the line.
vi-forward-word (unbound) (w) (unbound)
Move forward one word, vi-style.
forward-word (ESC-F ESC-f) (unbound) (unbound)
Move to the beginning of the next word. The editor's idea of a
word is specified with the WORDCHARS parameter.
emacs-forward-word
Move to the end of the next word.
vi-forward-word-end (unbound) (e) (unbound)
Move to the end of the next word.
vi-goto-column (ESC-) () (unbound)
Move to the column specified by the numeric argument.
vi-goto-mark (unbound) (`) (unbound)
Move to the specified mark.
vi-goto-mark-line (unbound) (') (unbound)
Move to beginning of the line containing the specified mark.
vi-repeat-find (unbound) (;) (unbound)
Repeat the last vi-find command.
vi-rev-repeat-find (unbound) (,) (unbound)
Repeat the last vi-find command in the opposite direction.
History Control
beginning-of-buffer-or-history (ESC-<) (unbound) (unbound)
Move to the beginning of the buffer, or if already there, move
to the first event in the history list.
beginning-of-line-hist
Move to the beginning of the line. If already at the beginning
of the buffer, move to the previous history line.
beginning-of-history
Move to the first event in the history list.
down-line-or-history (^N ESC-[B) (j) (ESC-[B)
Move down a line in the buffer, or if already at the bottom
line, move to the next event in the history list.
vi-down-line-or-history (unbound) (]) (unbound)
Move down a line in the buffer, or if already at the bottom
line, move to the next event in the history list. Then move to
the first non-blank character on the line.
down-line-or-search
Move down a line in the buffer, or if already at the bottom
line, search forward in the history for a line beginning with
the first word in the buffer.
If called from a function by the zle command with arguments, the
first argument is taken as the string for which to search,
rather than the first word in the buffer.
down-history (unbound) (^N) (unbound)
Move to the next event in the history list.
history-beginning-search-backward
Search backward in the history for a line beginning with the
current line up to the cursor. This leaves the cursor in its
original position.
end-of-buffer-or-history (ESC->) (unbound) (unbound)
Move to the end of the buffer, or if already there, move to the
last event in the history list.
end-of-line-hist
Move to the end of the line. If already at the end of the
buffer, move to the next history line.
end-of-history
Move to the last event in the history list.
vi-fetch-history (unbound) (G) (unbound)
Fetch the history line specified by the numeric argument. This
defaults to the current history line (i.e. the one that isn't
history yet).
history-incremental-search-backward (^R ^Xr) (unbound) (unbound)
Search backward incrementally for a specified string. The
search is case-insensitive if the search string does not have
uppercase letters and no numeric argument was given. The string
may begin with `^^' to anchor the search to the beginning of the
line.
A restricted set of editing functions is available in the
mini-buffer. An interrupt signal, as defined by the stty set-
ting, will stop the search and go back to the original line. An
undefined key will have the same effect. The supported functions
are: backward-delete-char, vi-backward-delete-char,
clear-screen, redisplay, quoted-insert, vi-quoted-insert,
accept-and-hold, accept-and-infer-next-history, accept-line and
accept-line-and-down-history.
magic-space just inserts a space. vi-cmd-mode toggles between
the `main' and `vicmd' keymaps; the `main' keymap (insert mode)
will be selected initially. history-incremental-search-backward
will get the next occurrence of the contents of the mini-buffer.
history-incremental-search-forward inverts the sense of the
search. vi-repeat-search and vi-rev-repeat-search are similarly
supported. The direction of the search is indicated in the
mini-buffer.
Any multi-character string that is not bound to one of the above
functions will beep and interrupt the search, leaving the last
found line in the buffer. Any single character that is not bound
to one of the above functions, or self-insert or
self-insert-unmeta, will have the same effect but the function
will be executed.
When called from a widget function by the zle command, the
incremental search commands can take a string argument. This
will be treated as a string of keys, as for arguments to the
bindkey command, and used as initial input for the command. Any
characters in the string which are unused by the incremental
search will be silently ignored. For example,
zle history-incremental-search-backward forceps
will search backwards for forceps, leaving the minibuffer con-
taining the string `forceps'.
history-incremental-search-forward (^S ^Xs) (unbound) (unbound)
Search forward incrementally for a specified string. The search
is case-insensitive if the search string does not have uppercase
letters and no numeric argument was given. The string may begin
with `^^' to anchor the search to the beginning of the line. The
functions available in the mini-buffer are the same as for his-
tory-incremental-search-backward.
history-search-backward (ESC-P ESC-p) (unbound) (unbound)
Search backward in the history for a line beginning with the
first word in the buffer.
If called from a function by the zle command with arguments, the
first argument is taken as the string for which to search,
rather than the first word in the buffer.
vi-history-search-backward (unbound) (/) (unbound)
Search backward in the history for a specified string. The
string may begin with `^^' to anchor the search to the beginning
of the line.
A restricted set of editing functions is available in the
mini-buffer. An interrupt signal, as defined by the stty set-
ting, will stop the search. The functions available in the
mini-buffer are: accept-line, backward-delete-char, vi-back-
ward-delete-char, backward-kill-word, vi-backward-kill-word,
clear-screen, redisplay, quoted-insert and vi-quoted-insert.
vi-cmd-mode is treated the same as accept-line, and magic-space
is treated as a space. Any other character that is not bound to
self-insert or self-insert-unmeta will beep and be ignored. If
the function is called from vi command mode, the bindings of the
current insert mode will be used.
If called from a function by the zle command with arguments, the
first argument is taken as the string for which to search,
rather than the first word in the buffer.
history-search-forward (ESC-N ESC-n) (unbound) (unbound)
Search forward in the history for a line beginning with the
first word in the buffer.
If called from a function by the zle command with arguments, the
first argument is taken as the string for which to search,
rather than the first word in the buffer.
vi-history-search-forward (unbound) (?) (unbound)
Search forward in the history for a specified string. The
string may begin with `^^' to anchor the search to the beginning
of the line. The functions available in the mini-buffer are the
same as for vi-history-search-backward. Argument handling is
also the same as for that command.
infer-next-history (^X^N) (unbound) (unbound)
Search in the history list for a line matching the current one
and fetch the event following it.
insert-last-word (ESC- ESC-.) (unbound) (unbound)
Insert the last word from the previous history event at the cur-
sor position. If a positive numeric argument is given, insert
that word from the end of the previous history event. If the
argument is zero or negative insert that word from the left
(zero inserts the previous command word). Repeating this com-
mand replaces the word just inserted with the last word from the
history event prior to the one just used; numeric arguments can
be used in the same way to pick a word from that event.
When called from a shell function invoked from a user-defined
widget, the command can take one to three arguments. The first
argument specifies a history offset which applies to successive
calls to this widget: if is -1, the default behaviour is used,
while if it is 1, successive calls will move forwards through
the history. The value 0 can be used to indicate that the his-
tory line examined by the previous execution of the command will
be reexamined. Note that negative numbers should be preceded
with a `--' argument to avoid confusing them with options.
If two arguments are given, the second specifies the word on the
command line in normal array index notation (as a more natural
alternative to the prefix argument). Hence 1 is the first word,
and -1 (the default) is the last word.
If a third argument is given, its value is ignored, but it is
used to signify that the history offset is relative to the cur-
rent history line, rather than the one remembered after the pre-
vious invocations of insert-last-word.
For example, the default behaviour of the command corresponds to
zle insert-last-word -- -1 -1
while the command
zle insert-last-word -- -1 1 -
always copies the first word of the line in the history immedi-
ately before the line being edited. This has the side effect
that later invocations of the widget will be relative to that
line.
vi-repeat-search (unbound) (n) (unbound)
Repeat the last vi history search.
vi-rev-repeat-search (unbound) (N) (unbound)
Repeat the last vi history search, but in reverse.
up-line-or-history (^P ESC-[A) (k) (ESC-[A)
Move up a line in the buffer, or if already at the top line,
move to the previous event in the history list.
vi-up-line-or-history (unbound) (-) (unbound)
Move up a line in the buffer, or if already at the top line,
move to the previous event in the history list. Then move to
the first non-blank character on the line.
up-line-or-search
Move up a line in the buffer, or if already at the top line,
search backward in the history for a line beginning with the
first word in the buffer.
If called from a function by the zle command with arguments, the
first argument is taken as the string for which to search,
rather than the first word in the buffer.
up-history (unbound) (^P) (unbound)
Move to the previous event in the history list.
history-beginning-search-forward
Search forward in the history for a line beginning with the cur-
rent line up to the cursor. This leaves the cursor in its orig-
inal position.
odifying Text
vi-add-eol (unbound) (A) (unbound)
Move to the end of the line and enter insert mode.
vi-add-next (unbound) (a) (unbound)
Enter insert mode after the current cursor position, without
changing lines.
backward-delete-char (^H ^?) (unbound) (unbound)
Delete the character behind the cursor.
vi-backward-delete-char (unbound) (X) (^H)
Delete the character behind the cursor, without changing lines.
If in insert mode, this won't delete past the point where insert
mode was last entered.
backward-delete-word
Delete the word behind the cursor.
backward-kill-line
Kill from the beginning of the line to the cursor position.
backward-kill-word (^W ESC-^H ESC-^?) (unbound) (unbound)
Kill the word behind the cursor.
vi-backward-kill-word (unbound) (unbound) (^W)
Kill the word behind the cursor, without going past the point
where insert mode was last entered.
capitalize-word (ESC-C ESC-c) (unbound) (unbound)
Capitalize the current word and move past it.
vi-change (unbound) (c) (unbound)
Read a movement command from the keyboard, and kill from the
cursor position to the endpoint of the movement. Then enter
insert mode. If the command is vi-change, change the current
line.
vi-change-eol (unbound) (C) (unbound)
Kill to the end of the line and enter insert mode.
vi-change-whole-line (unbound) (S) (unbound)
Kill the current line and enter insert mode.
copy-region-as-kill (ESC-W ESC-w) (unbound) (unbound)
Copy the area from the cursor to the mark to the kill buffer.
copy-prev-word (ESC-^) (unbound) (unbound)
Duplicate the word to the left of the cursor.
copy-prev-shell-word
Like copy-prev-word, but the word is found by using shell pars-
ing, whereas copy-prev-word looks for blanks. This makes a dif-
ference when the word is quoted and contains spaces.
vi-delete (unbound) (d) (unbound)
Read a movement command from the keyboard, and kill from the
cursor position to the endpoint of the movement. If the command
is vi-delete, kill the current line.
delete-char
Delete the character under the cursor.
vi-delete-char (unbound) (x) (unbound)
Delete the character under the cursor, without going past the
end of the line.
delete-word
Delete the current word.
down-case-word (ESC-L ESC-l) (unbound) (unbound)
Convert the current word to all lowercase and move past it.
kill-word (ESC-D ESC-d) (unbound) (unbound)
Kill the current word.
gosmacs-transpose-chars
Exchange the two characters behind the cursor.
vi-indent (unbound) (>) (unbound)
Indent a number of lines.
vi-insert (unbound) (i) (unbound)
Enter insert mode.
vi-insert-bol (unbound) (I) (unbound)
Move to the first non-blank character on the line and enter
insert mode.
vi-join (^X^J) (J) (unbound)
Join the current line with the next one.
kill-line (^K) (unbound) (unbound)
Kill from the cursor to the end of the line. If already on the
end of the line, kill the newline character.
vi-kill-line (unbound) (unbound) (^U)
Kill from the cursor back to wherever insert mode was last
entered.
vi-kill-eol (unbound) (D) (unbound)
Kill from the cursor to the end of the line.
kill-region
Kill from the cursor to the mark.
kill-buffer (^X^K) (unbound) (unbound)
Kill the entire buffer.
kill-whole-line (^U) (unbound) (unbound)
Kill the current line.
vi-match-bracket (^X^B) (%) (unbound)
Move to the bracket character (one of {{}}, () or []) that matches
the one under the cursor. If the cursor is not on a bracket
character, move forward without going past the end of the line
to find one, and then go to the matching bracket.
vi-open-line-above (unbound) (O) (unbound)
Open a line above the cursor and enter insert mode.
vi-open-line-below (unbound) (o) (unbound)
Open a line below the cursor and enter insert mode.
vi-oper-swap-case
Read a movement command from the keyboard, and swap the case of
all characters from the cursor position to the endpoint of the
movement. If the movement command is vi-oper-swap-case, swap
the case of all characters on the current line.
overwrite-mode (^X^O) (unbound) (unbound)
Toggle between overwrite mode and insert mode.
vi-put-before (unbound) (P) (unbound)
Insert the contents of the kill buffer before the cursor. If
the kill buffer contains a sequence of lines (as opposed to
characters), paste it above the current line.
vi-put-after (unbound) (p) (unbound)
Insert the contents of the kill buffer after the cursor. If the
kill buffer contains a sequence of lines (as opposed to charac-
ters), paste it below the current line.
quoted-insert (^V) (unbound) (unbound)
Insert the next character typed into the buffer literally. An
interrupt character will not be inserted.
vi-quoted-insert (unbound) (unbound) (^Q ^V)
Display a `^^' at the cursor position, and insert the next char-
acter typed into the buffer literally. An interrupt character
will not be inserted.
quote-line (ESC-') (unbound) (unbound)
Quote the current line; that is, put a `''' character at the
beginning and the end, and convert all `''' characters to `''\\'''''.
quote-region (ESC-") (unbound) (unbound)
Quote the region from the cursor to the mark.
vi-replace (unbound) (R) (unbound)
Enter overwrite mode.
vi-repeat-change (unbound) (.) (unbound)
Repeat the last vi mode text modification. If a count was used
with the modification, it is remembered. If a count is given to
this command, it overrides the remembered count, and is remem-
bered for future uses of this command. The cut buffer specifi-
cation is similarly remembered.
vi-replace-chars (unbound) (r) (unbound)
Replace the character under the cursor with a character read
from the keyboard.
self-insert (printable characters) (unbound) (printable characters and
some control characters)
Insert a character into the buffer at the cursor position.
self-insert-unmeta (ESC-^I ESC-^J ESC-^M) (unbound) (unbound)
Insert a character into the buffer after stripping the meta bit
and converting ^M to ^J.
vi-substitute (unbound) (s) (unbound)
Substitute the next character(s).
vi-swap-case (unbound) (~) (unbound)
Swap the case of the character under the cursor and move past
it.
transpose-chars (^T) (unbound) (unbound)
Exchange the two characters to the left of the cursor if at end
of line, else exchange the character under the cursor with the
character to the left.
transpose-words (ESC-T ESC-t) (unbound) (unbound)
Exchange the current word with the one before it.
vi-unindent (unbound) (<) (unbound)
Unindent a number of lines.
up-case-word (ESC-U ESC-u) (unbound) (unbound)
Convert the current word to all caps and move past it.
yank (^Y) (unbound) (unbound)
Insert the contents of the kill buffer at the cursor position.
yank-pop (ESC-y) (unbound) (unbound)
Remove the text just yanked, rotate the kill-ring, and yank the
new top. Only works following yank or yank-pop.
vi-yank (unbound) (y) (unbound)
Read a movement command from the keyboard, and copy the region
from the cursor position to the endpoint of the movement into
the kill buffer. If the command is vi-yank, copy the current
line.
vi-yank-whole-line (unbound) (Y) (unbound)
Copy the current line into the kill buffer.
vi-yank-eol
Copy the region from the cursor position to the end of the line
into the kill buffer. Arguably, this is what Y should do in vi,
but it isn't what it actually does.
Arguments
digit-argument (ESC-0..ESC-9) (1-9) (unbound)
Start a new numeric argument, or add to the current one. See
also vi-digit-or-beginning-of-line. This only works if bound to
a key sequence ending in a decimal digit.
Inside a widget function, a call to this function treats the
last key of the key sequence which called the widget as the
digit.
neg-argument (ESC--) (unbound) (unbound)
Changes the sign of the following argument.
universal-argument
Multiply the argument of the next command by 4. Alternatively,
if this command is followed by an integer (positive or nega-
tive), use that as the argument for the next command. Thus dig-
its cannot be repeated using this command. For example, if this
command occurs twice, followed immediately by forward-char, move
forward sixteen spaces; if instead it is followed by -2, then
forward-char, move backward two spaces.
Inside a widget function, if passed an argument, i.e. `zle uni-
versal-argument num', the numerical argument will be set to num;
this is equivalent to `NUMERIC==num'.
Completion
accept-and-menu-complete
In a menu completion, insert the current completion into the
buffer, and advance to the next possible completion.
complete-word
Attempt completion on the current word.
delete-char-or-list (^D) (unbound) (unbound)
Delete the character under the cursor. If the cursor is at the
end of the line, list possible completions for the current word.
expand-cmd-path
Expand the current command to its full pathname.
expand-or-complete (TAB) (unbound) (TAB)
Attempt shell expansion on the current word. If that fails,
attempt completion.
expand-or-complete-prefix
Attempt shell expansion on the current word up to cursor.
expand-history (ESC-space ESC-!) (unbound) (unbound)
Perform history expansion on the edit buffer.
expand-word (^X*) (unbound) (unbound)
Attempt shell expansion on the current word.
list-choices (ESC-^D) (^D =) (^D)
List possible completions for the current word.
list-expand (^Xg ^XG) (^G) (^G)
List the expansion of the current word.
magic-space
Perform history expansion and insert a space into the buffer.
This is intended to be bound to space.
menu-complete
Like complete-word, except that menu completion is used. See
the MENUCOMPLETE option.
menu-expand-or-complete
Like expand-or-complete, except that menu completion is used.
reverse-menu-complete
Perform menu completion, like menu-complete, except that if a
menu completion is already in progress, move to the previous
completion rather than the next.
end-of-list
When a previous completion displayed a list below the prompt,
this widget can be used to move the prompt below the list.
iscellaneous
accept-and-hold (ESC-A ESC-a) (unbound) (unbound)
Push the contents of the buffer on the buffer stack and execute
it.
accept-and-infer-next-history
Execute the contents of the buffer. Then search the history
list for a line matching the current one and push the event fol-
lowing onto the buffer stack.
accept-line (^J ^M) (^J ^M) (^J ^M)
Finish editing the buffer. Normally this causes the buffer to
be executed as a shell command.
accept-line-and-down-history (^O) (unbound) (unbound)
Execute the current line, and push the next history event on the
the buffer stack.
beep Beep, unless the BEP option is unset.
vi-cmd-mode (^X^V) (unbound) (^[)
Enter command mode; that is, select the `vicmd' keymap. Yes,
this is bound by default in emacs mode.
vi-caps-lock-panic
Hang until any lowercase key is pressed. This is for vi users
without the mental capacity to keep track of their caps lock key
(like the author).
clear-screen (^L ESC-^L) (^L) (^L)
Clear the screen and redraw the prompt.
describe-key-briefly
Reads a key sequence, then prints the function bound to that
sequence.
exchange-point-and-mark (^X^X) (unbound) (unbound)
Exchange the cursor position with the position of the mark.
execute-named-cmd (ESC-x) (unbound) (unbound)
Read the name of an editor command and execute it. A restricted
set of editing functions is available in the mini-buffer. An
interrupt signal, as defined by the stty setting, will abort the
function. The allowed functions are: backward-delete-char,
vi-backward-delete-char, clear-screen, redisplay, quoted-insert,
vi-quoted-insert, backward-kill-word, vi-backward-kill-word,
kill-whole-line, vi-kill-line, backward-kill-line, list-choices,
delete-char-or-list, complete-word, accept-line, expand-or-com-
plete and expand-or-complete-prefix.
kill-region kills the last word, and vi-cmd-mode is treated the
same as accept-line. The space and tab characters, if not bound
to one of these functions, will complete the name and then list
the possibilities if the AUTOLIST option is set. Any other
character that is not bound to self-insert or self-insert-unmeta
will beep and be ignored. The bindings of the current insert
mode will be used.
execute-last-named-cmd (ESC-z) (unbound) (unbound)
Redo the last function executed with execute-named-cmd.
get-line (ESC-G ESC-g) (unbound) (unbound)
Pop the top line off the buffer stack and insert it at the cur-
sor position.
pound-insert (unbound) (#) (unbound)
If there is no # character at the beginning of the buffer, add
one to the beginning of each line. If there is one, remove a #
from each line that has one. In either case, accept the current
line. The INTERACTIVECOMENTS option must be set for this to
have any usefulness.
vi-pound-insert
If there is no # character at the beginning of the current line,
add one. If there is one, remove it. The INTERACTIVECOMENTS
option must be set for this to have any usefulness.
push-input
Push the entire current multiline construct onto the buffer
stack and return to the top-level (PS1) prompt. If the current
parser construct is only a single line, this is exactly like
push-line. Next time the editor starts up or is popped with
get-line, the construct will be popped off the top of the buffer
stack and loaded into the editing buffer.
push-line (^Q ESC-Q ESC-q) (unbound) (unbound)
Push the current buffer onto the buffer stack and clear the
buffer. Next time the editor starts up, the buffer will be
popped off the top of the buffer stack and loaded into the edit-
ing buffer.
push-line-or-edit
At the top-level (PS1) prompt, equivalent to push-line. At a
secondary (PS2) prompt, move the entire current multiline con-
struct into the editor buffer. The latter is equivalent to
push-input followed by get-line.
recursive-edit
Only useful from a user-defined widget. At this point in the
function, the editor regains control until one of the standard
widgets which would normally cause zle to exit (typically an
accept-line caused by hitting the return key) is executed.
Instead, control returns to the user-defined widget. The status
returned is non-zero if the return was caused by an error, but
the function still continues executing and hence may tidy up.
This makes it safe for the user-defined widget to alter the com-
mand line or key bindings temporarily.
The following widget, caps-lock, serves as an example.
self-insert-ucase() {{
LBUFER]==$${{(U)KEYS[-1]}}
}}
integer stat
zle -N self-insert self-insert-ucase
zle -A caps-lock save-caps-lock
zle -A accept-line caps-lock
zle recursive-edit
stat=$?
zle -A .self-insert self-insert
zle -A save-caps-lock caps-lock
zle -D save-caps-lock
(( stat )) && zle send-break
return $stat
This causes typed letters to be inserted capitalised until
either accept-line (i.e. typically the return key) is typed or
the caps-lock widget is invoked again; the later is handled by
saving the old definition of caps-lock as save-caps-lock and
then rebinding it to invoke accept-line. Note that an error
from the recursive edit is detected as a non-zero return status
and propagated by using the send-break widget.
redisplay (unbound) (^R) (^R)
Redisplays the edit buffer.
reset-prompt (unbound) (unbound) (unbound)
Force the prompts on both the left and right of the screen to be
re-expanded, then redisplay the edit buffer. This reflects
changes both to the prompt variables themselves and changes in
the expansion of the values (for example, changes in time or
directory, or changes to the value of variables referred to by
the prompt).
Otherwise, the prompt is only expanded each time zle starts, and
when the display as been interrupted by output from another part
of the shell (such as a job notification) which causes the com-
mand line to be reprinted.
send-break (^G ESC-^G) (unbound) (unbound)
Abort the current editor function, e.g. execute-named-command,
or the editor itself, e.g. if you are in vared. Otherwise abort
the parsing of the current line.
run-help (ESC-H ESC-h) (unbound) (unbound)
Push the buffer onto the buffer stack, and execute the command
`run-help cmd', where cmd is the current command. run-help is
normally aliased to man.
vi-set-buffer (unbound) (") (unbound)
Specify a buffer to be used in the following command. There are
35 buffers that can be specified: the 26 `named' buffers ""a to
""z and the nine `queued' buffers ""1 to ""9. The named buffers
can also be specified as ""A to ""Z.
When a buffer is specified for a cut command, the text being cut
replaces the previous contents of the specified buffer. If a
named buffer is specified using a capital, the newly cut text is
appended to the buffer instead of overwriting it.
If no buffer is specified for a cut command, ""1 is used, and the
contents of ""1 to ""8 are each shifted along one buffer; the con-
tents of ""9 is lost.
vi-set-mark (unbound) (m) (unbound)
Set the specified mark at the cursor position.
set-mark-command (^@) (unbound) (unbound)
Set the mark at the cursor position.
spell-word (ESC-$ ESC-S ESC-s) (unbound) (unbound)
Attempt spelling correction on the current word.
undefined-key
This command is executed when a key sequence that is not bound
to any command is typed. By default it beeps.
undo (^ ^Xu ^X^U) (unbound) (unbound)
Incrementally undo the last text modification.
redo Incrementally redo undone text modifications.
vi-undo-change (unbound) (u) (unbound)
Undo the last text modification. If repeated, redo the modifi-
cation.
what-cursor-position (^X=) (unbound) (unbound)
Print the character under the cursor, its code as an octal, dec-
imal and hexadecimal number, the current cursor position within
the buffer and the column of the cursor in the current line.
where-is
Read the name of an editor command and and print the listing of
key sequences that invoke the specified command.
which-command (ESC-?) (unbound) (unbound)
Push the buffer onto the buffer stack, and execute the command
`which-command cmd'. where cmd is the current command.
which-command is normally aliased to whence.
vi-digit-or-beginning-of-line (unbound) (0) (unbound)
If the last command executed was a digit as part of an argument,
continue the argument. Otherwise, execute vi-beginning-of-line.
ZSHCOMPWID(1) ZSHCOMPWID(1)
NAME
zshcompwid - zsh completion widgets
DESCRIPTION
The shell's programmable completion mechanism can be manipulated in two
ways; here the low-level features supporting the newer, function-based
mechanism are defined. A complete set of shell functions based on
these features is described in zshcompsys(1), and users with no inter-
est in adding to that system (or, potentially, writing their own ---
see dictionary entry for `hubris') should skip this section. The older
system based on the compctl builtin command is described in zshcom-
pctl(1).
Completion widgets are defined by the -C option to the zle builtin com-
mand provided by the zsh/zle module (see zshzle(1)). For example,
zle -C complete expand-or-complete completer
defines a widget named `complete'. The second argument is the name of
any of the builtin widgets that handle completions: complete-word,
expand-or-complete, expand-or-complete-prefix, menu-complete,
menu-expand-or-complete, reverse-menu-complete, list-choices, or
delete-char-or-list. Note that this will still work even if the widget
in question has been re-bound.
When this newly defined widget is bound to a key using the bindkey
builtin command defined in the zsh/zle module (see zshzle(1)), typing
that key will call the shell function `completer'. This function is
responsible for generating the possible matches using the builtins
described below. As with other ZLE widgets, the function is called
with its standard input closed.
Once the function returns, the completion code takes over control again
and treats the matches in the same manner as the specified builtin wid-
get, in this case expand-or-complete.
SPECIAL PARAMETERS
Inside completion widgets, and any functions called from them, some
parameters have special meaning; outside these functions they are not
special to the shell in any way. These parameters are used to pass
information between the completion code and the completion widget. Some
of the builtin commands and the condition codes use or change the cur-
rent values of these parameters. Any existing values will be hidden
during execution of completion widgets; except for compstate, the
parameters are reset on each function exit (including nested function
calls from within the completion widget) to the values they had when
the function was entered.
CURENT
This is the number of the current word, i.e. the word the cursor
is currently on in the words array. Note that this value is
only correct if the ksharrays option is not set.
IPREFIX
Initially this will be set to the empty string. This parameter
functions like PREFIX; it contains a string which precedes the
one in PREFIX and is not considered part of the list of matches.
Typically, a string is transferred from the beginning of PREFIX
to the end of IPREFIX, for example:
IPREFIX==$${{PREFIX%%%%\\==**}}==
PREFIX==$${{PREFIX##**==}}
causes the part of the prefix up to and including the first
equal sign not to be treated as part of a matched string. This
can be done automatically by the compset builtin, see below.
ISUFIX
As IPREFIX, but for a suffix that should not be considered part
of the matches; note that the ISUFIX string follows the SUFIX
string.
PREFIX Initially this will be set to the part of the current word from
the beginning of the word up to the position of the cursor; it
may be altered to give a common prefix for all matches.
QIPREFIX
This parameter is read-only and contains the quoted string up to
the word being completed. E.g. when completing `""foo', this
parameter contains the double quote. If the -q option of compset
is used (see below), and the original string was `""foo bar' with
the cursor on the `bar', this parameter contains `""foo '.
QISUFIX
Like QIPREFIX, but containing the suffix.
SUFIX Initially this will be set to the part of the current word from
the cursor position to the end; it may be altered to give a com-
mon suffix for all matches. It is most useful when the option
COMPLETEINWORD is set, as otherwise the whole word on the com-
mand line is treated as a prefix.
compstate
This is an associative array with various keys and values that
the completion code uses to exchange information with the com-
pletion widget. The keys are:
allquotes
The -q option of the compset builtin command (see below)
allows a quoted string to be broken into separate words;
if the cursor is on one of those words, that word will be
completed, possibly invoking `compset -q' recursively.
With this key it is possible to test the types of quoted
strings which are currently broken into parts in this
fashion. Its value contains one character for each quot-
ing level. The characters are a single quote or a double
quote for strings quoted with these characters and a
backslash for strings not starting with a quote charac-
ter. The first character in the value always corresponds
to the innermost quoting level.
context
This will be set by the completion code to the overall
context in which completion is attempted. Possible values
are:
arrayvalue
when completing inside the value of an array
parameter assignment; in this case the words array
contains the words inside the parentheses.
braceparameter
when completing the name of a parameter in a
parameter expansion beginning with $${{.
assignparameter
when completing the name of a parameter in a
parameter assignment.
command
when completing for a normal command (either in
command position or for an argument of the com-
mand).
condition
when completing inside a `[...]' conditional
expression; in this case the words array contains
only the words inside the conditional expression.
math when completing in a mathematical environment such
as a `((...))' construct.
parameter
when completing the name of a parameter in a
parameter expansion beginning with $$ but not $${{.
redirect
when completing after a redirection operator.
subscript
when completing inside a parameter subscript.
value when completing the value of a parameter assign-
ment.
exact Controls the behaviour when the RECEXACT option is set.
It will be set to accept if an exact match would be
accepted, and will be unset otherwise.
If it was set when at least one match equal to the string
on the line was generated, the match is accepted.
exactstring
The string of an exact match if one was found, otherwise
unset.
ignored
The number of words that were ignored because they
matched one of the patterns given with the -F option to
the compadd builtin command.
insert This controls the manner in which a match is inserted
into the command line. On entry to the widget function,
if it is unset the command line is not to be changed; if
set to unambiguous, any prefix common to all matches is
to be inserted; if set to automenu-unambiguous, the com-
mon prefix is to be inserted and the next invocation of
the completion code may start menu completion (due to the
AUTOMENU option being set); if set to menu or automenu
menu completion will be started for the matches currently
generated (in the latter case this will happen because
the AUTOMENU is set). The value may also contain the
string `tab' when the completion code would normally not
really do completion, but only insert the TAB character.
On exit it may be set to any of the values above (where
setting it to the empty string is the same as unsetting
it), or to a number, in which case the match whose number
is given will be inserted into the command line. Nega-
tive numbers count backward from the last match (with
`-1' selecting the last match) and out-of-range values
are wrapped around, so that a value of zero selects the
last match and a value one more than the maximum selects
the first. Unless the value of this key ends in a space,
the match is inserted as in a menu completion, i.e. with-
out automatically appending a space.
Both menu and automenu may also specify the the number of
the match to insert, given after a colon. For example,
`menu::2' says to start menu completion, beginning with
the second match.
Note that a value containing the substring `tab' makes
the matches generated be ignored and only the TAB be
inserted.
Finally, it may also be set to all, which makes all
matches generated be inserted into the line.
insertpositions
When the completion system inserts an unambiguous string
into the line, there may be multiple places where charac-
ters are missing or where the character inserted differs
from at least one match. The value of this key contains
a colon separated list of all these positions, as indexes
into the command line.
lastprompt
If this is set to a non-empty string for every match
added, the completion code will move the cursor back to
the previous prompt after the list of completions has
been displayed. Initially this is set or unset according
to the ALWAYSLASTPROMPT option.
list This controls whether or how the list of matches will be
displayed. If it is unset or empty they will never be
listed; if its value begins with list, they will always
be listed; if it begins with autolist or ambiguous, they
will be listed when the AUTOLIST or LISTAMBIGUOUS
options respectively would normally cause them to be.
If the substring force appears in the value, this makes
the list be shown even if there is only one match. Nor-
mally, the list would be shown only if there are at least
two matches.
The value contains the substring packed if the
LISTPACKED option is set. If this substring is given for
all matches added to a group, this group will show the
LISTPACKED behavior. The same is done for the
LISTROWSFIRST option with the substring rows.
Finally, if the value contains the string explanations,
only the explanation strings, if any, will be listed and
if it contains messages, only the messages (added with
the -x option of compadd) will be listed. If it contains
both explanations and messages both kinds of explanation
strings will be listed. It will be set appropriately on
entry to a completion widget and may be changed there.
listlines
This gives the number of lines that are needed to display
the full list of completions. Note that to calculate the
total number of lines to display you need to add the num-
ber of lines needed for the command line to this value,
this is available as the value of the BUFERLINES special
parameter.
listmax
Initially this is set to the value of the LISTMAX parame-
ter. It may be set to any other value; when the widget
exits this value will be used in the same way as the
value of LISTMAX.
nmatches
The number of matches generated and accepted by the com-
pletion code so far.
oldinsert
On entry to the widget this will be set to the number of
the match of an old list of completions that is currently
inserted into the command line. If no match has been
inserted, this is unset.
As with oldlist, the value of this key will only be used
if it is the string keep. If it was set to this value by
the widget and there was an old match inserted into the
command line, this match will be kept and if the value of
the insert key specifies that another match should be
inserted, this will be inserted after the old one.
oldlist
This is set to yes if there is still a valid list of com-
pletions from a previous completion at the time the wid-
get is invoked. This will usually be the case if and
only if the previous editing operation was a completion
widget or one of the builtin completion functions. If
there is a valid list and it is also currently shown on
the screen, the value of this key is shown.
After the widget has exited the value of this key is only
used if it was set to keep. In this case the completion
code will continue to use this old list. If the widget
generated new matches, they will not be used.
parameter
The name of the parameter when completing in a subscript
or in the value of a parameter assignment.
patterninsert
Normally this is set to menu, which specifies that menu
completion will be used whenever a set of matches was
generated using pattern matching. If it is set to any
other non-empty string by the user and menu completion is
not selected by other option settings, the code will
instead insert any common prefix for the generated
matches as with normal completion.
patternmatch
Locally controls the behaviour given by the GLOBCOMPLETE
option. Initially it is set to `**' if and only if the
option is set. The completion widget may set it to this
value, to an empty string (which has the same effect as
unsetting it), or to any other non-empty string. If it
is non-empty, unquoted metacharacters on the command line
will be treated as patterns; if it is `**', then addition-
ally a wildcard `**' is assumed at the cursor position; if
it is empty or unset, metacharacters will be treated lit-
erally.
Note that the matcher specifications given to the compadd
builtin command are not used if this is set to a
non-empty string.
quote When completing inside quotes, this contains the quota-
tion character (i.e. either a single quote, a double
quote, or a backtick). Otherwise it is unset.
quoting
When completing inside single quotes, this is set to the
string single; inside double quotes, the string double;
inside backticks, the string backtick. Otherwise it is
unset.
redirect
The redirection operator when completing in a redirection
position, i.e. one of <<, >>, etc.
restore
This is set to auto before a function is entered, which
forces the special parameters mentioned above (words,
CURENT, PREFIX, IPREFIX, SUFIX, and ISUFIX) to be
restored to their previous values when the function
exits. If a function unsets it or sets it to any other
string, they will not be restored.
toend Specifies the occasions on which the cursor is moved to
the end of a string when a match is inserted. On entry
to a widget function, it may be single if this will hap-
pen when a single unambiguous match was inserted or match
if it will happen any time a match is inserted (for exam-
ple, by menu completion; this is likely to be the effect
of the ALWAYSTOEND option).
On exit, it may be set to single as above. It may also
be set to always, or to the empty string or unset; in
those cases the cursor will be moved to the end of the
string always or never respectively. Any other string is
treated as match.
unambiguous
This key is read-only and will always be set to the com-
mon (unambiguous) prefix the completion code has gener-
ated for all matches added so far.
unambiguouscursor
This gives the position the cursor would be placed at if
the common prefix in the unambiguous key were inserted,
relative to the value of that key. The cursor would be
placed before the character whose index is given by this
key.
unambiguouspositions
This contains all positions where characters in the unam-
biguous string are missing or where the character
inserted differs from at least one of the matches. The
positions are given as indexes into the string given by
the value of the unambiguous key.
vared If completion is called while editing a line using the
vared builtin, the value of this key is set to the name
of the parameter given as an argument to vared. This key
is only set while a vared command is active.
words This array contains the words present on the command line cur-
rently being edited.
BUILTIN COMANDS
compadd [ -akqQfenUl12C ] [ -F array ]
[ -P prefix ] [ -S suffix ]
[ -p hidden-prefix ] [ -s hidden-suffix ]
[ -i ignored-prefix ] [ -I ignored-suffix ]
[ -W file-prefix ] [ -d array ]
[ -J name ] [ -V name ] [ -X explanation ] [ -x message ]
[ -r remove-chars ] [ -R remove-func ]
[ -D array ] [ -O array ] [ -A array ]
[ -E number ]
[ -M match-spec ] [ -- ] [ words ... ]
This builtin command can be used to add matches directly and
control all the information the completion code stores with each
possible match. The return value is zero if at least one match
was added and non-zero if no matches were added.
The completion code breaks the string to complete into seven
fields in the order:
The first field is an ignored prefix taken from the command
line, the contents of the IPREFIX parameter plus the string
given with the -i option. With the -U option, only the string
from the -i option is used. The field is an optional pre-
fix string given with the -P option. The field is a
string that is considered part of the match but that should not
be shown when listing completions, given with the -p option; for
example, functions that do filename generation might specify a
common path prefix this way. is the part of the match
that should appear in the list of completions, i.e. one of the
words given at the end of the compadd command line. The suffixes
, and correspond to the prefixes ,
and and are given by the options -s, -S and -I,
respectively.
The supported flags are:
-P prefix
This gives a string to be inserted before the given
words. The string given is not considered as part of the
match and any shell metacharacters in it will not be
quoted when the string is inserted.
-S suffix
Like -P, but gives a string to be inserted after the
match.
-p hidden-prefix
This gives a string that should be inserted into the com-
mand line before the match but that should not appear in
the list of matches. Unless the -U option is given, this
string must be matched as part of the string on the com-
mand line.
-s hidden-suffix
Like `-p', but gives a string to insert after the match.
-i ignored-prefix
This gives a string to insert into the command line just
before any string given with the `-P' option. Without
`-P' the string is inserted before the string given with
`-p' or directly before the match.
-I ignored-suffix
Like -i, but gives an ignored suffix.
-a With this flag the words are taken as names of arrays and
the possible matches are their values. If only some ele-
ments of the arrays are needed, the words may also con-
tain subscripts, as in `foo[2,,-1]'.
-k With this flag the words are taken as names of associa-
tive arrays and the possible matches are their keys. As
for -a, the words may also contain subscripts, as in
`foo[(R)**bar**]'.
-d array
This adds per-match display strings. The array should
contain one element per word given. The completion code
will then display the first element instead of the first
word, and so on. The array may be given as the name of an
array parameter or directly as a space-separated list of
words in parentheses.
If there are fewer display strings than words, the left-
over words will be displayed unchanged and if there are
more display strings than words, the leftover display
strings will be silently ignored.
-l This option only has an effect if used together with the
-d option. If it is given, the display strings are listed
one per line, not arrayed in columns.
-J name
Gives the name of the group of matches the words should
be stored in.
-V name
Like -J but naming a unsorted group. These are in a dif-
ferent name space than groups created with the -J flag.
-1 If given together with the -V option, makes only consecu-
tive duplicates in the group be removed. If combined with
the -J option, this has no visible effect. Note that
groups with and without this flag are in different name
spaces.
-2 If given together with the -J or -V option, makes all
duplicates be kept. Again, groups with and without this
flag are in different name spaces.
-X explanation
The explanation string will be printed with the list of
matches, above the group currently selected.
-x message
Like -X, but the message will be printed even if there
are no matches in the group.
-q The suffix given with -S will be automatically removed if
the next character typed is a blank or does not insert
anything, or if the suffix consists of only one character
and the next character typed is the same character.
-r remove-chars
This is a more versatile form of the -q option. The suf-
fix given with -S or the slash automatically added after
completing directories will be automatically removed if
the next character typed inserts one of the characters
given in the remove-chars. This string is parsed as a
characters class and understands the backslash sequences
used by the print command. For example, `-r ""a-z\\t""'
removes the suffix if the next character typed inserts a
lowercase character or a TAB, and `-r ""^^00-9""' removes the
suffix if the next character typed inserts anything but a
digit. One extra backslash sequence is understood in this
string: `\\-' stands for all characters that insert noth-
ing. Thus `-S ""=="" -q' is the same as `-S ""=="" -r ""==
\\t\\n\\-""'.
This option may also be used without the -S option; then
any automatically added space will be removed when one of
the characters in the list is typed.
-R remove-func
This is another form of the -r option. When a suffix has
been inserted and the completion accepted, the function
remove-func will be called after the next character
typed. It is passed the length of the suffix as an argu-
ment and can use the special parameters available in
ordinary (non-completion) zle widgets (see zshzle(1)) to
analyse and modify the command line.
-f If this flag is given, all of the matches built from
words are marked as being the names of files. They are
not required to be actual filenames, but if they are, and
the option LISTYPES is set, the characters describing
the types of the files in the completion lists will be
shown. This also forces a slash to be added when the name
of a directory is completed.
-e This flag can be used to tell the completion code that
the matches added are parameter names for a parameter
expansion. This will make the AUTOPARAMSLASH and
AUTOPARAMKEYS options be used for the matches.
-W file-prefix
This string is a pathname that will be prepended to each
of the matches formed by the given words together with
any prefix specified by the -p option to form a complete
filename for testing. Hence it is only useful if com-
bined with the -f flag, as the tests will not otherwise
be performed.
-F array
Specifies an array containing patterns. Words matching
one of these patterns are ignored, i.e. not considered to
be possible matches.
The array may be the name of an array parameter or a list
of literal patterns enclosed in parentheses and quoted,
as in `-F ""(**??.o **??.h)""'. If the name of an array is
given, the elements of the array are taken as the pat-
terns.
-Q This flag instructs the completion code not to quote any
metacharacters in the words when inserting them into the
command line.
-M match-spec
This gives local match specifications as described below
in the section `Matching Control'. This option may be
given more than once. In this case all match-specs given
are concatenated with spaces between them to form the
specification string to use. Note that they will only be
used if the -U option is not given.
-n Specifies that the words added are to be used as possible
matches, but are not to appear in the completion listing.
-U If this flag is given, all words given will be accepted
and no matching will be done by the completion code. Nor-
mally this is used in functions that do the matching
themselves.
-O array
If this option is given, the words are not added to the
set of possible completions. Instead, matching is done
as usual and all of the words given as arguments that
match the string on the command line will be stored in
the array parameter whose name is given as array.
-A array
As the -O option, except that instead of those of the
words which match being stored in array, the strings gen-
erated internally by the completion code are stored. For
example, with a matching specification of `-M ""L::no==""',
the string `nof' on the command line and the string `foo'
as one of the words, this option stores the string
`nofoo' in the array, whereas the -O option stores the
`foo' originally given.
-D array
As with -O, the words are not added to the set of possi-
ble completions. Instead, the completion code tests
whether each word in turn matches what is on the line.
If the n'th word does not match, the n'th element of the
array is removed. Elements for which the corresponding
word is matched are retained.
-C This option adds a special match which expands to all
other matches when inserted into the line, even those
that are added after this option is used. Together with
the -d option it is possible to specify a string that
should be displayed in the list for this special match.
If no string is given, it will be shown as a string con-
taining the strings that would be inserted for the other
matches, truncated to the width of the screen.
-E This option adds number empty matches after the words
have been added. An empty match takes up space in com-
pletion listings but will never be inserted in the line
and can't be selected with menu completion or menu selec-
tion. This makes empty matches only useful to format
completion lists and to make explanatory string be shown
in completion lists (since empty matches can be given
display strings with the -d option). And because all but
one empty string would otherwise be removed, this option
implies the -V and -2 options (even if an explicit -J
option is given).
-
-- This flag ends the list of flags and options. All argu-
ments after it will be taken as the words to use as
matches even if they begin with hyphens.
Except for the -M flag, if any of these flags is given more than
once, the first one (and its argument) will be used.
compset -p number
compset -P [ number ] pattern
compset -s number
compset -S [ number ] pattern
compset -n begin [ end ]
compset -N beg-pat [ end-pat ]
compset -q
This command simplifies modification of the special parameters,
while its return value allows tests on them to be carried out.
The options are:
-p number
If the contents of the PREFIX parameter is longer than
number characters, the first number characters are
removed from it and appended to the contents of the
IPREFIX parameter.
-P [ number ] pattern
If the value of the PREFIX parameter begins with anything
that matches the pattern, the matched portion is removed
from PREFIX and appended to IPREFIX.
Without the optional number, the longest match is taken,
but if number is given, anything up to the number'th
match is moved. If the number is negative, the number'th
longest match is moved. For example, if PREFIX contains
the string `a==b==c', then compset -P ''**\\=='' will move the
string `a==b==' into the IPREFIX parameter, but compset -P
1 ''**\\=='' will move only the string `a=='.
-s number
As -p, but transfer the last number characters from the
value of SUFIX to the front of the value of ISUFIX.
-S [ number ] pattern
As -P, but match the last portion of SUFIX and transfer
the matched portion to the front of the value of ISUFIX.
-n begin [ end ]
If the current word position as specified by the parame-
ter CURENT is greater than or equal to begin, anything
up to the begin'th word is removed from the words array
and the value of the parameter CURENT is decremented by
begin.
If the optional end is given, the modification is done
only if the current word position is also less than or
equal to end. In this case, the words from position end
onwards are also removed from the words array.
Both begin and end may be negative to count backwards
from the last element of the words array.
-N beg-pat [ end-pat ]
If one of the elements of the words array before the one
at the index given by the value of the parameter CURENT
matches the pattern beg-pat, all elements up to and
including the matching one are removed from the words
array and the value of CURENT is changed to point to the
same word in the changed array.
If the optional pattern end-pat is also given, and there
is an element in the words array matching this pattern,
the parameters are modified only if the index of this
word is higher than the one given by the CURENT parame-
ter (so that the matching word has to be after the cur-
sor). In this case, the words starting with the one
matching end-pat are also removed from the words array.
If words contains no word matching end-pat, the testing
and modification is performed as if it were not given.
-q The word currently being completed is split on spaces
into separate words, respecting the usual shell quoting
conventions. The resulting words are stored in the words
array, and CURENT, PREFIX, SUFIX, QIPREFIX, and QISUF-
FIX are modified to reflect the word part that is com-
pleted.
In all the above cases the return value is zero if the test suc-
ceeded and the parameters were modified and non-zero otherwise.
This allows one to use this builtin in tests such as:
if compset -P ''**\\=='';; then ...
This forces anything up to and including the last equal sign to
be ignored by the completion code.
compcall [ -TD ]
This allows the use of completions defined with the compctl
builtin from within completion widgets. The list of matches
will be generated as if one of the non-widget completion func-
tion (complete-word, etc.) had been called, except that only
compctls given for specific commands are used. To force the code
to try completions defined with the -T option of compctl and/or
the default completion (whether defined by compctl -D or the
builtin default) in the appropriate places, the -T and/or -D
flags can be passed to compcall.
The return value can be used to test if a matching compctl defi-
nition was found. It is non-zero if a compctl was found and zero
otherwise.
Note that this builtin is defined by the zsh/compctl module.
CONDITION CODES
The following additional condition codes for use within the [ ... ]
construct are available in completion widgets. These work on the spe-
cial parameters. All of these tests can also be performed by the
compset builtin, but in the case of the condition codes the contents of
the special parameters are not modified.
-prefix [ number ] pattern
true if the test for the -P option of compset would succeed.
-suffix [ number ] pattern
true if the test for the -S option of compset would succeed.
-after beg-pat
true if the test of the -N option with only the beg-pat given
would succeed.
-between beg-pat end-pat
true if the test for the -N option with both patterns would suc-
ceed.
MATCHING CONTROL
It is possible by use of the -M option of the compadd builtin command
to specify how the characters in the string to be completed (referred
to here as the command line) map onto the characters in the list of
matches produced by the completion code (referred to here as the trial
completions). Note that this is not used if the command line contains a
glob pattern and the GLOBCOMPLETE option is set or the patternmatch
of the compstate special association is set to a non-empty string.
The match-spec given as the argument to the -M option (see `Builtin
Commands' above) consists of one or more matching descriptions sepa-
rated by whitespace. Each description consists of a letter followed by
a colon and then the patterns describing which character sequences on
the line match which character sequences in the trial completion. Any
sequence of characters not handled in this fashion must match exactly,
as usual.
The forms of match-spec understood are as follows. In each case, the
form with an uppercase initial character retains the string already
typed on the command line as the final result of completion, while with
a lowercase initial character the string on the command line is changed
into the corresponding part of the trial completion.
m::lpat==tpat
M::lpat==tpat
Here, lpat is a pattern that matches on the command line, corre-
sponding to tpat which matches in the trial completion.
l::lanchorlpat==tpat
L::lanchorlpat==tpat
l::lanchorranchor==tpat
L::lanchorranchor==tpat
b::lpat==tpat
B::lpat==tpat
These letters are for patterns that are anchored by another pat-
tern on the left side. Matching for lpat and tpat is as for m
and M, but the pattern lpat matched on the command line must be
preceded by the pattern lanchor. The lanchor can be blank to
anchor the match to the start of the command line string; other-
wise the anchor can occur anywhere, but must match in both the
command line and trial completion strings.
If no lpat is given but a ranchor is, this matches the gap
between substrings matched by lanchor and ranchor. Unlike lan-
chor, the ranchor only needs to match the trial completion
string.
The b and B forms are similar to l and L with an empty anchor,
but need to match only the beginning of the trial completion or
the word on the command line, respectively.
r::lpatranchor==tpat
R::lpatranchor==tpat
r::lanchorranchor==tpat
R::lanchorranchor==tpat
e::lpat==tpat
E::lpat==tpat
As l, L, b and B, with the difference that the command line and
trial completion patterns are anchored on the right side. Here
an empty ranchor and the e and E forms force the match to the
end of the trial completion or command line string.
Each lpat, tpat or anchor is either an empty string or consists of a
sequence of literal characters (which may be quoted with a backslash),
question marks, character classes, and correspondence classes; ordinary
shell patterns are not used. Literal characters match only themselves,
question marks match any character, and character classes are formed as
for globbing and match any character in the given set.
Correspondence classes are defined like character classes, but with two
differences: they are delimited by a pair of braces, and negated
classes are not allowed, so the characters !! and ^^ have no special
meaning directly after the opening brace. They indicate that a range
of characters on the line match a range of characters in the trial com-
pletion, but (unlike ordinary character classes) paired according to
the corresponding position in the sequence. For example, to make any
lowercase letter on the line match the corresponding uppercase letter
in the trial completion, you can use `m::{{a-z}}=={{A-Z}}'. More than one
pair of classes can occur, in which case the first class before the ==
corresponds to the first after it, and so on. If one side has more
such classes than the other side, the superfluous classes behave like
normal character classes. In anchor patterns correspondence classes
also behave like normal character classes.
The pattern tpat may also be one or two stars, `**' or `****'. This means
that the pattern on the command line can match any number of characters
in the trial completion. In this case the pattern must be anchored (on
either side); in the case of a single star, the anchor then determines
how much of the trial completion is to be included --- only the charac-
ters up to the next appearance of the anchor will be matched. With two
stars, substrings matched by the anchor can be matched, too.
Examples:
The keys of the options association defined by the parameter module are
the option names in all-lowercase form, without underscores, and with-
out the optional no at the beginning even though the builtins setopt
and unsetopt understand option names with uppercase letters, under-
scores, and the optional no. The following alters the matching rules
so that the prefix no and any underscore are ignored when trying to
match the trial completions generated and uppercase letters on the line
match the corresponding lowercase letters in the words:
compadd -M ''L::[nN][oO]== M::== M::{{A-Z}}=={{a-z}}'' - \\
$${{(k)options}}
The first part says that the pattern `[nN][oO]' at the beginning (the
empty anchor before the pipe symbol) of the string on the line matches
the empty string in the list of words generated by completion, so it
will be ignored if present. The second part does the same for an under-
score anywhere in the command line string, and the third part uses cor-
respondence classes so that any uppercase letter on the line matches
the corresponding lowercase letter in the word. The use of the upper-
case forms of the specification characters (L and M) guarantees that
what has already been typed on the command line (in particular the pre-
fix no) will not be deleted.
Note that the use of L in the first part means that it matches only
when at the beginning of both the command line string and the trial
completion. I.e., the string `NOf' would not be completed to
`NOfoo', nor would `NONOf' be completed to `NONOfoo' because of the
leading underscore or the second `NO' on the line which makes the pat-
tern fail even though they are otherwise ignored. To fix this, one
would use `B::[nN][oO]==' instead of the first part. As described above,
this matches at the beginning of the trial completion, independent of
other characters or substrings at the beginning of the command line
word which are ignored by the same or other match-specs.
The second example makes completion case insensitive. This is just the
same as in the option example, except here we wish to retain the char-
acters in the list of completions:
compadd -M ''m::{{a-z}}=={{A-Z}}'' ...
This makes lowercase letters match their uppercase counterparts. To
make uppercase letters match the lowercase forms as well:
compadd -M ''m::{{a-zA-Z}}=={{A-Za-z}}'' ...
A nice example for the use of ** patterns is partial word completion.
Sometimes you would like to make strings like `c.s.u' complete to
strings like `comp.source.unix', i.e. the word on the command line con-
sists of multiple parts, separated by a dot in this example, where each
part should be completed separately --- note, however, that the case
where each part of the word, i.e. `comp', `source' and `unix' in this
example, is to be completed from separate sets of matches is a differ-
ent problem to be solved by the implementation of the completion wid-
get. The example can be handled by:
compadd -M ''r::.==** r::==**'' \\
- comp.sources.unix comp.sources.misc ...
The first specification says that lpat is the empty string, while
anchor is a dot; tpat is **, so this can match anything except for the
`.' from the anchor in the trial completion word. So in `c.s.u', the
matcher sees `c', followed by the empty string, followed by the anchor
`.', and likewise for the second dot, and replaces the empty strings
before the anchors, giving `c[omp].s[ources].u[nix]', where the last
part of the completion is just as normal.
With the pattern shown above, the string `c.u' could not be completed
to `comp.sources.unix' because the single star means that no dot
(matched by the anchor) can be skipped. By using two stars as in
`r::.==****', however, `c.u' could be completed to `comp.sources.unix'.
This also shows that in some cases, especially if the anchor is a real
pattern, like a character class, the form with two stars may result in
more matches than one would like.
The second specification is needed to make this work when the cursor is
in the middle of the string on the command line and the option CO-
PLETEINWORD is set. In this case the completion code would normally
try to match trial completions that end with the string as typed so
far, i.e. it will only insert new characters at the cursor position
rather then at the end. However in our example we would like the code
to recognise matches which contain extra characters after the string on
the line (the `nix' in the example). Hence we say that the empty
string at the end of the string on the line matches any characters at
the end of the trial completion.
More generally, the specification
compadd -M ''r::[.,,-]==** r::==**'' ...
allows one to complete words with abbreviations before any of the char-
acters in the square brackets. For example, to complete veryverylong-
file.c rather than veryverylongheader.h with the above in effect, you
can just type very.c before attempting completion.
The specifications with both a left and a right anchor are useful to
complete partial words whose parts are not separated by some special
character. For example, in some places strings have to be completed
that are formed `LikeThis' (i.e. the separate parts are determined by a
leading uppercase letter) or maybe one has to complete strings with
trailing numbers. Here one could use the simple form with only one
anchor as in:
compadd -M ''r::[A-Z00-9]==** r::==**'' LikeTHIS FooHoo 5foo123 5bar234
But with this, the string `H' would neither complete to `FooHoo' nor to
`LikeTHIS' because in each case there is an uppercase letter before the
`H' and that is matched by the anchor. Likewise, a `2' would not be
completed. In both cases this could be changed by using
`r::[A-Z00-9]==****', but then `H' completes to both `LikeTHIS' and
`FooHoo' and a `2' matches the other strings because characters can be
inserted before every uppercase letter and digit. To avoid this one
would use:
compadd -M ''r::[^^A-Z00-9][A-Z00-9]==**** r::==**'' \\
LikeTHIS FooHoo foo123 bar234
By using these two anchors, a `H' matches only uppercase `H's that are
immediately preceded by something matching the left anchor `[^^A-Z00-9]'.
The effect is, of course, that `H' matches only the string `FooHoo', a
`2' matches only `bar234' and so on.
When using the completion system (see zshcompsys(1)), users can define
match specifications that are to be used for specific contexts by using
the matcher and matcher-list styles. The values for the latter will be
used everywhere.
COMPLETION WIDGET EXAMPLE
The first step is to define the widget:
zle -C complete complete-word complete-files
Then the widget can be bound to a key using the bindkey builtin com-
mand:
bindkey ''^^X\\t'' complete
After that the shell function complete-files will be invoked after typ-
ing control-X and TAB. The function should then generate the matches,
e.g.:
complete-files () {{ compadd - ** }}
This function will complete files in the current directory matching the
current word.
ZSHCOMPSYS(1) ZSHCOMPSYS(1)
NAME
zshcompsys - zsh completion system
DESCRIPTION
This describes the shell code for the new completion system. It con-
sists of various shell functions; those beginning `comp' are to be
called directly, while those beginning `' are called by the completion
code. The shell functions of the second set, which implement comple-
tion behaviour and may be bound to keystrokes, are referred to as `wid-
gets'.
INITIALIZATION
If the system was installed completely, it should be enough to call the
shell function compinit from your initialization file; see the next
section. However, the function compinstall can be run by a user to
configure various aspects of the completion system.
Usually, compinstall will insert code into .zshrc, although if that is
not writable it will save it in another file and tell you that file's
location. Note that it is up to you to make sure that the lines added
to .zshrc are actually run; you may, for example, need to move them to
an earlier place in the file if .zshrc usually returns early. So long
as you keep them all together (including the comment lines at the start
and finish), you can rerun compinstall and it will correctly locate and
modify these lines. Note, however, that any code you add to this sec-
tion by hand is likely to be lost if you rerun compinstall, although
lines using the command `zstyle' should be gracefully handled.
The new code will take effect next time you start the shell, or run
.zshrc by hand; there is also an option to make them take effect imme-
diately. However, if compinstall has removed definitions, you will
need to restart the shell to see the changes.
To run compinstall you will need to make sure it is in a directory men-
tioned in your fpath parameter, which should already be the case if zsh
was properly configured as long as your startup files do not remove the
appropriate directories from fpath. Then it must be autoloaded
(`autoload -U compinstall' is recommended). You can abort the instal-
lation any time you are being prompted for information, and your .zshrc
will not be altered at all; changes only take place right at the end,
where you are specifically asked for confirmation.
Use of compinit
This section describes the use of compinit to initialize completion for
the current session when called directly; if you have run compinstall
it will be called automatically from your .zshrc.
To initialize the system, the function compinit should be in a direc-
tory mentioned in the fpath parameter, and should be autoloaded
(`autoload -U compinit' is recommended), and then run simply as
`compinit'. This will define a few utility functions, arrange for all
the necessary shell functions to be autoloaded, and will then re-define
all widgets that do completion to use the new system. If you use the
menu-select widget, which is part of the zsh/complist module, you
should make sure that that module is loaded before the call to compinit
so that that widget is also re-defined. If completion styles (see
below) are set up to perform expansion as well as completion by
default, and the TAB key is bound to expand-or-complete, compinit will
rebind it to complete-word; this is necessary to use the correct form
of expansion.
Should you need to use the original completion commands, you can still
bind keys to the old widgets by putting a `.' in front of the widget
name, e.g. `.expand-or-complete'.
To speed up the running of compinit, it can be made to produce a dumped
configuration that will be read in on future invocations; this is the
default, but can be turned off by calling compinit with the option -D.
The dumped file is .zcompdump in the same directory as the startup
files (i.e. $$ZDOTDIR or $$HOME); alternatively, an explicit file name
can be given by `compinit -d dumpfile'. The next invocation of
compinit will read the dumped file instead of performing a full ini-
tialization.
If the number of completion files changes, compinit will recognise this
and produce a new dump file. However, if the name of a function or the
arguments in the first line of a ##compdef function (as described below)
change, it is easiest to delete the dump file by hand so that compinit
will re-create it the next time it is run. The check performed to see
if there are new functions can be omitted by giving the option -C. In
this case the dump file will only be created if there isn't one
already.
The dumping is actually done by another function, compdump, but you
will only need to run this yourself if you change the configuration
(e.g. using compdef) and then want to dump the new one. The name of
the old dumped file will be remembered for this purpose.
If the parameter compdir is set, compinit uses it as a directory where
completion functions can be found; this is only necessary if they are
not already in the function search path.
For security reasons compinit also checks if the completion system
would use files not owned by root or by the current user, or files in
directories that are world- or group-writable or that are not owned by
root or by the current user. If such files or directories are found,
compinit will ask if the completion system should really be used. To
avoid these tests and make all files found be used without asking, use
the option -u, and to make compinit silently ignore all insecure files
and directories use the option -i. This security check is skipped
entirely when the -C option is given.
The security check can be retried at any time by running the function
compaudit. This is the same check used by compinit, but when it is
executed directly any changes to fpath are made local to the function
so they do not persist. The directories to be checked may be passed as
arguments; if none are given, compaudit uses fpath and compdir to find
completion system directories, adding missing ones to fpath as neces-
sary. To force a check of exactly the directories currently named in
fpath, set compdir to an empty string before calling compaudit or
compinit.
Autoloaded files
The convention for autoloaded functions used in completion is that they
start with an underscore; as already mentioned, the fpath/FPATH parame-
ter must contain the directory in which they are stored. If zsh was
properly installed on your system, then fpath/FPATH automatically con-
tains the required directories for the standard functions.
For incomplete installations, if compinit does not find enough files
beginning with an underscore (fewer than twenty) in the search path, it
will try to find more by adding the directory compdir to the search
path. If that directory has a subdirectory named Base, all subdirecto-
ries will be added to the path. Furthermore, if the subdirectory Base
has a subdirectory named Core, compinit will add all subdirectories of
the subdirectories is to the path: this allows the functions to be in
the same format as in the zsh source distribution.
When compinit is run, it searches all such files accessible via
fpath/FPATH and reads the first line of each of them. This line should
contain one of the tags described below. Files whose first line does
not start with one of these tags are not considered to be part of the
completion system and will not be treated specially.
The tags are:
##compdef names... [ -[pP] patterns... [ -N names... ] ]
The file will be made autoloadable and the function defined in
it will be called when completing names, each of which is either
the name of a command whose arguments are to be completed or one
of a number of special contexts in the form -context- described
below.
Each name may also be of the form `cmd==service'. When complet-
ing the command cmd, the function typically behaves as if the
command (or special context) service was being completed
instead. This provides a way of altering the behaviour of func-
tions that can perform many different completions. It is imple-
mented by setting the parameter $$service when calling the func-
tion; the function may choose to interpret this how it wishes,
and simpler functions will probably ignore it.
If the ##compdef line contains one of the options -p or -P, the
words following are taken to be patterns. The function will be
called when completion is attempted for a command or context
that matches one of the patterns. The options -p and -P are
used to specify patterns to be tried before or after other com-
pletions respectively. Hence -P may be used to specify default
actions.
The option -N is used after a list following -p or -P; it speci-
fies that remaining words no longer define patterns. It is pos-
sible to toggle between the three options as many times as nec-
essary.
##compdef -k style key-sequences...
This option creates a widget behaving like the builtin widget
style and binds it to the given key-sequences, if any. The
style must be one of the builtin widgets that perform comple-
tion, namely complete-word, delete-char-or-list, expand-or-com-
plete, expand-or-complete-prefix, list-choices, menu-complete,
menu-expand-or-complete, or reverse-menu-complete. If the
zsh/complist module is loaded (see zshmodules(1)) the widget
menu-select is also available.
When one of the key-sequences is typed, the function in the file
will be invoked to generate the matches. Note that a key will
not be re-bound if if it already was (that is, was bound to
something other than undefined-key). The widget created has the
same name as the file and can be bound to any other keys using
bindkey as usual.
##compdef -K widget-name style key-sequences ...
This is similar to -k except that only one key-sequences argu-
ment may be given for each widget-name style pair. However, the
entire set of three arguments may be repeated with a different
set of arguments. Note in particular that the widget-name must
be distinct in each set. If it does not begin with `' this
will be added. The widget-name should not clash with the name
of any existing widget: names based on the name of the function
are most useful. For example,
##compdef -K foocomplete complete-word ""^^X^^C"" \\
foolist list-choices ""^^X^^D""
(all on one line) defines a widget foocomplete for completion,
bound to `^^X^^C', and a widget foolist for listing, bound to
`^^X^^D'.
##autoload [ options ]
Functions with the ##autoload tag are marked for autoloading but
are not otherwise treated specially. Typically they are to be
called from within one of the completion functions. Any options
supplied will be passed to the autoload builtin; a typical use
is ]X to force the function to be loaded immediately. Note that
the -U and -z flags are always added implicitly.
The ## is part of the tag name and no white space is allowed after it.
The ##compdef tags use the compdef function described below; the main
difference is that the name of the function is supplied implicitly.
The special contexts for which completion functions can be defined are:
-array-value-
The right hand side of an array-assignment (`foo==(...)')
-brace-parameter-
The name of a parameter expansion within braces (`$${{...}}')
-assign-parameter-
The name of a parameter in an assignment, i.e. on the left hand
side of an `=='
-command-
A word in command position
-condition-
A word inside a condition (`[...]')
-default-
Any word for which no other completion is defined
-equal-
A word beginning with an equals sign
-first-
This is tried before any other completion function. The func-
tion called may set the compskip parameter to one of various
values: all: no further completion is attempted; a string con-
taining the substring patterns: no pattern completion functions
will be called; a string containing default: the function for
the `-default-' context will not be called, but functions
defined for commands will
-math- Inside mathematical contexts, such as `((...))'
-parameter-
The name of a parameter expansion (`$$...')
-redirect-
The word after a redirection operator.
-subscript-
The contents of a parameter subscript.
-tilde-
After an initial tilde (`~~'), but before the first slash in the
word.
-value-
On the right hand side of an assignment.
Default implementations are supplied for each of these contexts. In
most cases the context -context- is implemented by a corresponding
function context, for example the context `-tilde-' and the function
`tilde').
The contexts -redirect- and -value- allow extra context-specific infor-
mation. (Internally, this is handled by the functions for each context
calling the function dispatch.) The extra information is added sepa-
rated by commas.
For the -redirect- context, the extra information is in the form `-re-
direct-,,op,,command', where op is the redirection operator and command
is the name of the command on the line. If there is no command on the
line yet, the command field will be empty.
For the -value- context, the form is `-value-,,name,,command', where name
is the name of the parameter. In the case of elements of an associa-
tive array, for example `assoc==(key < |