zshmisc − everything and then some


A simple command is a sequence of optional parameter assignments followed by blank−separated words, with optional redirections interspersed. For a description of assignment, see the beginning of zshparam(1).


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 ordinary 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 status). If two pipelines are separated by ’||’, the second is executed only if the first fails (returns a nonzero status). 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


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.



The command is executed with a ’’ prepended to its argv[0] string.



command [ −pvV ]

The command word is taken to be the name of an external command, rather than a shell function or builtin. If the POSIX_BUILTINS 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.

exec [ −cl ] [ −a argv0 ]

The following command together with any arguments is run in place of the current process, rather than as a sub−process. The shell does not fork and is replaced. The shell does not invoke TRAPEXIT, nor does it source zlogout files. The options are provided for compatibility with other shells.

The −c option clears the environment.

The −l option is equivalent to the precommand modifier, to treat the replacement command as a login shell; the command is executed with a prepended to its argv[0] string. This flag has no effect if used together with the −a option.







A complex command in zsh is one of the following:



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.

The term consists of one or more newline or ; which terminate the words, and are optional when the ’in word’ is omitted.



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


until list do list done


repeat word do list done


The repeat syntax is disabled by default when the shell starts in a mode emulating another shell. It can be enabled with the command ’enable −r repeat





If the list that is executed is terminated with ;| the shell continues to scan the patterns looking for the next match, executing the corresponding list, and applying the rule for the corresponding terminator ;;, ;& or ;|. Note that word is not re−expanded; all applicable patterns are tested with the same word.



( 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’.


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 try−list. This will be non−zero if there was an error, even if TRY_BLOCK_ERROR was set to zero.


# code which may cause an error
} always {
# This code is executed regardless of the error.
# The error condition has been reset.

An exit command (or a return command executed at the outermost function level of a script) encountered in try−list does not cause the execution of always−list. Instead, the shell exits immediately after any EXIT trap has been executed.

... () [ term ] { list }
... () [ term ] command




func() { ... } 2>&1


time [ pipeline ]


[[ 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.


Many of zsh’s complex commands have alternate forms. These are non−standard and are likely not to be obvious even to seasoned shell programmers; they should not be used anywhere that portability of shell code is a concern.

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.

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


for name ... ( word ... ) sublist

A short form of for.




A short form of the arithmetic for command.


Another form of for.

while list { list }


until list { list }


repeat word sublist

This is a short form of repeat.


An alternative form of case.

select name [ in word ... term ] sublist



This is a short form of function.


The following words are recognized as reserved words when used as the first word of a command unless quoted or disabled using disable −r:


Additionally, ’}’ is recognized in any position if neither the IGNORE_BRACES option nor the IGNORE_CLOSE_BRACES option is set.


Certain errors are treated as fatal by the shell: in an interactive shell, they cause control to return to the command line, and in a non−interactive shell they cause the shell to be aborted. In older versions of zsh, a non−interactive shell running a script would not abort completely, but would resume execution at the next command to be read from the script, skipping the remainder of any functions or shell constructs such as loops or conditions; this somewhat illogical behaviour can be recovered by setting the option CONTINUE_ON_ERROR.

Fatal errors found in non−interactive shells include:

Failure to parse shell options passed when invoking the shell

Failure to change options with the set builtin

Parse errors of all sorts, including failures to parse mathematical expressions


Execution of incorrectly positioned loop control structures (continue, break)

Attempts to use regular expression with no regular expression module available

Disallowed operations when the RESTRICTED options is set

Failure to create a pipe needed for a pipeline

Failure to create a multio

Failure to autoload a module needed for a declared shell feature

Errors creating command or process substitutions

Syntax errors in glob qualifiers

File generation errors where not caught by the option BAD_PATTERN

All bad patterns used for matching within case statements

File generation failures where not caused by NO_MATCH or similar options


Memory errors where detected by the shell

Invalid subscripts to shell variables

Attempts to assign read−only variables

Logical errors with variables such as assignment to the wrong type

Use of invalid variable names

Errors in variable substitution syntax

Failure to convert characters in $’... expressions



In non−interactive 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.



A word is defined as:

Any plain string or glob pattern


Any parameter reference or command substitution



With global aliasing, any command separator, any redirection operator, and ’(’ or ’)’ when not part of a glob pattern



For use with completion, which would remove an initial backslash followed by a character that isn’t special, it may be more convenient to quote the word by starting with a single quote, i.e. ’foo; completion will automatically add the trailing single quote.

Alias difficulties
Although aliases can be used in ways that bend normal shell syntax, not every string of non−white−space characters can be used as an alias.



It is not presently possible to alias the ’((’ token that introduces arithmetic expressions, because until a full statement has been parsed, it cannot be distinguished from two consecutive ’(’ tokens introducing nested subshells. Also, if a separator such as && is aliased, \&& turns into the two tokens \& and &, each of which may have been aliased separately. Similarly for \<<, \>|, etc.


alias echobar=’echo bar’; echobar

This prints a message that the command echobar could not be found. This happens because aliases are expanded when the code is read in; the entire line is read in one go, so that when echobar is executed it is too late to expand the newly defined alias. This is often a problem in shell scripts, functions, and code executed with ’source’ or ’.’. Consequently, use of functions rather than aliases is recommended in non−interactive code.

Note also the unhelpful interaction of aliases and function definitions:

alias func=’noglob func’
func() {
echo Do something with $*


noglob func() {
echo Do something with $*

which defines noglob as well as func as functions with the body given. To avoid this, either quote the name func or use the alternative function definition form ’function func’. Ensuring the alias is defined after the function works but is problematic if the code fragment might be re−executed.


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 ’’’’


Inside double quotes (""), parameter and command substitution occur, and ’\’ quotes the characters ’\’, ’’, ’"’, ’$’, and the first character of $histchars (default ’!’).




< word


<> word


> word


>| word


>> word


>>| word


<<[] 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 substitution 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


<& −

>& −

Close the standard input/output.

<& p

>& p


>& 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

Redirects both standard output and standard error (file descriptor 2) in the manner of ’>| word’.

>>& word

Redirects both standard output and standard error (file descriptor 2) in the manner of ’>> word’.

>>&| word

Redirects both standard output and standard error (file descriptor 2) in the manner of ’>>| word’.


... 1>fname 2>&1


The ’|&’ command separator described in Simple Commands & Pipelines in zshmisc(1) is a shorthand for ’2>&1 |’.

The various forms of process substitution, ’<(list)’, and ’=(list)’ for input and ’>(list)’ for output, are often used together with redirection. For example, if word in an output redirection is of the form ’>(list)’ then the output is piped to the command represented by list. See Process Substitution in zshexpn(1).



... {myfd}>&1


The syntax {varid}>&−, for example {myfd}>&−, may be used to close a file descriptor opened in this fashion. Note that the parameter given by varid must previously be set to a file descriptor in this case.





integer myfd
exec {myfd}>~/logs/mylogfile.txt
print This is a log message. >&$myfd
exec {myfd}>&−




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.



date >&1 >output


date >output >&1



: > *

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



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).


echo Hello > bar > baz

when MULTIOS is unset will truncate ’bar’, and write ’Hello’ into ’baz’.


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).


{ cat file } >file >file2





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



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.


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.

If no external command is found but a function command_not_found_handler exists the shell executes this function with all command line arguments. The return status of the function becomes the status of the command. If the function wishes to mimic the behaviour of the shell when the command is not found, it should print the message ’command not found: cmd’ to standard error and return status 127. Note that the handler is executed in a subshell forked to execute an external command, hence changes to directories, shell parameters, etc. have no effect on the main shell.


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’.)


The return builtin is used to return from function calls.



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.










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...


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.


autoload +X myfunc


If no name is given for a function, it is ’anonymous’ and is handled specially. Either form of function definition may be used: a ’()’ with no preceding name, or a ’function’ with an immediately following open brace. The function is executed immediately at the point of definition and is not stored for future use. The function name is set to ’(anon)’.

Arguments to the function may be specified as words following the closing brace defining the function, hence if there are none no arguments (other than $0) are set. This is a difference from the way other functions are parsed: normal function definitions may be followed by certain keywords such as ’else’ or ’fi’, which will be treated as arguments to anonymous functions, so that a newline or semicolon is needed to force keyword interpretation.


Redirections may be applied to the anonymous function in the same manner as to a current−shell structure enclosed in braces. The main use of anonymous functions is to provide a scope for local variables. This is particularly convenient in start−up files as these do not provide their own local variable scope.

For example,

function {
local variable=inside
print "I am $variable with arguments $*"
} this and that
print "I am $variable"

outputs the following:

I am inside with arguments this and that
I am outside

Note that function definitions with arguments that expand to nothing, for example ’name=; function $name { ... }’, are not treated as anonymous functions. Instead, they are treated as normal function definitions where the definition is silently discarded.



Hook Functions
For the functions below, it is possible to define an array that has the same name as the function with ’_functions’ appended. Any element in such an array is taken as the name of a function to execute; it is executed in the same context and with the same arguments as the basic function. For example, if $chpwd_functions is an array containing the values ’mychpwd’, ’chpwd_save_dirstack’, then the shell attempts to execute the functions ’chpwd’, ’mychpwd’ and ’chpwd_save_dirstack’, in that order. Any function that does not exist is silently ignored. A function found by this mechanism is referred to elsewhere as a ’hook function’. An error in any function causes subsequent functions not to be run. Note further that an error in a precmd hook causes an immediately following periodic function not to run (though it may run at the next opportunity).


Executed whenever the current working directory is changed.




Executed before each prompt. Note that precommand functions are not re−executed simply because the command line is redrawn, as happens, for example, when a notification about an exiting job is displayed.





If any of the hook functions returns status 1 (or any non−zero value other than 2, though this is not guaranteed for future versions of the shell) the history line will not be saved, although it lingers in the history until the next line is executed, allowing you to reuse or edit it immediately.

If any of the hook functions returns status 2 the history line will be saved on the internal history list, but not written to the history file. In case of a conflict, the first non−zero status value is taken.



zshaddhistory() {
print −sr −− ${1%%$’\n’}
fc −p .zsh_local_history



Trap Functions





print "Caught SIGINT, aborting."
return $(( 128 + $1 ))







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 function TRAPERR acts the same as TRAPZERR on systems where there is no SIGERR (this is the usual case).


# code

(’function traps’) and

trap ’
# code






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.





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.


The job with the given number.


The last job whose command line begins with string.


The last job whose command line contains string.


Current job.


Equivalent to ’%%’.


Previous job.



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.



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



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 always uses the ’double’ type with whatever corresponding precision is provided by the compiler and the library.

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 "..."’. The return status is 0 if the arithmetic value of the expression is non−zero, 1 if it is zero, and 2 if an error occurred.

For example, the following statement

(( val = 2 + 1 ))

is equivalent to

let "val = 2 + 1"


Integers can be in bases other than 10. A leading ’0x’ or ’0X’ denotes hexadecimal and a leading ’0b’ or ’0B’ binary. 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.

An integer expression or a base given in the form ’base#n’ may contain underscores (’_’) after the leading digit for visual guidance; these are ignored in computation. Examples are 1_000_000 or 0xffff_ffff which are equivalent to 1000000 and 0xffffffff respectively.

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 $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.


setopt cbases

outputs ’0x1_0000_0000’.


zmodload zsh/mathfunc

outputs ’3_162.277_660_168_379_5’ (the number of decimal places shown may vary).

If the C_BASES option is set, hexadecimal numbers are output 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.



+ − ! ~ ++ −−


<< >>

bitwise shift left, right


bitwise AND


bitwise XOR


bitwise OR



* / %

multiplication, division, modulus (remainder)

+ −

addition, subtraction

< > <= >=


== !=

equality and inequality


logical AND

|| ^^

logical OR, XOR

? :

ternary operator




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.

+ − ! ~ ++ −−




* / %

multiplication, division, modulus (remainder)

+ −

addition, subtraction

<< >>

bitwise shift left, right

< > <= >=


== !=

equality and inequality


bitwise AND


bitwise XOR


bitwise OR


logical AND


logical XOR


logical OR

? :

ternary operator




comma operator

Note the precedence of exponentiation in both cases is below that of unary operators, hence ’−3**2’ evaluates as ’9’, not ’−9’. Use parentheses where necessary: ’−(3**2)’. This is for compatibility with other shells.

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 value of this character and an expression of the form ’#name’ gives the value of the first character of the contents of the parameter name. Character values are according to the character set used in the current locale; for multibyte character handling the option MULTIBYTE must be set. Note that this form is different from ’$#name’, a standard parameter substitution which gives the length of the parameter name. ’#\’ is accepted instead of ’##’, but its use is deprecated.


((val2 = val1 * 2))



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 towards zero except for ’~’ which rounds down.




# use $f

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.



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’.)

When no option named option exists, and the POSIX_BUILTINS option hasn’t been set, return 3 with a warning. If that option is set, return 1 with no warning.

−p file


−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


−u file

true if file exists and has its setuid bit set.

−v varname

true if shell variable varname is set.

−w file

true if file exists and is writable by current process.

−x file


−z string

true if length of string is zero.

−L file

true if file exists and is a symbolic link.

−O file


−G file


−S file

true if file exists and is a socket.

−N file


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


string = pattern
== pattern

true if string matches pattern. The two forms are exactly equivalent. The ’=’ form is the traditional shell syntax (and hence the only one generally used with the test and [ builtins); the ’==’ form provides compatibility with other sorts of computer language.

string != pattern

true if string does not match pattern.

string =~ regexp


If the option BASH_REMATCH is not set the scalar parameter MATCH is set to the substring that matched the pattern and the integer parameters MBEGIN and MEND to the index of the start and end, respectively, of the match in string, such that if string is contained in variable var the expression ’${var[$MBEGIN,$MEND]}’ is identical to ’$MATCH’. The setting of the option KSH_ARRAYS is respected. Likewise, the array match is set to the substrings that matched parenthesised subexpressions and the arrays mbegin and mend to the indices of the start and end positions, respectively, of the substrings within string. The arrays are not set if there were no parenthesised subexpresssions. For example, if the string ’a short string’ is matched against the regular expression ’s(...)t’, then (assuming the option KSH_ARRAYS is not set) MATCH, MBEGIN and MEND are ’short’, 3 and 7, respectively, while match, mbegin and mend are single entry arrays containing the strings ’hor’, ’4’ and ’6’, respectively.


string1 < string2


string1 > string2


exp1 −eq exp2

true if exp1 is numerically equal to exp2. Note that for purely numeric comparisons use of the ((...)) builtin described in the section ’ARITHMETIC EVALUATION’ is more convenient than conditional expressions.

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.

For compatibility, if there is a single argument that is not syntactically significant, typically a variable, the condition is treated as a test for whether the expression expands as a string of non−zero length. In other words, [[ $var ]] is the same as [[ −n $var ]]. It is recommended that the second, explicit, form be used where possible.




For example,

[[ −n file*(#qN) ]]

produces status zero if and only if there is at least one file in the current directory beginning with the string ’file’. The globbing qualifier N ensures that the expression is empty if there is no matching file.

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.


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 sequences undergo a special form of expansion. This type of expansion is also available using the −P option to the print builtin.


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. Many escapes are followed by a single character, although some of these take an optional integer argument that should appear between the ’%’ and the next character of the sequence. More complicated escape sequences are available to provide conditional expansion.


Special characters


A ’%’.


A ’)’.

Login information


The line (tty) the user is logged in on, without ’/dev/’ prefix. If the name starts with ’/dev/tty’, that prefix is stripped.


The full machine hostname.


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.




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 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.


The status of the parser in reverse. This is the same as ’%_’ other than the order of strings. It is often used in RPS2.



Current working directory. If an integer follows the ’%’, it specifies a number of trailing components of the current working directory 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 the current working directory starts with $HOME, that part is replaced by a ’~’. Furthermore, if it has a named directory as its prefix, that part is replaced by a ’~’ followed by the name of the directory, but only if the result is shorter than the full path; see Dynamic and Static named directories in zshexpn(1).





Current history event number.






The number of jobs.


The current value of $SHLVL.


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.






Trailing component of the current working directory. 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


The date in yymmdd format.


Current time of day, in 24−hour format.



Current time of day, in 12−hour, am/pm format.


Current time of day in 24−hour format, with seconds.


The date in daydd format.


The date in mm/dd/yy format.




a day of the month


the hour of the day on the 24−hour clock


the hour of the day on the 12−hour clock

In addition, if the system supports the POSIX gettimeofday system call, %. provides decimal fractions of a second since the epoch with leading zeroes. By default three decimal places are provided, but a number of digits up to 9 may be given following the %; hence %6. outputs microseconds, and %9. outputs nanoseconds. (The latter requires a nanosecond−precision clock_gettime; systems lacking this will return a value multiplied by the appropriate power of 10.) A typical example of this is the format ’%D{%H:%M:%S.%.}’.


Additionally, the GNU extension that a ’’ between the % and the format character causes a leading zero or space to be stripped is handled directly by the shell for the format characters d, f, H, k, l, m, M, S and y; any other format characters are provided to the system’s strftime(3) with any leading ’’ present, so the handling is system dependent. Further GNU (or other) extensions are also passed to strftime(3) and may work if the system supports them.

Visual effects

Start (stop) boldface mode.


Clear to end of line.

%U (%u)

Start (stop) underline mode.

%S (%s)

Start (stop) standout mode.

%F (%f)


%K (%k)






Within a %{...%} sequence, include a ’glitch’: that is, assume that a single character width will be output. This is useful when outputting characters that otherwise cannot be correctly handled by the shell, such as the alternate character set on some terminals. The characters in question can be included within a %{...%} sequence together with the appropriate number of %G sequences to indicate the correct width. An integer between the ’%’ and ’G’ indicates a character width other than one. Hence %{seq%2G%} outputs seq and assumes it takes up the width of two standard characters.





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.


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, except as noted below for ’l’. 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.











True if the day of the month is equal to n.


True if the evaluation depth is at least n.


True if the effective gid of the current process is n.


True if the number of jobs is at least n.


True if the SHLVL parameter is at least n.




True if the SECONDS parameter is at least n.


True if the time in hours is equal to n.


True if the time in minutes is equal to n.


True if the array psvar has at least n elements.


True if element n of the array psvar is set and non−empty.




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 string will be displayed in place of the truncated portion of any string; note this does not undergo prompt expansion.


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


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

Truncation applies only within each individual line of the prompt, as delimited by embedded newlines (if any). If the total length of any line of the prompt after truncation is greater than the terminal width, or if the part to be truncated contains embedded newlines, truncation behavior is undefined and may change in a future version of the shell. Use ’%−n(l.true−text.false−text)’ to remove parts of the prompt when the available space is less than n.