
ZSHALL
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 manual 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 mechanism, and a host of other features. AUTHOR
Zsh was originally written by Paul Falstad <pf@zsh.org>. Zsh is now maintained by the members of the zsh-workers mailing list <zsh-work- ers@sunsite.dk>. The development is currently coordinated by Peter Stephenson <pws@zsh.org>. The coordinator can be contacted at <coordi- nator@zsh.org>, 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 Sourceforge. See http://sourceforge.net/projects/zsh/ for details. MAILING LISTS
Zsh has 3 mailing lists: <zsh-announce@sunsite.dk> Announcements about releases, major changes in the shell and the monthly posting of the Zsh FAQ. (moderated) <zsh-users@sunsite.dk> User discussions. <zsh-workers@sunsite.dk> Hacking, development, bug reports and patches. To subscribe or unsubscribe, send mail to the associated administrative address for the mailing list. <zsh-announce-subscribe@sunsite.dk> <zsh-users-subscribe@sunsite.dk> <zsh-workers-subscribe@sunsite.dk> <zsh-announce-unsubscribe@sunsite.dk> <zsh-users-unsubscribe@sunsite.dk> <zsh-workers-unsubscribe@sunsite.dk> YOU ONLY NEED 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-workers. If you have problems subscribing/unsubscribing to any of the mailing lists, send mail to <listmaster@zsh.org>. The mailing lists are maintained by Karsten Thygesen <karthy@kom.auc.dk>. The mailing lists are archived; the archives can be accessed via the administrative addresses listed above. There is also a hypertext archive, maintained by Geoff Wing <gcw@zsh.org>, available at http://www.zsh.org/mla/. THE ZSH FAQ
Zsh has a list of Frequently Asked Questions (FAQ), maintained by Peter Stephenson <pws@zsh.org>. 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 <faqmaster@zsh.org>. THE ZSH WEB PAGE
Zsh has a web page which is located at http://www.zsh.org/. This is maintained by Karsten Thygesen <karthy@zsh.org>, of SunSITE Denmark. The contact address for web-related matters is <webmaster@zsh.org>. 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, chapters dealing with startup files and their contents and the new completion 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 configurations. INVOCATION OPTIONS
The following flags are interpreted by the shell when invoked to determine 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 further arguments are given, the first one is assigned to $0, 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 SH_WORD_SPLIT 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 SH_WORD_SPLIT 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 standard 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 processing. Secondly, a special option `--' (or `+-'), which may be specified 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 respectively; 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 SHELL environment variable and perform emulation based on that. In sh and ksh compatibility modes the following parameters are not special 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: NO_BAD_PATTERN, NO_BANG_HIST, NO_BG_NICE, NO_EQUALS, NO_FUNCTION_ARGZERO, GLOB_SUBST, NO_GLOBAL_EXPORT, NO_HUP, INTERACTIVE_COMMENTS, KSH_ARRAYS, NO_MULTIOS, NO_NOMATCH, NO_NOTIFY, POSIX_BUILTINS, NO_PROMPT_PERCENT, RM_STAR_SILENT, SH_FILE_EXPANSION, SH_GLOB, SH_OPTION_LETTERS, SH_WORD_SPLIT. Additionally the BSD_ECHO and IGNORE_BRACES options are set if zsh is invoked as sh. Also, the KSH_OPTION_PRINT, LOCAL_OPTIONS, PROMPT_BANG, PROMPT_SUBST and SINGLE_LINE_ZLE options are set if zsh is invoked as ksh. RESTRICTED SHELL
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: changing directories with the cd builtin changing or unsetting the PATH, path, MODULE_PATH, module_path, SHELL, HISTFILE, HISTSIZE, GID, EGID, UID, EUID, USERNAME, LD_LIBRARY_PATH, LD_AOUT_LIBRARY_PATH, LD_PRELOAD and LD_AOUT_PRELOAD parameters specifying command names containing / specifying command pathnames using hash redirecting output to files using the exec builtin command to replace the shell with another command using jobs -Z to overwrite the shell process' argument and environment space using the ARGV0 parameter to override argv[0] for external commands 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 commands 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 GLOBAL_RCS 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 GLOBAL_RCS. Both RCS and GLOBAL_RCS 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/.zprofile. 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 GLOBAL_RCS 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 installation. 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 command (see zshbuiltins(1)). If a compiled file exists (named for the original file plus the .zwc extension) and it is newer than the original file, the compiled file will be used instead. ZSHMISC(1) ZSHMISC(1) NAME
zshmisc - everything and then some SIMPLE COMMANDS & PIPELINES A simple command is a sequence of optional parameter assignments followed by blank-separated words, with optional redirections interspersed. The first word is the command to be executed, and the remaining 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 pipeline 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 command 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 sublist 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 whatsoever, including the complex commands below; this is implied wherever the word `list' appears in later descriptions. For example, the commands in a shell function form a special sort of list. PRECOMMAND 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[0] 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 interpreted 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 COMMANDS
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, executing list each time. If the in word is omitted, use the positional 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 section `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 selection 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, continue, 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, continue, 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 function, 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 substitution 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 TRY_BLOCK_ERROR. 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 TRY_BLOCK_ERROR 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 useful (unless this forms part of an enclosing always block). Regardless of TRY_BLOCK_ERROR, 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 TRY_BLOCK_ERROR was set to zero. The following executes the given code, ignoring any errors it causes. This is an alternative to the usual convention of protecting code by executing it in a subshell. { # code which may cause an error } always { # This code is executed regardless of the error. (( TRY_BLOCK_ERROR = 0 )) } # The error condition has been reset. An exit command encountered in try-list does not cause the execution 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 SH_GLOB 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 parameter. 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 COMMANDS
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 SHORT_LOOPS option is set. For the if, while and until commands, in both these cases the test part of the loop must also be suitably 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 SHORT_LOOPS 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 IGNORE_BRACES option is not set. COMMENTS
In noninteractive shells, or in interactive shells with the INTERACTIVE_COMMENTS 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 command), 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 preceding 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 considered 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 RC_QUOTES 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 RC_QUOTES 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 produces 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 CLOBBER 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 CLOBBER is unset. >> word Open file word for writing in append mode as standard output. If the file does not exist, and the CLOBBER 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 CLOBBER 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. Backquotes 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 section below). >&| word >&! word &>| word &>! word Redirects both standard output and standard error (file descriptor 2) in the manner of `>| word'. >>& word &>> word Redirects both standard output and standard error (file descriptor 2) in the manner of `>> word'. >>&| word >>&! word &>>| word &>>! word Redirects both standard output and standard error (file descriptor 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 descriptor 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 Substitution 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 0 >> *.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 <foo <fubar or even sort <f{oo,ubar} is equivalent to `cat foo fubar | sort'. Note that a pipe is an implicit redirection; thus cat bar | sort <foo is equivalent to `cat bar foo | sort' (note the order of the inputs). If the MULTIOS option is unset, each redirection replaces the previous redirection for that file descriptor. However, all files redirected to are actually opened, so echo foo > 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 COMMAND
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 NULLCMD is not set or the option CSH_NULLCMD is set, an error is caused. This is the csh behavior and CSH_NULLCMD is set by default when emulating csh. If the option SH_NULLCMD is set, the builtin `:' is inserted as a command with the given redirections. This is the default when emulating sh or ksh. Otherwise, if the parameter NULLCMD is set, its value will be used as a command with the given redirections. If both NULLCMD and READNULLCMD 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 NULLCMD is `cat' and for READNULLCMD is `more'. Thus < file shows the contents of file on standard output, with paging if that is a terminal. NULLCMD and READNULLCMD may refer to shell functions. COMMAND 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 operating systems that do not handle this executable format in the kernel. FUNCTIONS
Shell functions are defined with the function reserved word or the special syntax `funcname ()'. Shell functions are read in and stored internally. Alias names are resolved when the function is read. Functions are executed like commands with the arguments passed as positional parameters. (See 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 environment of the caller. The return builtin is used to return from function calls. Function identifiers can be listed with the functions builtin. Functions can be undefined with the unfunction builtin. AUTOLOADING FUNCTIONS
A function can be marked as undefined using the autoload builtin (or `functions -u' or `typeset -fu'). Such a function has no body. When the function is first executed, the shell searches for its definition using the elements of the fpath variable. Thus to define functions for autoloading, a typical sequence is: fpath=(~/myfuncs $fpath) autoload myfunc1 myfunc2 ... The usual alias expansion during reading will be suppressed if the autoload builtin or its equivalent is given the option -U. This is recommended for the use of functions supplied with the zsh distribution. Note that for functions precompiled with the zcompile builtin command the flag -U must be provided when the .zwc file is created, as the corresponding information is compiled into the latter. For each element in fpath, the shell looks for three possible files, the newest of which is used to load the definition for the function: element.zwc A file created with the zcompile builtin command, which is expected to contain the definitions for all functions in the directory named element. The file is treated in the same manner as a directory containing files for functions and is searched for the definition of the function. If the definition is not found, the search for a definition proceeds with the other two possibilities described below. If element already includes a .zwc extension (i.e. the extension was explicitly given by the user), element is searched for the definition of the function without comparing its age to that of other files; in fact, there does not need to be any directory named element without the suffix. Thus including an element such as `/usr/local/funcs.zwc' in fpath will speed up the search for functions, with the disadvantage that functions included must be explicitly recompiled by hand before the shell notices any changes. element/function.zwc A file created with zcompile, which is expected to contain the definition for function. It may include other function definitions as well, but those are neither loaded nor executed; a file found in this way is searched only for the definition of function. element/function A file of zsh command text, taken to be the definition for function. In summary, the order of searching is, first, in the parents of directories in fpath for the newer of either a compiled directory or a directory in fpath; second, if more than one of these contains a definition for the function that is sought, the leftmost in the fpath is chosen; and third, within a directory, the newer of either a compiled function or an ordinary function definition is used. If the KSH_AUTOLOAD option is set, or the file contains only a simple definition of the function, the file's contents will be executed. This will normally define the function in question, but may also perform initialization, which is executed in the context of the function execution, and may therefore define local parameters. It is an error if the function is not defined by loading the file. Otherwise, the function body (with no surrounding `funcname() {...}') is taken to be the complete contents of the file. This form allows the file to be used directly as an executable shell script. If processing of the file results in the function being re-defined, the function itself is not re-executed. To force the shell to perform initialization and then call the function defined, the file should contain initialization code (which will be executed then discarded) in addition to a complete function definition (which will be retained for subsequent calls to the function), and a call to the shell function, including any arguments, at the end. For example, suppose the autoload file func contains func() { print This is func; } print func is initialized then `func; func' with KSH_AUTOLOAD set will produce both messages on the first call, but only the message `This is func' on the second and subsequent calls. Without KSH_AUTOLOAD set, it will produce the initialization message on the first call, and the other message on the second and subsequent calls. It is also possible to create a function that is not marked as autoloaded, but which loads its own definition by searching fpath, by using `autoload -X' within a shell function. For example, the following are equivalent: myfunc() { autoload -X } myfunc args... and unfunction myfunc # if myfunc was defined autoload myfunc myfunc args... In fact, the functions command outputs `builtin autoload -X' as the body of an autoloaded function. This is done so that eval "$(functions)" produces a reasonable result. A true autoloaded function can be identified by the presence of the comment `# undefined' in the body, because all comments are discarded from defined functions. To load the definition of an autoloaded function myfunc without executing myfunc, use: autoload +X myfunc SPECIAL FUNCTIONS
The following functions, if defined, have special meaning to the shell: chpwd Executed whenever the current working directory is changed. periodic If the parameter PERIOD is set, this function is executed every $PERIOD seconds, just before a prompt. precmd Executed before each prompt. preexec Executed just after a command has been read and is about to be executed. If the history mechanism is active (and the line was not discarded from the history buffer), the string that the user typed is passed as the first argument, otherwise it is an empty string. The actual command that will be executed (including expanded aliases) is passed in two different forms: the second argument is a single-line, size-limited version of the command (with things like function bodies elided); the third argument contains the full text 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 execution 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 TRAPZERR, TRAPDEBUG and TRAPEXIT are never executed 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. TRAPZERR
Executed whenever a command has a non-zero exit status. However, the function is not executed if the command occurred in a sublist followed by `&&' or `||'; only the final command in a sublist of this type causes the trap to be executed. The functions beginning `TRAP' may alternatively be defined with the trap builtin: this may be preferable for some uses, as they are then run in the environment of the calling process, rather than in their own function environment. Apart from the difference in calling procedure and the fact that the function form appears in lists of functions, the forms TRAPNAL() { # code } and trap ' # code 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 `suspended', and print another prompt. You can then manipulate the state of this job, putting it in the background with the bg command, or run some other commands and then eventually bring the job back into the foreground with the foreground command fg. A ^Z takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. A job being run in the background will suspend if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command `stty tostop'. If you set this tty option, then background jobs will suspend when they try to produce output like they do when they try to read input. When a command is suspended and continued later with the fg or wait builtins, zsh restores tty modes that were in effect when it was suspended. This (intentionally) does not apply if the command is continued via `kill -CONT', nor when it is continued with bg. There are several ways to refer to jobs in the shell. A job can be referred to by the process ID of any process of the job or by one of the following: %number The job with the given number. %string Any job whose command line begins with string. %?string Any job whose command line contains string. %% Current job. %+ Equivalent to `%%'. %- Previous job. The shell learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible. If the NOTIFY option is not set, it waits until just before it prints a prompt before it informs you. All such notifications 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 triggers any trap set for CHLD. When you try to leave the shell while jobs are running or suspended, you will be warned that `You have suspended (running) jobs'. You may use the jobs command to see what they are. If you do this or immediately try to exit again, the shell will not warn you a second time; the suspended jobs will be terminated, and the running jobs will be sent a SIGHUP signal, if the HUP option is set. To avoid having the shell terminate the running jobs, either use the nohup command (see nohup(1)) or the disown builtin. SIGNALS
The INT and QUIT signals for an invoked command are ignored if the command is followed by `&' and the MONITOR option is not active. Otherwise, signals have the values inherited by the shell from its parent (but see the TRAPNAL special functions in 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 - $(( 12345678901 ))'; if the number appears unchanged, the precision is at least 8 bytes. Floating point arithmetic is always double precision. The let builtin command takes arithmetic expressions as arguments; each is evaluated separately. Since many of the arithmetic operators, as well as spaces, require quoting, an alternative form is provided: for any command which begins with a `((', all the characters until a matching `))' are treated as a quoted expression and arithmetic expansion performed as for an argument of let. More precisely, `((...))' is equivalent to `let "..."'. For example, the following statement (( val = 2 + 1 )) is equivalent to let "val = 2 + 1" both assigning the value 3 to the shell variable val and returning a zero status. Integers can be in bases other than 10. A leading `0x' or `0X' denotes hexadecimal. Integers may also be of the form `base#n', where base is a decimal number between two and thirty-six representing the arithmetic base and n is a number in that base (for example, `16#ff' is 255 in hexadecimal). The base# may also be omitted, in which case base 10 is used. For backwards compatibility the form `[base]n' is also accepted. It is also possible to specify a base to be used for output in the form `[#base]', for example `[#16]'. This is used when outputting arithmetical substitutions or when assigning to scalar parameters, but an explicitly defined integer or floating point parameter will not be affected. If an integer variable is implicitly defined by an arithmetic expression, any base specified in this way will be set as the variable's output arithmetic base as if the option `-i base' to the typeset builtin had been used. The expression has no precedence and if it occurs more than once in a mathematical expression, the last encountered is used. For clarity it is recommended that it appear at the beginning of an expression. As an example: typeset -i 16 y print $(( [#8] x = 32, y = 32 )) print $x $y outputs first `8#40', the rightmost value in the given output base, and then `8#40 16#20', because y has been explicitly declared to have output base 16, while x (assuming it does not already exist) is implicitly typed by the arithmetic evaluation, where it acquires the output base 8. If the C_BASES option is set, hexadecimal numbers in the standard C format, for example 0xFF instead of the usual `16#FF'. If the option OCTAL_ZEROES is also set (it is not by default), octal numbers will be treated similarly and hence appear as `077' 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 appropriate base prefix will be output if necessary, so that the value output is valid syntax for input. If the # is doubled, for example `[##16]', then no base prefix is output. Floating point constants are recognized by the presence of a decimal point or an exponent. The decimal point may be the first character of the constant, but the exponent character e or E may not, as it will be taken for a parameter name. An arithmetic expression uses nearly the same syntax, precedence, and associativity of expressions in C. The following operators are supported (listed in decreasing order of precedence): + - ! ~ ++ -unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement << >> bitwise shift left, right & bitwise AND ^ bitwise XOR | bitwise OR ** exponentiation * / % multiplication, division, modulus (remainder) + - addition, subtraction < > <= >= comparison == != equality and inequality && logical AND || ^^ logical OR, XOR ? : ternary operator = += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **= assignment , comma operator The operators `&&', `||', `&&=', and `||=' are short-circuiting, and only one of the latter two expressions in a ternary operator is evaluated. Note the precedence of the bitwise AND, OR, and XOR operators. Mathematical functions can be called with the syntax `func(args)', where the function decides if the args is used as a string or a comma-separated list of arithmetic expressions. The shell currently defines no mathematical functions by default, but the module zsh/mathfunc may be loaded with the zmodload builtin to provide standard floating point mathematical functions. An expression of the form `##x' where x is any character sequence such as `a', `^A', or `\M-\C-x' gives the ASCII value of this character and an expression of the form `#foo' gives the ASCII value of the first character of the value of the parameter foo. Note that this is different from the expression `$#foo', a standard parameter substitution which gives the length of the parameter foo. `#\' is accepted instead of `##', but its use is deprecated. Named parameters and subscripted arrays can be referenced by name within an arithmetic expression without using the parameter expansion syntax. For example, ((val2 = val1 * 2)) assigns twice the value of $val1 to the parameter named val2. An internal integer representation of a named parameter can be specified with the integer builtin. Arithmetic evaluation is performed on the value of each assignment to a named parameter declared integer in this manner. Assigning a floating point number to an integer results in rounding down to the next integer. Likewise, floating point numbers can be declared with the float builtin; there are two types, differing only in their output format, as described for the typeset builtin. The output format can be bypassed by using arithmetic substitution instead of the parameter substitution, i.e. `${float}' uses the defined format, but `$((float))' uses a generic floating point format. Promotion of integer to floating point values is performed where necessary. In addition, if any operator which requires an integer (`~', `&', `|', `^', `%', `<<', `>>' and their equivalents with assignment) is given a floating point argument, it will be silently rounded down to the next integer. Scalar variables can hold integer or floating point values at different times; there is no memory of the numeric type in this case. If a variable is first assigned in a numeric context without previously being declared, it will be implicitly typed as integer or float and retain that type either until the type is explicitly changed or until the end of the scope. This can have unforeseen consequences. For example, in the loop for (( f = 0; f < 1; f += 0.1 )); do # use $f done if f has not already been declared, the first assignment will cause it to be created as an integer, and consequently the operation `f += 0.1' will always cause the result to be truncated to zero, so that the loop will fail. A simple fix would be to turn the initialization into `f = 0.0'. It is therefore best to declare numeric variables with explicit types. CONDITIONAL EXPRESSIONS
A conditional expression is used with the [[ compound command to test attributes of files and to compare strings. Each expression can be constructed from one or more of the following unary or binary 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 character, 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 ASCII value of their characters. string1 > string2 true if string1 comes after string2 based on ASCII value of their characters. exp1 -eq exp2 true if exp1 is numerically equal to exp2. exp1 -ne exp2 true if exp1 is numerically not equal to exp2. exp1 -lt exp2 true if exp1 is numerically less than exp2. exp1 -gt exp2 true if exp1 is numerically greater than exp2. exp1 -le exp2 true if exp1 is numerically less than or equal to exp2. exp1 -ge exp2 true if exp1 is numerically greater than or equal to exp2. ( exp ) true if exp is true. ! exp true if exp is false. exp1 && exp2 true if exp1 and exp2 are both true. exp1 || exp2 true if either exp1 or exp2 is true. Normal shell expansion is performed on the file, string and pattern arguments, but the result of each expansion is constrained to be a single word, similar to the effect of double quotes. However, pattern metacharacters are active for the pattern arguments; the patterns are the same as those used for filename generation, see 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 PROMPT_SUBST 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 PROMPT_BANG option is set, a `!' in the prompt is replaced by the current history event number. A literal `!' may then be represented as `!!'. If the PROMPT_PERCENT option is set, certain escape sequences that start with `%' are expanded. Some escapes take an optional integer argument, which should appear between the `%' and the next character of the sequence. The following escape sequences are recognized: 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 $0. An integer may follow the `%' to specify a number of trailing path components to show; zero means the full path. A negative integer specifies leading components. %c %. %C Trailing component of $PWD. An integer may follow the `%' to get more than one component. Unless `%C' is used, tilde contraction is performed first. These are deprecated as %c and %C are equivalent to %1~ and %1/, respectively, while explicit positive integers have the same effect as for the latter two sequences. 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 strftime(3) href="time.3.html">time(3) for more details. Three additional codes are available: %f prints the day of the month, like %e but without any preceding space if the day is a single digit, and %K/%L correspond to %k/%l for the hour of the day (24/12 hour clock) in the same way. 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 following: ! 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< %>string> %[xstring] Specifies truncation behaviour for the remainder of the prompt string. The third, deprecated, form is equivalent to `%xstringx', i.e. x may be `<' or `>'. The numeric argument, which in the third form may appear immediately after the `[', specifies the maximum permitted length of the various strings that can be displayed in the prompt. The string will be displayed in place of the truncated portion of any string; note this does not undergo prompt expansion. The forms with `<' truncate at the left of the string, and the forms with `>' truncate at the right of the string. For example, if the current directory is `/home/pike', the prompt `%8<..<%/' will expand to `..e/pike'. In this string, the ter- minating character (`<', `>' or `]'), or in fact any character, may be quoted by a preceding `\'; note when using print -P, however, that this must be doubled as the string is also subject to standard print processing, in addition to any backslashes removed by a double quoted string: the worst case is therefore `print -P "%<\\\\<<..."'. If the string is longer than the specified truncation length, it will appear in full, completely replacing the truncated string. The part of the prompt string to be truncated runs to the end of the string, or to the end of the next enclosing group of the `%(' construct, or to the next truncation encountered at the same grouping level (i.e. truncations inside a `%(' are 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 SH_FILE_EXPANSION option is set, the order of expansion is modified for compatibility with sh and ksh. In that case filename expansion is performed immediately after alias expansion, preceding the set of five expansions mentioned above. Filename Generation This expansion, commonly referred to as globbing, is always done last. The following sections explain the types of expansion in detail. HISTORY EXPANSION
History expansion allows you to use words from previous command lines in the command line you are typing. This simplifies spelling corrections and the repetition of complicated commands or arguments. Immediately before execution, each command is saved in the history list, the size of which is controlled by the HISTSIZE parameter. The one most recent command is always retained in any case. Each saved command in the history list is called a history event and is assigned a number, beginning with 1 (one) when the shell starts up. The history number that you may see in your prompt (see Prompt Expansion 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 command line; history expansions do not nest. The `!' can be escaped with `\' or can be enclosed between a pair of single quotes ('') to suppress its special meaning. Double quotes will not work for this. Following this history character is an optional event designator (see 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 previous command. However, if the option CSH_JUNKIE_HISTORY is set, then every history reference with no event specification always refers to the previous command. For example, `!' is the event designator for the previous command, so `!!:1' always refers to the first word of the previous command, and `!!$' always refers to the last word of the previous command. With CSH_JUNKIE_HISTORY set, then `!:1' and `!$' function in the same manner as `!!:1' and `!!$', respectively. Conversely, if CSH_JUNKIE_HISTORY is unset, then `!:1' and `!$' refer to the first and last words, respectively, of the same event referenced by the nearest other history reference preceding them on the current command line, or to the previous command if there is no preceding reference. The character sequence `^foo^bar' (where `^' is actually the second character of the histchars parameter) repeats the last command, replacing the string foo with bar. More precisely, the sequence `^foo^bar^' is synonymous with `!!:s^foo^bar^', hence other modifiers (see the section `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 support is provided by the fc builtin. Event Designators An event designator is a reference to a command-line entry in the history list. In the list below, remember that the initial `!' in each item may be changed to another character by setting the histchars parameter. ! Start a history expansion, except when followed by a blank, newline, `=' or `('. If followed immediately by a word designator (see the section `Word Designators'), this forms a history reference 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 modifier or followed by any text that is not to be considered part of str. !# Refer to the current command line typed in so far. The line is treated as if it were complete up to and including the word before the one with the `!#' reference. !{...} Insulate a history reference from adjacent characters (if necessary). Word Designators A word designator indicates which word or words of a given command line are to be included in a history reference. A `:' usually separates the event specification from the word designator. It may be omitted only if the word designator begins with a `^', `$', `*', `-' or `%'. Word designators include: 0 The first input word (command). n The nth argument. ^ The first argument. That is, 1. $ The last argument. % The word matched by (the most recent) ?str search. x-y A range of words; x defaults to 0. * All the arguments, or a null value if there are none. x* Abbreviates `x-$'. x- Like `x*' but omitting word $. Note that a `%' word designator works only when used in one of `!%', `!:%' or `!?str?:%', and only when used after a !? expansion (possibly in an earlier command). Anything else results in an error, although the error may not be the most obvious one. Modifiers After the optional word designator, you can add a sequence of one or more of the following modifiers, each preceded by a `:'. These modifiers also work on the result of filename generation and parameter expansion, except where noted. h Remove a trailing pathname component, leaving the head. This works like `dirname'. r Remove a filename extension of the form `.xxx', leaving the root name. e Remove all but the extension. t Remove all leading pathname components, leaving the tail. This works like `basename'. p Print the new command but do not execute it. Only works with history expansion. q Quote the substituted words, escaping further substitutions. Works with history expansion and parameter expansion, though for parameters it is only useful if the resulting text is to be re-evaluated such as by eval. Q Remove one level of quotes from the substituted words. x Like q, but break into words at whitespace. Does not work with parameter expansion. l Convert the words to all lowercase. u Convert the words to all uppercase. s/l/r[/] Substitute r for l as described below. Unless preceded immediately by a g, with no colon between, the substitution is done only for the first string that matches l. For arrays and for filename generation, this applies to each word of the expanded text. & Repeat the previous s substitution. Like s, may be preceded immediately by a g. In parameter expansion the & must appear inside braces, and in filename generation it must be quoted with a backslash. The s/l/r/ substitution works as follows. The left-hand side of substitutions are not regular expressions, but character strings. Any character can be used as the delimiter in place of `/'. A backslash quotes the delimiter character. The character `&', in the right-hand-side r, is replaced by the text from the left-hand-side l. The `&' can be quoted with a backslash. A null l uses the previous string either from the previous l or from the contextual scan string s from `!?s'. You can omit the rightmost delimiter if a newline immediately follows r; the rightmost `?' in a context scan can similarly be omitted. Note the same record of the last l and r is maintained across all forms of expansion. The following f, F, w and W modifiers work only with parameter expansion and filename generation. They are listed here to provide a single point of reference for all modifiers. f Repeats the immediately (without a colon) following modifier until the resulting word doesn't change any more. F:expr: Like f, but repeats only n times if the expression expr evaluates to n. Any character can be used instead of the `:'; if `(', `[', or `{' is used as the opening delimiter, the closing delimiter should be ')', `]', or `}', respectively. w Makes the immediately following modifier work on each word in the string. W:sep: Like w but words are considered to be the parts of the string that are separated by sep. Any character can be used instead of the `:'; opening parentheses are handled specially, see above. PROCESS SUBSTITUTION
Each command argument of the form `<(list)', `>(list)' or `=(list)' is subject to process substitution. In the case of the < or > forms, the shell runs process list asynchronously. If the system supports the /dev/fd mechanism, the command argument is the name of the device file corresponding to a file descriptor; otherwise, if the system supports named pipes (FIFOs), the command argument will be a named pipe. If the form with > is selected then writing on this special file will provide input for list. If < is used, then the file passed as an argument will be connected to the output of the list process. For example, paste <(cut -f1 file1) <(cut -f3 file2) | tee >(process1) >(process2) >/dev/null cuts fields 1 and 3 from the files file1 and file2 respectively, pastes the results together, and sends it to the processes process1 and process2. 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 behaviour) block for ever and have to be killed explicitly. In both cases, the shell actually supplies the information using a pipe, so that programmes that expect to lseek (see lseek(2)) on the file will not work. Also note that the previous example can be more compactly and efficiently written (provided the MULTIOS option is set) as: paste <(cut -f1 file1) <(cut -f3 file2) \ > >(process1) > >(process2) The shell uses pipes instead of FIFOs to implement the latter two process substitutions in the above example. 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 asynchronously. 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 zshparam(1) a -->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 SH_WORD_SPLIT 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 letter, 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 KSH_ARRAYS is not set, are a single subscript 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 KSH_ARRAYS 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 KSH_ARRAYS, this is the first element of an array. No field splitting is done on the result unless the SH_WORD_SPLIT option is set. ${+name} If name is the name of a set parameter `1' is substituted, otherwise `0' is substituted. ${name:-word} If name is set and is non-null then substitute its value; otherwise 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; otherwise, print word and exit from the shell. Interactive shells instead return to the prompt. If word is omitted, then a standard 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 substitution 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 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} 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 `(M)' 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 GLOB_SUBST 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 pattern 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 RC_EXPAND_PARAM 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 section `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 SH_WORD_SPLIT 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 GLOB_SUBST 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 substitution 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 further 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