ZSHMISC(1)

๐Ÿ‘‘ ZSHMISC(1) โ€” the manual page, but make it make sense ๐Ÿ’…

okay bestie, so this is zshmisc from the General Commands Manual โ€” yes the whole "everything and then some" situation โ€” and no cap, that tagline is literally the name description. buckle up ๐ŸŽ€


๐ŸŒธ NAME ๐ŸŒธ

zshmisc โ€” everything and then some. fr fr, that's the whole description. iconic of them honestly.


โœจ SIMPLE COMMANDS & PIPELINES โœจ

๐Ÿซถ the humble simple command

so a simple command is: some optional parameter assignments (peep the start of zshparam(1) for what assignment actually means), then blank-separated words, with optional redirections sprinkled in wherever. it's giving chaos but organized ๐Ÿ’…

the first word is the command to be executed, and every word after it is an argument to that command. if there's a command name given, those parameter assignments modify the environment of the command when it runs. the value of a simple command is its exit status โ€” or 128 plus the signal number if it got terminated by a signal ๐Ÿ˜ญ

example time:

echo foo

that's a simple command with arguments. slay.

๐Ÿฆ‹ pipelines

a pipeline is either one simple command, or two-or-more simple commands each separated from the next by | or |&.

  • with | โ€” the standard output of the first command gets connected to the standard input of the next
  • with |& โ€” that's shorthand for 2>&1 |, which connects both the standard output and the standard error of the command to the standard input of the next. double the vibe, same pipe ๐Ÿ”ฅ

the value of a pipeline is the value of the last command, unless ! comes before the pipeline โ€” then it's the logical inverse of the value of the last command.

echo foo | sed 's/foo/bar/'

that's a pipeline, where the output of the first command (foo plus a newline) gets passed to the input of the second. ate.

๐Ÿ’€ coproc moment

if a pipeline is preceded by coproc, it runs as a coprocess โ€” a two-way pipe gets established between it and the parent shell. the shell can read from or write to the coprocess using the >&p and <&p redirection operators, or with print -p and read -p.

โš ๏ธ heads up bestie: a pipeline cannot be preceded by both coproc and !. pick a lane ๐Ÿ™ˆ

if job control is active, the coprocess can be treated as an ordinary background job for things other than input and output.

๐ŸŒˆ sublists

a sublist is either a single pipeline, or two-or-more pipelines separated by && or ||.

  • && โ€” the second pipeline only runs if the first succeeds (returns a zero status)
  • || โ€” the second only runs 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. periodt.

dmesg | grep panic && print yes

that's a sublist of two pipelines โ€” the second is just a simple command, and it runs if and only if the grep command returns a zero status. if it doesn't, the value of the sublist is that return status; otherwise it's the status returned by the print (almost certainly zero, obviously ๐Ÿ’…).

๐ŸŽ€ lists

a list is zero or more sublists, where each sublist is terminated by ;, &, &|, &!, or a newline.

  • that terminator can optionally be left off the last sublist when the list shows up as a complex command inside (...) or {...}
  • terminate with ; or a newline โ†’ the shell waits for it to finish before running the next sublist
  • terminate with &, &|, 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. zsh said "just the last pipeline, bestie."

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 shows up in later descriptions. for example, the commands in a shell function form a special sort of list. iykyk.


๐Ÿ”ฅ PRECOMMAND MODIFIERS ๐Ÿ”ฅ

a simple command may be preceded by a precommand modifier, which alters how the command gets interpreted. these modifiers are shell builtin commands โ€” with the exception of nocorrect, which is a reserved word. the way that distinction matters, honestly ๐Ÿ’œ

  • - โ€” the command is executed with a - prepended to its argv[0] string. tiny dash, big energy.
  • builtin โ€” the command word is taken to be the name of a builtin command, rather than a shell function or external command.
  • 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's equivalent to whence -v. multitasking icon ๐Ÿ’…
  • 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, treating 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.
    • the -a option is used to explicitly specify the argv[0] string (the name of the command as seen by the process itself) to be used by the replacement command, and is directly equivalent to setting a value for the ARGV0 environment variable.
  • nocorrect โ€” spelling correction is not done on any of the words. this must appear before any other precommand modifier, since it's interpreted immediately, before any parsing is done. it has no effect in non-interactive shells. ๐Ÿงš
  • noglob โ€” filename generation (globbing) is not performed on any of the words.

more coming bestie, don't go anywhere ๐Ÿ’–

๐Ÿ’– COMPLEX COMMANDS ๐Ÿ’–

okay so a complex command in zsh is literally one of these, bestie:

๐ŸŒธ if โ€” choose-your-own-adventure energy

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 status is zero, the then list is executed. If each elif list returns nonzero status, the else list is executed.

๐ŸŒธ for name ... โ€” the classic loop, sheโ€™s iconic

for name ... [ in word ... ] term do list done

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.

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 (( ... )) โ€” the arithmetic loop, math girlie edition

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 โ€” keep going while itโ€™s giving zero

while list do list done

Execute the do list as long as the while list returns a zero exit status.

๐ŸŒธ until โ€” keep going while itโ€™s giving nonzero

until list do list done

Execute the do list as long as the until list returns a nonzero exit status.

๐ŸŒธ repeat โ€” say it n times, periodt

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.

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.

๐ŸŒธ case โ€” pattern matching with main character energy

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.

Note further that, unless the SH_GLOB option is set, the whole pattern with alternatives is treated by the shell as equivalent to a group of patterns within parentheses, although white space may appear about the parentheses and the vertical bar and will be stripped from the pattern at those points. White space may appear elsewhere in the pattern; this is not stripped. If the SH_GLOB option is set, so that an opening parenthesis can be unambiguously treated as part of the case syntax, the expression is parsed into separate words and these are treated as strict alternatives (as in other shells).

If the list that is executed is terminated with ;& rather than ;;, the following list is also executed. The rule for the terminator of the following list ;;, ;& or ;| is applied unless the esac is reached.

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.

๐ŸŒธ select โ€” the menu loop, very interactive bestie

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 ) โ€” subshell moment

( list )

Execute list in a subshell. Traps set by the trap builtin are reset to their default values while executing list; an exception is that ignored signals will continue to be ignored if the option POSIXTRAPS is set.

๐ŸŒธ { list } โ€” just run it, no drama

{ list }

Execute list.

๐Ÿฆ‹ { try-list } always { always-list } โ€” the โ€œno matter what, bestieโ€ block

{ try-list } always { always-list }

First execute try-list. Regardless of errors, or break or continue 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 or continue 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 preceding 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 try-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.

When a try block occurs outside of any function, a return or an exit encountered in try-list does not cause the execution of always-list. Instead, the shell exits immediately after any EXIT trap has been executed. Otherwise, a return command encountered in try-list will cause the execution of always-list, just like break and continue.

๐Ÿ‘‘ function โ€” define it, name it, slay it

function [ -T ] 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.

The options of function have the following meanings:

  • -T โ€” Enable tracing for this function, as though with functions -T. See the documentation of the -f option to the typeset builtin, in zshbuiltins(1).

If the option SH_GLOB is set for compatibility with other shells, then whitespace may appear 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.

In any of the forms above, a redirection may appear outside the function body, for example

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

The redirection is stored with the function and applied whenever the function is executed. Any variables in the redirection are expanded at the point the function is executed, but outside the function scope.

โฐ time [ pipeline ] โ€” clock the vibe

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 ]] โ€” conditional expression, truth check

[[ exp ]]

Evaluates the conditional expression exp and returns a zero exit status if it is true. See the section Conditional Expressions for a description of exp.

โœจ ALTERNATE FORMS FOR COMPLEX COMMANDS โœจ

ok so listen up bestie, because zsh has these alternate forms for a bunch of its complex commands and they areโ€ฆ a lot. ๐Ÿซถ These are non-standard and honestly even seasoned shell programmers probably won't clock what they're looking at. So like, do NOT use these anywhere you care about portability, okay? Please. I'm begging.

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 those cases the test part of the loop has to be suitably delimited too, like with [[ ... ]] or (( ... )) โ€” otherwise the shell literally cannot find where the test ends. ๐Ÿ˜ญ For for, repeat, case and select, no such special form for the arguments is necessary, but the other condition (special form of sublist or SHORT_LOOPS being on) still applies. There's also the SHORT_REPEAT option which enables the short version only for the repeat command. โญ

  • if list { list } [ elif list { list } ] ... [ else { list } ] โ€” an alternate form of if. The rules mean this works:
if [[ -o ignorebraces ]] {
  print yes
}

but this absolutely does not:

if true {  # Does not work!
  print yes
}

because the test isn't suitably delimited. ๐Ÿ’€

  • if list sublist โ€” a short form of the alternate if. Same limitations on the form of list as the previous one, no cap.
  • 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. yes, foreach. we love a csh moment. ๐Ÿ™ˆ
  • while list { list } โ€” an alternative form of while. Mind the limitations on the form of list mentioned above, bestie.
  • until list { list } โ€” an alternative form of until. Again: limitations on the form of list mentioned above. ๐Ÿ‘‘
  • repeat word sublist โ€” 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.
  • function word ... [ () ] [ term ] sublist โ€” a short form of function.

๐Ÿ”’ RESERVED WORDS ๐Ÿ”’

These words are recognized as reserved words when they're used as the first word of a command โ€” unless they're quoted, or disabled with disable -r. โœจ

do done esac then elif else fi for case if while function repeat time until select coproc nocorrect foreach end ! [[ { } declare export float integer local readonly typeset

Additionally โ€” and this is the cute little bonus rule โ€” } is recognized in any position if neither the IGNORE_BRACES option nor the IGNORE_CLOSE_BRACES option is set. ๐ŸŽ€


๐Ÿ’€ ERRORS ๐Ÿ’€

Some errors are treated as fatal by the shell. What that means: in an interactive shell, control returns to the command line; in a non-interactive shell, the shell gets aborted. Periodt. ๐Ÿ”ฅ

In older versions of zsh, a non-interactive shell running a script wouldn't abort completely โ€” it would resume execution at the next command read from the script, skipping the rest of any functions or shell constructs like loops or conditions. That's some somewhat illogical behaviour honestly, but like, if you want it back, you can recover it 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
  • Failures to set or modify variable behaviour with typeset, local, declare, export, integer, float
  • 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 NOMATCH or similar options
  • All file generation errors where the pattern was used to create a multio
  • 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

And if the POSIX_BUILTINS option is set, even more errors associated with shell builtin commands get treated as fatal โ€” as specified by the POSIX standard. yep. that's the vibe check. โญ


๐Ÿ’ฌ COMMENTS ๐Ÿ’ฌ

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. ๐Ÿฆ‹

So like. # bestie this whole line is a vibe and also a no-op. slay.


๐ŸŽ€ ALIASING ๐ŸŽ€

okay this is the good stuff. Every eligible word in the shell input gets checked to see if there's an alias defined for it. If there is, it gets replaced by the text of the alias โ€” but only if it's in command position (i.e. it could be the first word of a simple command), or if the alias is a global alias. ๐ŸŒˆ And here's the cute detail: if the replacement text ends with a space, the next word in the shell input is always eligible for alias expansion purposes. iykyk.

It's an error for the function name, word, in the sh-compatible function definition syntax word () ... to be a word that resulted from alias expansion โ€” unless the ALIAS_FUNC_DEF option is set. ๐Ÿ™ˆ

You define an alias with the alias builtin; global aliases can be defined with the -g option to that builtin. ๐Ÿ’…

A word is defined as:

  • Any plain string or glob pattern
  • Any quoted string, using any quoting method (note that the quotes must be part of the alias definition for this to be eligible!)
  • Any parameter reference or command substitution
  • Any series of the foregoing, concatenated without whitespace or other tokens between them
  • Any reserved word (case, do, else, etc.)
  • With global aliasing, any command separator, any redirection operator, and ( or ) when not part of a glob pattern

Alias expansion happens on the shell input before any other expansion except history expansion. So if an alias is defined for the word foo, you can dodge alias expansion by quoting part of the word, like \foo. Any form of quoting works โ€” though ngl, there's nothing stopping someone from defining an alias for the quoted form like \foo as well. ๐Ÿ’€

In particular, note that you must quote when using unalias to remove global aliases:

% alias -g foo=bar
% unalias foo
unalias: no such hash table element: bar
% unalias \foo
%

When POSIX_ALIASES is set, only plain unquoted strings are eligible for aliasing. The alias builtin does not reject ineligible aliases โ€” they just don't get expanded. rude but okay. ๐Ÿ™ƒ

And 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

So although aliases can be used in ways that bend normal shell syntax all the way backwards, not every string of non-white-space characters can be used as an alias. ๐Ÿ˜ญ

Any set of characters not listed as a word above is not a word, hence no attempt is made to expand it as an alias โ€” no matter how it's defined (i.e. via the builtin, or via the special parameter aliases described in the section THE ZSH/PARAMETER MODULE in zshmodules(1)). However, as noted in the case of POSIX_ALIASES above, the shell doesn't try to deduce whether the string corresponds to a word at the time the alias is created. ๐Ÿ’…

For example: an expression containing an = at the start of a command line is an assignment and cannot be expanded as an alias; a lone = is not an assignment but can only be set as an alias using the parameter โ€” because otherwise the = gets taken as part of the syntax of the builtin command. ๐Ÿ™ˆ

It is not presently possible to alias the (( token that introduces arithmetic expressions, because until a full statement has been parsed, it can't 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. Same deal for \<<, \>|, etc. ๐Ÿ˜ญ

There's a commonly encountered problem with aliases, illustrated by this code:

alias echobar='echo bar'; echobar

This prints a message that the command echobar could not be found. Why? Because aliases are expanded when the code is read in โ€” the entire line is read in one go, so by the time echobar is executed it's way 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 functions rather than aliases in non-interactive code. that's the takeaway, bestie. ๐Ÿซถ


๐ŸŒธ QUOTING ๐ŸŒธ

A character can be quoted (that is, made to stand for itself) by putting a \ in front of it. And \ 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 gets 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. iconic behaviour honestly. ๐Ÿ‘‘

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

๐Ÿ”ฅ REDIRECTION ๐Ÿ”ฅ

okay so bestie, redirect town ๐Ÿ’… 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. It is an error to open a file in this fashion if it does not exist.
  • <> 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, regardless of CLOBBER.
  • >> word โ€” open file word for writing in append mode as standard output. If the file does not exist, and the CLOBBER and APPEND_CREATE options are both 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, regardless of CLOBBER and APPEND_CREATE.
  • <<[-] word โ€” here-doc time, and itโ€™s giving main character energy ๐Ÿ˜ญ 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. The result will have a trailing newline after it.
  • <& 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 |.

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


๐ŸŽ€ OPENING FILE DESCRIPTORS USING PARAMETERS ๐ŸŽ€

When the shell is parsing arguments to a command, and the shell option IGNORE_BRACES is not set, a different form of redirection is allowed: instead of a digit before the operator there is a valid shell identifier enclosed in braces. The shell will open a new file descriptor that is guaranteed to be at least 10 and set the parameter named by the identifier to the file descriptor opened. No whitespace is allowed between the closing brace and the redirection character. For example:

... {myfd}>&1

This opens a new file descriptor that is a duplicate of file descriptor 1 and sets the parameter myfd to the number of the file descriptor, which will be at least 10. The new file descriptor can be written to using the syntax >&$myfd. The file descriptor remains open in subshells and forked external executables.

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.

It is an error to open or close a file descriptor in this fashion when the parameter is readonly. However, it is not an error to read or write a file descriptor using <&$param or >&$param if param is readonly.

If the option CLOBBER is unset, it is an error to open a file descriptor using a parameter that is already set to an open file descriptor previously allocated by this mechanism. Unsetting the parameter before using it for allocating a file descriptor avoids the error.

Note that this mechanism merely allocates or closes a file descriptor; it does not perform any redirections from or to it. It is usually convenient to allocate a file descriptor prior to use as an argument to exec. The syntax does not in any case work when used around complex commands such as parenthesised subshells or loops, where the opening brace is interpreted as part of a command list to be executed in the current shell.

The following shows a typical sequence of allocation, use, and closing of a file descriptor:

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

Note that the expansion of the variable in the expression >&$myfd occurs at the point the redirection is opened. This is after the expansion of command arguments and after any redirections to the left on the command line have been processed.

๐ŸŒˆ MULTIOS ๐ŸŒˆ

okay so bestie, this is the part where zsh gets extra in the best way ๐Ÿ’…

If you try to open a file descriptor for writing more than once, the shell opens that fd as a pipe to a process that copies its input to all the outputs you specified โ€” basically tee energy, except it's built in. This happens as long as the MULTIOS option is set, and guess what, it's set by default โœจ So:

date >foo >bar

writes the date to two files, named foo and bar. iconic, no notes ๐ŸŽ€

note that a pipe is an implicit redirection ๐Ÿ™ˆ so this:
date >foo | cat

writes the date to the file foo, and also pipes it to cat.

Also! The shell opens all the files to be used in the multio process immediately, not at the point they're about to be written. keep that in mind bestie โญ

And redirections are always expanded in order. That part happens regardless of whether MULTIOS is set, but with the option on there are extra consequences ๐Ÿ‘€ For example, the meaning of the expression >&1 will change after a previous redirection:

date >&1 >output

In that case, the >&1 refers to the standard output at the start of the line; the result is similar to the tee command. But now consider:

date >output >&1

Since redirections are evaluated in order, when the >&1 is encountered the standard output is set to the file output, and another copy of the output is therefore sent to that file. which isโ€ฆ probably not what you intended ๐Ÿ˜ญ fr fr.

If the MULTIOS option is set, the word after a redirection operator is also subjected to filename generation (globbing) ๐Ÿฆ‹ so:

: > *

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 *.) And similarly, you can do:

echo exit 0 >> *.sh

Now for the reading side ๐Ÿ“– If you try to open a file descriptor for reading more than once, the shell opens the fd as a pipe to a process that copies all the specified inputs to its output in the order specified, provided the MULTIOS option is set. Important caveat though: each file is opened immediately, not at the point where it's about to be read โ€” this behaviour differs from cat, so if you need strictly standard behaviour, use cat instead, periodt ๐Ÿ’…

Thus:

sort <foo <fubar

or even:

sort <f{oo,ubar}

is equivalent to cat foo fubar | sort.

Expansion of the redirection argument occurs at the point the redirection is opened โ€” that's the point described above for the expansion of the variable in >&$myfd ๐Ÿซถ

note that a pipe is an implicit redirection ๐ŸŒธ so cat bar | sort <foo is equivalent to cat bar foo | sort (note the order of the inputs, bestie, the order MATTERS).

If the MULTIOS option is unset, each redirection replaces the previous redirection for that file descriptor. However โ€” plot twist โ€” all files redirected to are actually opened ๐Ÿ˜ณ so:

echo Hello > bar > baz

with MULTIOS unset will truncate bar, and write Hello into baz.


okay now, there's a known problem ๐Ÿ˜ญ when an output multio is attached to an external program. A simple example shows it:

cat file >file1 >file2
cat file1 file2

Here, it's possible that the second cat will not display the full contents of file1 and file2 (i.e. the original contents of file repeated twice). and you'd be like "where did my data go" ๐Ÿ’€

The reason: 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. Which means the command as shown can exit before file1 and file2 are completely written. The workaround? 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. slay ๐ŸŽ€


โœจ 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. it's giving choose-your-own-adventure ๐ŸŒˆ

  • 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. and yes, 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 execution fails: an error message is printed, and one of the following values is returned ๐Ÿ‘‡

  • 127 โ€” The search was unsuccessful. The error message is command not found: cmd.
  • 126 โ€” The executable file has insufficient permissions, is a directory or special file, or is not a script and is in a format unrecognized by the operating system. The exact conditions and error message are operating system-dependent; see execve(2).

If execution fails because the file is not in executable format, and the file is not a directory, it's 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. iykyk ๐Ÿ˜Œ

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 ๐Ÿซถ

watch out though โ€” 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 ๐Ÿ™ˆ important!!

๐Ÿฆ‹ 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 the 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. literally so tidy ๐ŸŒธ

โœจ AUTOLOADING FUNCTIONS โœจ

Okay bestie, so you can mark a function as undefined using the autoload builtin (or functions -u, or typeset -fu). A function like that has literally no body yet. The first time it gets executed, the shell goes looking for its definition using the elements of the fpath variable. So a typical little setup looks like this:

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

The usual alias expansion while reading gets suppressed if the autoload builtin โ€” or its equivalent โ€” is given the -U option. That's the recommended move for functions that ship with the zsh distribution. And heads up: for functions precompiled with the zcompile builtin command, the flag -U must be provided when the .zwc file is created, because that corresponding info gets compiled into it. ๐Ÿ’…

For each element in fpath, the shell checks three possible files, and the newest one wins for loading the function definition:

  • element.zwc โ€” a file created with the zcompile builtin command, expected to contain the definitions for all functions in the directory named element. It's treated the same way as a directory containing files for functions, and it gets searched for the definition of the function. If the definition isn't found there, the search moves on to the other two possibilities below.
    • If element already includes a .zwc extension (like, the extension was explicitly given by you), then element is searched for the function's definition without comparing its age to that of other files. In fact, there doesn't even need to be a directory named element without the suffix. So putting an element like /usr/local/funcs.zwc in fpath speeds up the function search โ€” the tradeoff being that functions included must be explicitly recompiled by hand before the shell notices any changes. ๐Ÿ™ˆ
  • element/function.zwc โ€” a file created with zcompile, expected to contain the definition for function. It may include other function definitions too, but those are neither loaded nor executed; a file found 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.

So in summary, the search order 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 you're hunting, the leftmost in the fpath is chosen; and third, inside a directory, the newer of either a compiled function or an ordinary function definition is used. Slay, that's the whole vibe check. โœจ

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. That normally defines the function in question, but it may also perform initialization, which runs in the context of the function execution and may therefore define local parameters. And 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 lets the file be used directly as an executable shell script. If processing 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. Iconic behavior, honestly. ๐Ÿ’–

It's 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, these two 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. That's 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

๐ŸŒธ ANONYMOUS FUNCTIONS ๐ŸŒธ

If no name is given for a function, it's anonymous and gets 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. Its function name is set to (anon). Main character energy, truly. ๐Ÿ‘‘

Arguments to the function may be specified as words following the closing brace defining the function, so 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 a newline or semicolon is needed to force keyword interpretation. Careful with that, bestie. ๐Ÿ’…

Also note that the argument list of any enclosing script or function is hidden (as would be the case for any other function called at this point).

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, since those do not provide their own local variable scope. ๐Ÿฆ‹

For example:

variable=outside
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're treated as normal function definitions where the definition is silently discarded. Rude, but that's the rule. ๐Ÿ’€โœจ

๐Ÿ’ซ SPECIAL FUNCTIONS ๐Ÿ’ซ

okay so bestie, listen up โ€” some functions in zsh are not like the other functions. If you define them with the right names, the shell treats them like the main character. They have special meaning to the shell. Periodt. ๐Ÿ‘‘


๐Ÿช Hook Functions ๐Ÿช

Okay so here's the cute part. For each of the functions below, you can also define an array with the same name as the function but with _functions slapped on the end. โœจ Any element in that array gets treated as the name of a function to execute โ€” and it runs in the same context, with the same arguments, and with the same initial value of $? as the basic function. So they all vibe together.

Like, for example โ€” if $chpwd_functions is an array containing the values mychpwd, chpwd_save_dirstack, then the shell tries to execute the functions chpwd, mychpwd and chpwd_save_dirstack, in that order. ๐Ÿ’…

Any function that doesn't exist? Silently ignored. No drama. ๐Ÿ™ˆ

A function found by this mechanism is called a hook function elsewhere. And heads up: an error in any function means the subsequent functions don't get run. Also note โ€” an error in a precmd hook causes an immediately following periodic function not to run (though it may run at the next opportunity). ๐Ÿ˜ญ

  • chpwd โ€” runs whenever the current working directory is changed. ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ
  • periodic โ€” if the parameter PERIOD is set, this function runs every $PERIOD seconds, just before a prompt. But listen: if multiple functions are defined using the array periodic_functions, only one period is applied to the complete set of functions, and the scheduled time is not reset if the list of functions is altered. Hence the whole set of functions is always called together. Teamwork, bestie. ๐Ÿซถ
  • precmd โ€” runs before each prompt. Note that precommand functions are not re-executed just because the command line is redrawn โ€” you know, like when a notification about an exiting job gets displayed. So don't come for me about that. ๐Ÿ’…
  • preexec โ€” runs just after a command has been read and is about to be executed. If the history mechanism is active (regardless of whether the line was discarded from the history buffer), the string the user typed is passed as the first argument โ€” otherwise it's an empty string. The actual command that will be executed (including expanded aliases) comes in two different forms: the second argument is a single-line, size-limited version of the command (with things like function bodies elided), and the third argument contains the full text that's being executed. Iconic. ๐Ÿ”ฅ
  • zshaddhistory โ€” runs when a history line has been read interactively, but before it is executed. The sole argument is the complete history line โ€” so any terminating newline will still be present. Bestie, it's raw.
    • 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 โ€” mark that) the history line will not be saved, although it lingers in the history until the next line is executed, letting you 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. ๐Ÿ˜ค
    • A hook function may call fc -p ... to switch the history context so the history gets saved in a different file from the one in the global HISTFILE parameter. This is handled specially: the history context is automatically restored after the processing of the history line is finished. โœจ

The following example function works with one of the options INC_APPEND_HISTORY or SHARE_HISTORY set, in order that the line is written out immediately after the history entry is added. It first adds the history line to the normal history with the newline stripped โ€” which is usually the correct behaviour โ€” then switches the history context so the line gets written to a history file in the current directory. Obsessed with this one honestly:

zshaddhistory() {
  print -sr -- ${1%%$'\n'}
  fc -p .zsh_local_history
}
  • zshexit โ€” runs at the point where the main shell is about to exit normally. This is not called by exiting subshells, nor when the exec precommand modifier is used before an external command. Also, unlike TRAPEXIT, it is not called when functions exit. ๐Ÿ’€

๐Ÿชค Trap Functions ๐Ÿชค

These babies are treated specially too โ€” but plot twist โ€” they do not have corresponding hook arrays. No _functions array for these girlies. ๐ŸŒธ

  • TRAPNAL โ€” if defined and non-null, this function gets 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 status from the function is handled specially. If it's zero, the signal is assumed to have been handled, and execution continues normally. Otherwise, the shell behaves as interrupted โ€” except the return status of the trap is retained. ๐Ÿ‘‘

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

And bestie, important: the functions TRAPZERR, TRAPDEBUG and TRAPEXIT are never executed inside other traps. No nesting shenanigans. ๐Ÿšซ

  • TRAPDEBUG โ€” if the option DEBUG_BEFORE_CMD is set (as it is by default ๐Ÿ‘), it runs before each command; otherwise it runs after each command. See the description of the trap builtin in zshbuiltins(1) for details of additional features provided in debug traps. iykyk.
  • TRAPEXIT โ€” runs when the shell exits, or when the current function exits if defined inside a function. The value of $? at the start of execution is the exit status of the shell or the return status of the function exiting. ๐ŸŽฌ
  • TRAPZERR โ€” runs 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's no SIGERR (which is the usual case). ๐Ÿ˜ญ

The functions beginning TRAP may alternatively be defined with the trap builtin โ€” this may be preferable for some uses. Setting a trap with one form removes any trap of the other form for the same signal; removing a trap in either form removes all traps for the same signal. The forms

TRAPNAL() {
 # code
}

(function traps) and

trap '
 # code
' NAL

(list traps) are equivalent in most ways โ€” the exceptions being the following:

  • Function traps have all the properties of normal functions, appearing in the list of functions and being called with their own function context rather than the context where the trap was triggered. ๐Ÿ’…
  • The return status from function traps is special, whereas a return from a list trap causes the surrounding context to return with the given status. ๐ŸŒ€
  • Function traps are not reset within subshells, in accordance with zsh behaviour; list traps are reset, in accordance with POSIX behaviour. ๐ŸŒˆ

๐Ÿ’… JOBS ๐Ÿ’…

Okay so bestie, if the MONITOR option is set, an interactive shell literally gives every pipeline its own little job. It keeps a whole table of your current jobs (which is what the jobs command prints for you, slay) and hands each one a cute small integer number. When you kick a job off asynchronously with &, the shell prints a line to standard error that looks, no cap, like this:

[1] 1234

which is telling you that the job you just started async is job number 1, it had one (top-level) process, and that process's ID was 1234. Iconic.

If a job gets started with &| or &!, then that job is immediately disowned. Like, right away. After it starts up it has zero place in the job table and it is not subject to any of the job control features we're about to describe. It's giving โœจindependentโœจ.

So you're running a job, and you wanna do something else. Just hit Ctrl+Z (that's ^Z) which sends a TSTP signal to the current job โ€” though heads up, that key can be redefined by the susp option of the external stty command. The shell will then normally be like "bestie, that job has been suspended" and print you another prompt. Then you get to mess with that job's whole state: yeet it into the background with the bg command, or run some other commands and eventually bring it back to the foreground with the foreground command fg. A ^Z takes effect immediately and it's like an interrupt in that pending output and unread input get discarded the moment you type it. ๐Ÿซถ

A job that's running in the background will suspend if it tries to read from the terminal. Rude, but necessary.

โš ๏ธ Note this one, it's important: if the job running in the foreground is a shell function, then suspending it will have the effect of causing the shell to fork. This is necessary to separate the function's state from that of the parent shell doing the job control, so that the parent can get back to the command line prompt. As a result, even if fg is used to continue the job, the function will no longer be part of the parent shell, and any variables set by the function will not be visible in the parent shell. So the behaviour is different from the case where the function was never suspended. Zsh is different from many other shells in this regard. ๐Ÿ˜ญ

One additional side effect: using disown with a job created by suspending shell code in this fashion is delayed โ€” the job can only be disowned once any process started from the parent shell has terminated. At that point, the disowned job disappears silently from the job list. Poof. ๐Ÿ’จ

The same behaviour shows up when the shell is executing code as the right hand side of a pipeline or any complex shell construct like if, for, etc., all so the entire block of code can be managed as a single job. Background jobs are normally allowed to produce output, but you can disable that by giving the command stty tostop. If you set this tty option, then background jobs will suspend when they try to produce output, exactly like they do when they try to read input.

When a command is suspended and then continued later with the fg or wait builtins, zsh restores the 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's 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 these:

  • %number โ€” the job with the given number.
  • %string โ€” the last job whose command line begins with string.
  • %?string โ€” the last 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 standard output or standard error. iykyk.

When 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'll get warned that You have suspended (running) jobs. You can use the jobs command to see what they are. If you do that, 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(1) command or the disown builtin. Protect your faves, fr fr.


โšก 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. The shell itself always ignores the QUIT signal โ€” it's just built different. Otherwise, signals have the values inherited by the shell from its parent (but bestie, see the TRAPNAL special functions in the section Functions).

Certain jobs are run asynchronously by the shell other than those you explicitly put into the background. Even in cases where the shell would usually wait for such jobs, an explicit exit command โ€” or exit due to the option ERR_EXIT โ€” will cause the shell to exit without waiting. Examples of such asynchronous jobs are process substitution (see the section PROCESS SUBSTITUTION in the zshexpn(1) manual page) and the handler processes for multios (see the section MULTIOS in the zshmisc(1) manual page). ๐ŸŒˆ

โœจ ARITHMETIC EVALUATION โœจ

Okay bestie, so zsh is out here doing math โ€” both integer and floating point โ€” and there are two ways to make it happen: the builtin let, or the substitution form $((...)). For integers, the shell is usually compiled to use 8-byte precision where that's available; otherwise precision is 4 bytes. Wanna test it? Run print - $(( 12345678901 )) โ€” if the number comes back unchanged, your precision is at least 8 bytes. Floating point arithmetic always uses the double type with whatever corresponding precision the compiler and the library provide. ๐Ÿ’…

The let builtin command takes arithmetic expressions as arguments; each one is evaluated separately. And because so many of the arithmetic operators โ€” plus spaces โ€” require quoting, there's a glow-up alternative form: for any command that begins with a ((, all the characters until a matching )) are treated as a double-quoted expression and arithmetic expansion is 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. Iconic. ๐ŸŽ€

So for example, this statement:

(( val = 2 + 1 ))

is literally equivalent to:

let "val = 2 + 1"

Both of them assign the value 3 to the shell variable val and return a zero status. Slay. โœจ


๐Ÿฆ‹ Bases, bestie

Integers can be in bases other than 10, no cap:

  • A leading 0x or 0X denotes hexadecimal.
  • A leading 0b or 0B denotes 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. So aesthetic. ๐Ÿ’–


๐ŸŒธ Output bases and the whole [#base] situation

You can also 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's recommended that it appear at the beginning of an expression. Example time:

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

This 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. The way that works out is lowkey gorgeous. ๐ŸŒˆ


๐Ÿงš Grouping with underscores

The base may be replaced or followed by an underscore, which may itself be followed by a positive integer (if it's missing, the value 3 is used). This indicates that underscores should be inserted into the output string, grouping the number for visual clarity. The following integer specifies the number of digits to group together. For example:

setopt cbases
print $(( [#16_4] 65536 ** 2 ))

outputs 0x1_0000_0000. Obsessed. ๐Ÿ’…

This feature can be used with floating point numbers too, in which case the base must be omitted; grouping is away from the decimal point. For example:

zmodload zsh/mathfunc
print $(( [#_] sqrt(1e7) ))

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


โญ C_BASES and OCTAL_ZEROES

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. Noted, bestie. ๐Ÿซถ

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 be, because it will be taken for a parameter name. All numeric parts (before and after the decimal point and in the exponent) may contain underscores after the leading digit for visual guidance; these are ignored in computation.


๐Ÿ‘‘ Operators: native mode

An arithmetic expression uses nearly the same syntax and associativity of expressions as in C.

In the native mode of operation, the following operators are supported โ€” listed in decreasing order of precedence, so the top ones bind tightest, iykyk:

  • + - ! ~ ++ -- โ€” 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. Also, note the precedence of the bitwise AND, OR, and XOR operators. ๐Ÿ‘€


๐ŸŒบ Operators: C_PRECEDENCES mode

With the option C_PRECEDENCES, the precedences (but no other properties) of the operators are altered to be the same as those in most other languages that support the relevant operators:

  • + - ! ~ ++ -- โ€” unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement
  • ** โ€” exponentiation
  • * / % โ€” multiplication, division, modulus (remainder)
  • + - โ€” addition, subtraction
  • << >> โ€” bitwise shift left, right
  • < > <= >= โ€” comparison
  • == != โ€” equality and inequality
  • & โ€” bitwise AND
  • ^ โ€” bitwise XOR
  • | โ€” bitwise OR
  • && โ€” logical AND
  • ^^ โ€” logical XOR
  • || โ€” logical OR
  • ? : โ€” ternary operator
  • = += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **= โ€” assignment
  • , โ€” 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. ๐Ÿ’€

๐Ÿ“ Math functions

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. That's your plug-in era. ๐Ÿ”ฅ

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 โ€” so like, don't. ๐Ÿ™ˆ

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. Cute. ๐ŸŽ€


๐Ÿ’– Integer and float variables

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

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. ๐Ÿ’…


๐Ÿฆ‹ The big warning (read this, bestie)

Users should beware that, in common with many other programming languages but not software designed for calculation, the evaluation of an expression in zsh is taken a term at a time, and promotion of integers to floating point does not occur in terms only containing integers. A typical result of this is that a division such as 6/8 is truncated, in this being rounded towards 0. The FORCE_FLOAT shell option can be used in scripts or functions where floating point evaluation is required throughout. ๐Ÿ˜ญ

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. Periodt. ๐Ÿ‘‘

๐Ÿ’… CONDITIONAL EXPRESSIONS ๐Ÿ’…

So [[ is the compound command that does the vibe check on files and strings, okay? And each expression inside it gets built out of one or more of these unary or binary bits โ€” here's the whole menu, no skips:

  • -a file โ€” true if file exists. That's it. It's there. Slay.
  • -b file โ€” true if file exists and is a block special file. (Yes, the blocky kind ๐Ÿงฑ)
  • -c file โ€” true if file exists and is a character special file.
  • -d file โ€” true if file exists and is a directory. Folder core ๐Ÿ“
  • -e file โ€” true if file exists. (Yeah bestie, -a and -e both do this, don't come for me)
  • -f file โ€” true if file exists and is a regular file. Just a normal lil file, no drama โœจ
  • -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. Sticky. Like your screen after a slushie ๐Ÿ“
  • -n string โ€” true if the length of string is non-zero. Non-empty = valid, periodt.
  • -o option โ€” true if the option named option is on. The option can be a single character, in which case it's a single letter option name. (Check the section Specifying Options, iykyk.)

And listen, this part matters: when no option named option exists, and the POSIX_BUILTINS option hasn't been set, it returns 3 with a warning ๐Ÿ˜ญ. If that option is set, it returns 1 with no warning. Big difference, don't sleep on it.

  • -p file โ€” true if file exists and is a FIFO special file (a named pipe).
  • -r file โ€” true if file exists and is readable by the 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, don't try it.
  • -u file โ€” true if file exists and has its setuid bit set.
  • -v varname โ€” true if the shell variable varname is set. Variable check, lowkey useful.
  • -w file โ€” true if file exists and is writable by the current process.
  • -x file โ€” true if file exists and is executable by the current process. And if file exists and is a directory, then the current process has permission to search in the directory. ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • -z string โ€” true if the length of string is zero. Empty girlie check ๐Ÿ’€
  • -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.

Now the binary file comparisons, two files entering the chat:

  • 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. Same file energy ๐Ÿซถ

String comparisons, the main character section ๐ŸŽ€

  • string = pattern
  • string == pattern

true if string matches pattern. The two forms are exactly equivalent โ€” no cap. 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. Both valid, pick your fighter.

  • string != pattern โ€” true if string does not match pattern. The hater check.
  • string =~ regexp โ€” true if string matches the regular expression regexp.

Okay this one's a whole thing, buckle up. If the option RE_MATCH_PCRE is set, regexp is tested as a PCRE regular expression using the zsh/pcre module; else it's tested as a POSIX extended regular expression using the zsh/regex module. Upon successful match, some variables will be updated; no variables are changed if the matching fails. ๐Ÿ™…โ€โ™€๏ธ

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

Example time, because honestly same: 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. Obsessed with how clean that is ngl.

If the option BASH_REMATCH is set, the array BASH_REMATCH is set to the substring that matched the pattern, followed by the substrings that matched parenthesised subexpressions within the pattern.

  • string1 < string2 โ€” true if string1 comes before string2 based on the ASCII value of their characters.
  • string1 > string2 โ€” true if string1 comes after string2 based on the ASCII value of their characters.

Numeric comparisons โœจ

  • exp1 -eq exp2 โ€” true if exp1 is numerically equal to exp2. โš ๏ธ heads up though: for purely numeric comparisons, use of the ((...)) builtin described in the section ARITHMETIC EVALUATION is more convenient than conditional expressions. Do with that what you will.
  • 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.

Logic glue ๐Ÿงš

  • ( exp ) โ€” true if exp is true. Parens, iconic.
  • ! exp โ€” true if exp is false. The negate era.
  • 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. Bestie, be explicit. It's a whole vibe.

Normal shell expansion is performed on the file, string and pattern arguments, but here's the catch โ€” the result of each expansion is constrained to be a single word, similar to the effect of double quotes. One word only, no plus-ones.

Filename generation is not performed on any form of argument to conditions. However ๐Ÿ˜Œ, it can be forced in any case where normal shell expansion is valid and when the option EXTENDED_GLOB is in effect, by using an explicit glob qualifier of the form (#q) at the end of the string. A normal glob qualifier expression may appear between the q and the closing parenthesis; if none appears, the expression has no effect beyond causing filename generation. The results of filename generation are joined together to form a single word, as with the results of other forms of expansion. Clean. Tidy. Slay.

This special use of filename generation is only available with the [[ syntax. If the condition occurs within the [ or test builtin commands, then globbing occurs instead as part of normal command line expansion before the condition is evaluated. In this case it may generate multiple words, which are likely to confuse the syntax of the test command. ๐Ÿ˜ญ So like, don't.

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. Neat trick, keep it in your back pocket ๐Ÿซถ

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. Important distinction, don't mix it up.

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. Magic-ish, but it's real.

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. Chef's kiss ๐Ÿ”ฅ


๐ŸŒธ EXPANSION OF PROMPT SEQUENCES ๐ŸŒธ

Okay so prompt sequences undergo a special form of expansion. And guess what โ€” this type of expansion is also available using the -P option to the print builtin. Same energy, different door. โœจ

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 !!. Double it up, bestie ๐Ÿ’…

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. ๐Ÿ‘‘

๐Ÿ’… SIMPLE PROMPT ESCAPES ๐Ÿ’…

okay so these are the little % codes that make your prompt pop off ๐Ÿ’– theyโ€™re literally the main character energy of your shell prompt, and yes, every one of them matters.

โœจ Special characters โœจ

  • %% โ€” a literal %.
  • %) โ€” a literal ).

๐ŸŽ€ Login information ๐ŸŽ€

  • %l โ€” the line (tty) youโ€™re logged in on, without the /dev/ prefix. If the name starts with /dev/tty, that prefix gets stripped.
  • %M โ€” the full machine hostname.
  • %m โ€” the hostname up to the first .. You can put an integer after the % to say how many components of the hostname you want. With a negative integer, trailing components of the hostname are shown.
  • %n โ€” $USERNAME.
  • %y โ€” the line (tty) youโ€™re logged in on, without the /dev/ prefix. This one does not treat /dev/tty names specially.

๐Ÿฆ‹ Shell state ๐Ÿฆ‹

  • %# โ€” a # if the shell is running with privileges, a % if not. Equivalent to %(!.#.%%). โ€œPrivilegedโ€ here means either the effective user ID is zero, or โ€” if POSIX.1e capabilities are supported โ€” at least one capability is raised in either the Effective or Inheritable capability vectors.
  • %? โ€” the return status 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 you give it an integer, that many strings will be printed; zero, a negative number, or no integer means print as many as there are. 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. Same as %_ except the order of strings is flipped. Often used in RPS2.
  • %d, %/ โ€” 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 โ€” so %-1d specifies the first component.
  • %~ โ€” like %d and %/, but if the current working directory starts with $HOME, that part is replaced by a ~. Also, 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).
  • %e โ€” evaluation depth of the current sourced file, shell function, or eval. This is incremented or decremented every time the value of %N is set or reverted to a previous value, respectively. Most useful for debugging as part of $PS4.
  • %h, %! โ€” current history event number.
  • %i โ€” the line number currently being executed in the script, sourced file, or shell function given by %N. Most useful for debugging as part of $PS4.
  • %I โ€” the line number currently being executed in the file %x. Similar to %i, but the line number is always a line number in the file where the code was defined, even if the code is a shell function.
  • %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 isnโ€™t one, 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.
  • %x โ€” the name of the file containing the source code currently being executed. Behaves like %N except function and eval command names are not shown โ€” instead you get the file where they were defined.
  • %c, %., %C โ€” 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. Heads up: these are deprecated, because %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) for more details. Various zsh extensions provide numbers with no leading zero or space if the number is a single digit:
    • %f โ€” a day of the month
    • %K โ€” the hour of the day on the 24-hour clock
    • %L โ€” 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.%.}.

The GNU extension %N is handled as a synonym for %9..

Additionally, the GNU extension where 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 ๐Ÿ’…

  • %B (%b) โ€” start (stop) boldface mode.
  • %E โ€” clear to end of line.
  • %U (%u) โ€” start (stop) underline mode.
  • %S (%s) โ€” start (stop) standout mode.
  • %F (%f) โ€” start (stop) using a different foreground colour, if supported by the terminal. The colour may be specified two ways: either as a numeric argument, as normal, or by a sequence in braces following the %F, for example %F{red}. In the latter case the values allowed are as described for the fg zle_highlight attribute; see Character Highlighting in zshzle(1). This means numeric colours are allowed in the second format also.
  • %K (%k) โ€” start (stop) using a different bacKground colour. The syntax is identical to that for %F and %f.
  • %{...%} โ€” include a string as a literal escape sequence. The string within the braces should not change the cursor position. Brace pairs can nest.

A positive numeric argument between the % and the { is treated as described for %G below.

  • %G โ€” 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.

Multiple uses of %G accumulate in the obvious fashion; the position of the %G is unimportant. Negative integers are not handled.

Note that when prompt truncation is in use it is advisable to divide up output into single characters within each %{...%} group so that the correct truncation point can be found.

โœจ CONDITIONAL SUBSTRINGS IN PROMPTS โœจ

Okay so this is the part where prompts get spicy โ€” like, actual logic in your prompt string. Buckle up bestie, it's giving brain-expansion time ๐Ÿง โœจ

  • %v โ€” prints the value of the first element of the psvar array parameter. And listen โ€” if you follow the % with an integer, you get that element of the array instead. Negative integers count from the end of the array, because of course they do ๐Ÿ’…
  • %(x.true-text.false-text) โ€” this is a whole ternary expression, right inside your prompt. Iconic.

The character right after the x is arbitrary โ€” you pick it. That same character is what separates the text for the true result from the text for the false result. Important caveat: this separator may not appear in the true-text, except as part of a %-escape sequence. Also, a ) may appear in the false-text, but you have to write it as %). And both true-text and false-text may contain arbitrarily-nested escape sequences, including further ternary expressions. It's ternaries all the way down ๐ŸŒ€

The left parenthesis may be preceded or followed by a positive integer n, which defaults to zero. A negative integer gets multiplied by -1 โ€” except as noted below for l. The test character x can be any of these bad boys:

  • ! โ€” 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.
  • e โ€” true if the evaluation depth is at least 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. When n is negative, true if at least abs(n) characters remain before the opposite margin (thus the left margin for RPROMPT). This is the one with the special negative-number behaviour, remember ๐Ÿ’…
  • 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.
  • V โ€” true if element n of the array psvar is set and non-empty.
  • w โ€” true if the day of the week is equal to n (Sunday = 0).

Now for the truncation girlies โœ‚๏ธโœจ

  • %<string<
  • %>string>
  • %[xstring]

These specify truncation behaviour for the remainder of the prompt string. Heads up: the third form is deprecated ๐Ÿ™ˆ โ€” it's equivalent to %xstringx, i.e. x may be < or >. The string will be displayed in place of the truncated portion of any string โ€” and ngl, note that this does not undergo prompt expansion.

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. In the first two forms, this numeric argument may be negative, in which case the truncation length is determined by subtracting the absolute value of the numeric argument from the number of character positions remaining on the current prompt line. If that gives you a zero or negative length, a length of 1 is used. In other words: a negative argument arranges that after truncation at least n characters remain before the right margin (left margin for RPROMPT). Werk ๐Ÿ’…

The forms with < truncate at the left of the string, and the forms with > truncate at the right of the string. Example time: if the current directory is /home/pike, the prompt %8<..<%/ will expand to ..e/pike. Obsessed.

In this string, the terminating character (<, > or ]), or in fact any character, may be quoted by a preceding \. But โ€” and this is the trap โ€” when using print -P, this must be doubled, because 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 "%<\\\\<<..."

๐Ÿ˜ญ yeah. That's the worst case. You're welcome.

If the string is longer than the specified truncation length, it will appear in full, completely replacing the truncated string. No half-measures, no cap.

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) โ€” whichever 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. Sneaky. And note โ€” %-0<< is not equivalent to %<<; it specifies that the prompt is truncated at the right margin. Different vibe entirely.

Truncation applies only within each individual line of the prompt, as delimited by embedded newlines (if any). And here's the cautionary bit, bestie, so listen up:

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. ๐Ÿ’€

Instead, use %-n(l.true-text.false-text) to remove parts of the prompt when the available space is less than n. Much safer, much slay ๐Ÿซถ


And that's a wrap on ZSHMISC(1)! This absolute unit of a man page is from zsh 5.9.2, dated July 12, 2026, and it lives at ZSHMISC(1) โ€” go forth and make your prompts unreasonably gorgeous, bestie ๐Ÿ’–โœจ๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from