ZSHMODULES(1)
๐ zshmodules(1) โ zsh loadable modules ๐
hey bestie ๐ welcome to zshmodules(1) from the General Commands Manual โ the zsh loadable modules page. Itโs giving โoptional zsh bits, but make it modularโ, and honestly? iconic. ๐ฆ
๐ธ NAME ๐ธ
zshmodules - zsh loadable modules. Short, sweet, slay. ๐
โจ DESCRIPTION โจ
Okay so some optional parts of zsh are in modules, separate from the core of the shell. Each of these modules may be linked in to the shell at build time, or can be dynamically linked while the shell is running if the installation supports this feature. Modules are linked at runtime with the zmodload command, see zshbuiltins(1).
The modules that are bundled with the zsh distribution are:
zsh/attrโ builtins for manipulating extended attributes (xattr). ๐zsh/capโ builtins for manipulating POSIX.1e (POSIX.6) capability (privilege) sets. ๐ฅzsh/cloneโ a builtin that can clone a running shell onto another terminal. ๐ฆzsh/compctlโ thecompctlbuiltin for controlling completion.zsh/completeโ the basic completion code.zsh/complistโ completion listing extensions. ๐zsh/computilโ a module with utility builtins needed for the shell function based completion system.zsh/cursesโ curses windowing commands.zsh/datetimeโ some date/time commands and parameters. โฐzsh/db/gdbmโ builtins for managing associative array parameters tied to GDBM databases.zsh/deltocharโ a ZLE function duplicating EMACS' zap-to-char.zsh/exampleโ an example of how to write a module.zsh/filesโ some basic file manipulation commands as builtins. ๐zsh/langinfoโ interface to locale information.zsh/mapfileโ access to external files via a special associative array.zsh/mathfuncโ standard scientific functions for use in mathematical evaluations. ๐zsh/nearcolorโ map colours to the nearest colour in the available palette. ๐จzsh/newuserโ arrange for files for new users to be installed.zsh/parameterโ access to internal hash tables via special associative arrays.zsh/pcreโ interface to the PCRE library.zsh/param/privateโ builtins for managing private-scoped parameters in function context.zsh/regexโ interface to the POSIX regex library.zsh/schedโ a builtin that provides a timed execution facility within the shell.zsh/net/socketโ manipulation of Unix domain sockets.zsh/statโ a builtin command interface to thestatsystem call.zsh/systemโ a builtin interface to various low-level system features.zsh/net/tcpโ manipulation of TCP sockets.zsh/termcapโ interface to the termcap database.zsh/terminfoโ interface to the terminfo database.zsh/watchโ reporting of login and logout events.zsh/zftpโ a builtin FTP client.zsh/zleโ the Zsh Line Editor, including thebindkeyandvaredbuiltins. ๐zsh/zleparameterโ access to internals of the Zsh Line Editor via parameters.zsh/zprofโ a module allowing profiling for shell functions.zsh/zptyโ a builtin for starting a command in a pseudo-terminal.zsh/zselectโ block and return when file descriptors are ready.zsh/zutilโ some utility builtins, e.g. the one for supporting configuration via styles.
๐ง THE ZSH/ATTR MODULE ๐ง
The zsh/attr module is used for manipulating extended attributes. The -h option causes all commands to operate on symbolic links instead of their targets. The builtins in this module are:
zgetattr [ -h ] filename attribute [ parameter ]โ Get the extended attributeattributefrom the specifiedfilename. If the optional argumentparameteris given, the attribute is set on that parameter instead of being printed to stdout.zsetattr [ -h ] filename attribute valueโ Set the extended attributeattributeon the specifiedfilenametovalue.zdelattr [ -h ] filename attributeโ Remove the extended attributeattributefrom the specifiedfilename.zlistattr [ -h ] filename [ parameter ]โ List the extended attributes currently set on the specifiedfilename. If the optional argumentparameteris given, the list of attributes is set on that parameter instead of being printed to stdout.
zgetattr and zlistattr allocate memory dynamically. If the attribute or list of attributes grows between the allocation and the call to get them, they return 2. On all other errors, 1 is returned. This allows the calling function to check for this case and retry. ๐ซถ
๐ฅ THE ZSH/CAP MODULE ๐ฅ
The zsh/cap module is used for manipulating POSIX.1e (POSIX.6) capability sets. If the operating system does not support this interface, the builtins defined by this module will do nothing. The builtins in this module are:
cap [ capabilities ]โ Change the shell's process capability sets to the specifiedcapabilities, otherwise display the shell's current capabilities.getcap filename ...โ This is a built-in implementation of the POSIX standard utility. It displays the capability sets on each specifiedfilename.setcap capabilities filename ...โ This is a built-in implementation of the POSIX standard utility. It sets the capability sets on each specifiedfilenameto the specifiedcapabilities.
๐ฆ THE ZSH/CLONE MODULE ๐ฆ
The zsh/clone module makes available one builtin command:
clone ttyโ Creates a forked instance of the current shell, attached to the specifiedtty. In the new shell, thePID,PPIDandTTYspecial parameters are changed appropriately.$!is set to zero in the new shell, and to the new shell'sPIDin the original shell.
The return status of the builtin is zero in both shells if successful, and non-zero on error.
The target of clone should be an unused terminal, such as an unused virtual console or a virtual terminal created by
xterm -e sh -c 'trap : INT QUIT TSTP; tty;
while :; do sleep 100000000; done'
Some words of explanation are warranted about this long xterm command line: when doing clone on a pseudo-terminal, some other session ("session" meant as a unix session group, or SID) is already owning the terminal. Hence the cloned zsh cannot acquire the pseudo-terminal as a controlling tty. That means two things:
- the job control signals will go to the sh-started-by-xterm process group (that's why we disable
INT,QUITandTSTPwithtrap; otherwise thewhileloop could get suspended or killed) - the cloned shell will have job control disabled, and the job control keys (
control-C,control-\andcontrol-Z) will not work.
This does not apply when cloning to an unused vc.
Cloning to a used (and unprepared) terminal will result in two processes reading simultaneously from the same terminal, with input bytes going randomly to either process. ๐ญ
clone is mostly useful as a shell built-in replacement for openvt.
๐ THE ZSH/COMPCTL MODULE ๐
The zsh/compctl module makes available two builtin commands. compctl is the old, deprecated way to control completions for ZLE. See zshcompctl(1). The other builtin command, compcall, can be used in user-defined completion widgets, see zshcompwid(1).
๐ THE ZSH/COMPLETE MODULE ๐
The zsh/complete module makes available several builtin commands which can be used in user-defined completion widgets, see zshcompwid(1).
๐ THE ZSH/COMPLIST MODULE ๐
The zsh/complist module offers three extensions to completion listings: the ability to highlight matches in such a list, the ability to scroll through long lists and a different style of menu completion.
๐ Colored completion listings ๐
Whenever one of the parameters ZLS_COLORS or ZLS_COLOURS is set and the zsh/complist module is loaded or linked into the shell, completion lists will be colored. Note, however, that complist will not automatically be loaded if it is not linked in: on systems with dynamic loading, zmodload zsh/complist is required.
The parameters ZLS_COLORS and ZLS_COLOURS describe how matches are highlighted. To turn on highlighting an empty value suffices, in which case all the default values given below will be used. The format of the value of these parameters is the same as used by the GNU version of the ls command: a colon-separated list of specifications of the form name=value. The name may be one of the following strings, most of which specify file types for which the value will be used. The strings and their default values are:
no 0โ for normal text (i.e. when displaying something other than a matched file)fi 0โ for regular filesdi 32โ for directoriesln 36โ for symbolic links. If this has the special valuetarget, symbolic links are dereferenced and the target file used to determine the display format.pi 31โ for named pipes (FIFOs)so 33โ for socketsbd 44;37โ for block devicescd 44;37โ for character devicesor noneโ for a symlink to nonexistent file (default is the value defined forln)mi noneโ for a non-existent file (default is the value defined forfi); this code is currently not usedsu 37;41โ for files with setuid bit setsg 30;43โ for files with setgid bit settw 30;42โ for world writable directories with sticky bit setow 34;43โ for world writable directories without sticky bit setsa noneโ for files with an associated suffix alias; this is only tested after specific suffixes, as described belowst 37;44โ for directories with sticky bit set but not world writableex 35โ for executable fileslc \e[โ for the left code (see below)rc mโ for the right codetc 0โ for the character indicating the file type printed after filenames if theLIST_TYPESoption is setsp 0โ for the spaces printed after matches to align the next columnec noneโ for the end code
Apart from those literal strings, the name can also be an asterisk (*) followed by any string, and the value you give for that gets used for every file whose name ends with that string. Also! The name can be an equals sign (=) followed by a pattern โ and when that happens, the EXTENDED_GLOB option gets turned on just for evaluating the pattern. The value you give for that pattern is used for all matches (not just filenames, like, anything) whose display string the pattern matches. Definitions with the leading equals sign take precedence over the values you defined for file types, which in turn take precedence over the leading-asterisk form (file extensions). Ranking, periodt. ๐
The leading-equals form is also the one that lets you color different parts of a displayed string differently, which is iconic. For that, the pattern has to use the (#b) globbing flag and pairs of parentheses around the parts of the strings you want colored differently. Then your value can be more than one color code separated by equal signs. The first code goes on every part that has no explicit code of its own, and the following codes go on the parts matched by the sub-patterns in parentheses. Example time: the spec =(#b)(?)*(?)=0=3=7 applies to all matches that are at least two characters long, using code 3 for the first character, 7 for the last character, and 0 for everything in between. Chef's kiss. โจ
All three forms of name can be preceded by a pattern in parentheses. When you give that, the value only gets used for matches in groups whose names are matched by the pattern inside the parens. For example, (g*)m*=43 highlights all matches starting with m in groups whose names start with g, using color code 43. But heads up: for the lc, rc, and ec codes, the group pattern gets ignored.
Also ngl, all the patterns are tried in the order they appear in the parameter value, until the first one matches โ and that one gets used. Patterns may match against completions, descriptions (possibly with spaces appended for padding), or lines consisting of a completion followed by a description. For consistent coloring you might need more than one pattern, or a pattern with backreferences.
When it prints a match, the code prints: the value of lc, then the value for the file-type or the last matching specification with a *, then the value of rc, then the string to display for the match itself, and then the value of ec if that's defined โ or the values of lc, no, and rc if ec isn't defined.
The default values are ISO 6429 (ANSI) compliant ๐ and work on vt100 compatible terminals such as xterms. On monochrome terminals the default values have no visible effect (sad, but true). The colors function from the contribution can give you associative arrays containing the codes for ANSI terminals (peep the section Other Functions in zshcontrib(1)). So like, after loading colors, you could use $color[red] for the code for foreground color red, and $color[bg-green] for the code for background color green. Slay.
๐ If the completion system invoked bycompinitis used, do not set these parameters directly, because the system controls them itself. Use thelist-colorsstyle instead (see the sectionCompletion System Configurationinzshcompsys(1)). Fr fr.
๐ Scrolling in completion listings ๐
To enable scrolling through a completion list, the LISTPROMPT parameter must be set. Its value gets used as the prompt; if it's the empty string, a default prompt is used instead. The value may contain escapes of the form %x. It supports the escapes %B, %b, %S, %s, %U, %u, %F, %f, %K, %k and %{...%} โ same ones used in shell prompts โ plus three extra pairs of sequences:
- a
%lor%Lgets replaced by the number of the last line shown and the total number of lines, in the formnumber/total - a
%mor%Mgets replaced with the number of the last match shown and the total number of matches - a
%por%Pgets replaced withTop,Bottom, or the position of the first line shown as a percent of the total number of lines, respectively
And in each of those cases, the uppercase version gets replaced with a string of fixed width, padded to the right with spaces, while the lowercase version doesn't get padded. Cute little detail. ๐
If LISTPROMPT is set, the completion code will not ask whether the list should be shown. It just immediately starts displaying the list, stops after the first screenful, shows the prompt at the bottom, and waits for a keypress after temporarily switching to the listscroll keymap. Some of the zle functions have special meaning while scrolling lists:
send-breakโ stops listing, discarding the key pressedaccept-line,down-history,down-line-or-history,down-line-or-search,vi-down-line-or-historyโ scrolls forward one linecomplete-word,menu-complete,expand-or-complete,expand-or-complete-prefix,menu-complete-or-expandโ scrolls forward one screenfulaccept-searchโ stops listing but takes no other action
Every other character stops listing and immediately processes the key as usual. Any key that isn't bound in the listscroll keymap, or that's bound to undefined-key, gets looked up in the keymap currently selected.
Same deal as with ZLS_COLORS and ZLS_COLOURS: LISTPROMPT should not be set directly when using the shell function based completion system. Use the list-prompt style instead. ๐
๐ Menu selection ๐
The zsh/complist module also offers an alternative style of picking matches out of a list, called menu selection, which you can use if the shell is set up to return to the last prompt after showing a completion list (see the ALWAYS_LAST_PROMPT option in zshoptions(1)).
Menu selection can be invoked directly by the widget menu-select, defined by this module. It's a standard ZLE widget, so you can bind it to a key the usual way, as described in zshzle(1).
Alternatively โ the other route โ the parameter MENUSELECT can be set to an integer, which gives the minimum number of matches that must be present before menu selection is automatically turned on. This second method requires that menu completion be started, either directly from a widget such as menu-complete, or because one of the options MENU_COMPLETE or AUTO_MENU is set. If MENUSELECT is set but is 0, 1 or empty, menu selection will always be started during an ambiguous menu completion.
๐ซถ When using the completion system based on shell functions, theMENUSELECTparameter should not be used (just like theZLS_COLORSandZLS_COLOURSparameters described above). Use themenustyle with theselect=...keyword instead.
Once menu selection starts, the matches get listed. If there are more matches than fit on the screen, only the first screenful is shown. The matches to insert into the command line can be selected from this list. In the list, one match is highlighted using the value for ma from the ZLS_COLORS or ZLS_COLOURS parameter. The default value for this is 7, which forces the selected match to be highlighted using standout mode on a vt100-compatible terminal. If neither ZLS_COLORS nor ZLS_COLOURS is set, the same terminal control sequence as for the %S escape in prompts is used. โจ
If there are more matches than fit on the screen and the parameter MENUPROMPT is set, its value gets shown below the matches. It supports the same escape sequences as LISTPROMPT, but the number of the match or line shown will be that of the one where the mark is placed. If its value is the empty string, a default prompt is used.
The MENUSCROLL parameter specifies how the list is scrolled. If it's unset, scrolling is done line by line. If it's set to 0 (zero), the list scrolls half the number of lines of the screen. If the value is positive, it gives the number of lines to scroll, and if it's negative, the list gets scrolled the number of lines of the screen minus the (absolute) value.
๐ And as forZLS_COLORS,ZLS_COLOURSandLISTPROMPTโ neitherMENUPROMPTnorMENUSCROLLshould be set directly when using the shell function based completion system. Use theselect-promptandselect-scrollstyles instead.
Okay so sometimes the completion code decides not to show all the matches in the list. These hidden matches are either matches where the completion function that added them explicitly asked for them not to appear in the list (using the -n option of the compadd builtin command), or matches that duplicate a string already in the list (because they differ only in stuff like prefixes or suffixes that aren't displayed). In the list used for menu selection though, even these matches get shown, so you can actually select them. To highlight such matches, the hi and du capabilities in the ZLS_COLORS and ZLS_COLOURS parameters are supported for hidden matches of the first and second kind, respectively. ๐ฆ
Selecting matches is done by moving the mark around using the zle movement functions. When not all matches fit on the screen at the same time, the list scrolls up and down when you cross the top or bottom line. The following zle functions have special meaning during menu selection. Note that these always perform the same task within the menu selection map, and cannot be replaced by user defined widgets โ the set of functions can't be extended either:
accept-line,accept-searchโ accept the current match and leave menu selection (but do not cause the command line to be accepted)send-breakโ leaves menu selection and restores the previous contents of the command lineredisplay,clear-screenโ execute their normal function without leaving menu selectionaccept-and-hold,accept-and-menu-completeโ accept the currently inserted match and keep selecting, so you can select the next match to insert into the lineaccept-and-infer-next-historyโ accepts the current match and then tries completion with menu selection again; for files this lets you select a directory and immediately attempt to complete files inside it; if there are no matches, a message is shown and you can useundoto go back to completion on the previous level, and every other key leaves menu selection (including the other zle functions that are otherwise special during menu selection)undoโ removes matches inserted during menu selection by one of the three functions beforedown-history,down-line-or-history,vi-down-line-or-history,down-line-or-searchโ moves the mark one line downup-history,up-line-or-history,vi-up-line-or-history,up-line-or-searchโ moves the mark one line up
๐ธ (and yes, there's more โ stick around, bestie) ๐ธ
forward-char,vi-forward-charโ moves the mark one column right ๐backward-char,vi-backward-charโ moves the mark one column leftforward-word,vi-forward-wordvi-forward-word-end,emacs-forward-wordโ moves the mark one screenful downbackward-word,vi-backward-word,emacs-backward-wordโ moves the mark one screenful upvi-forward-blank-word,vi-forward-blank-word-endโ moves the mark to the first line of the next group of matches โจvi-backward-blank-wordโ moves the mark to the last line of the previous group of matchesbeginning-of-historyโ moves the mark to the first lineend-of-historyโ moves the mark to the last linebeginning-of-buffer-or-history,beginning-of-linebeginning-of-line-hist,vi-beginning-of-lineโ moves the mark to the leftmost columnend-of-buffer-or-history,end-of-lineend-of-line-hist,vi-end-of-lineโ moves the mark to the rightmost columncomplete-word,menu-complete,expand-or-completeexpand-or-complete-prefix,menu-expand-or-completeโ moves the mark to the next matchreverse-menu-completeโ moves the mark to the previous matchvi-insertโ this toggles between normal and interactive mode ๐ฆ in interactive mode the keys bound toself-insertandself-insert-unmetainsert into the command line as in normal editing mode but without leaving menu selection; after each character completion is tried again and the list changes to contain only the new matches; the completion widgets make the longest unambiguous string be inserted in the command line andundoandbackward-delete-chargo back to the previous set of matcheshistory-incremental-search-forwardhistory-incremental-search-backwardโ this starts incremental searches in the list of completions displayed; in this mode,accept-lineonly leaves incremental search, going back to the normal menu selection mode
okay so all movement functions wrap around at the edges ๐ซ any other zle function not listed leaves menu selection and executes that function. And bestie, you can make widgets in the above list do the same โ just use the form of the widget with a . in front. For example, the widget .accept-line has the effect of leaving menu selection and accepting the entire command line. iconique.
During this selection the widget uses the keymap menuselect. Any key that is not defined in this keymap or that is bound to undefined-key is looked up in the keymap currently selected ๐ This is used to ensure that the most important keys used during selection (namely the cursor keys, return, and TAB) have sensible defaults. However, keys in the menuselect keymap can be modified directly using the bindkey builtin command (see zshmodules(1)). For example, to make the return key leave menu selection without accepting the match currently selected one could call
bindkey -M menuselect '^M' send-break
after loading the zsh/complist module. no cap, that's the whole vibe ๐
โจ THE ZSH/COMPUTIL MODULE โจ
The zsh/computil module adds several builtin commands that are used by some of the completion functions in the completion system based on shell functions (see zshcompsys(1) ). Except for compquote these builtin commands are very specialised and thus not very interesting when writing your own completion functions ๐ In summary, these builtin commands are:
compargumentsโ This is used by the_argumentsfunction to do the argument and command line parsing. Likecompdescribeit has an option-ito do the parsing and initialize some internal state and various options to access the state information to decide what should be completed.compdescribeโ This is used by the_describefunction to build the displays for the matches and to get the strings to add as matches with their options. On the first call one of the options-ior-Ishould be supplied as the first argument. In the first case, display strings without the descriptions will be generated; in the second case, the string used to separate the matches from their descriptions must be given as the second argument and the descriptions (if any) will be shown. All other arguments are like the definition arguments to_describeitself.- Once
compdescribehas been called with either the-ior the-Ioption, it can be repeatedly called with the-goption and the names of four parameters as its arguments. This will step through the different sets of matches and store the value ofcompstate[list]in the first scalar, the options forcompaddin the second array, the matches in the third array, and the strings to be displayed in the completion listing in the fourth array ๐ฅ The arrays may then be directly given tocompaddto register the matches with the completion code.
- Once
compfilesโ Used by the_path_filesfunction to optimize complex recursive filename generation (globbing). It does three things, bestie: with the-pand-Poptions it builds the glob patterns to use, including the paths already handled and trying to optimize the patterns with respect to the prefix and suffix from the line and the match specification currently used. The-ioption does the directory tests for theignore-parentsstyle and the-roption tests if a component for some of the matches are equal to the string on the line and removes all other matches if that is true.compgroupsโ Used by the_tagsfunction to implement the internals of thegroup-orderstyle. This only takes its arguments as names of completion groups and creates the groups for it (all six types: sorted and unsorted, both without removing duplicates, with removing all duplicates and with removing consecutive duplicates) โจcompquote [ -p ] names ...โ There may be reasons to write completion functions that have to add the matches using the-Qoption tocompaddand perform quoting themselves. Instead of interpreting the first character of theall_quoteskey of thecompstatespecial association and using theqflag for parameter expansions, one can use this builtin command. The arguments are the names of scalar or array parameters and the values of these parameters are quoted as needed for the innermost quoting level. If the-poption is given, quoting is done as if there is some prefix before the values of the parameters, so that a leading equal sign will not be quoted.- The return status is non-zero in case of an error and zero otherwise ๐
comptagscomptryโ These implement the internals of the tags mechanism.compvaluesโ Likecomparguments, but for the_valuesfunction.
โจ THE ZSH/CURSES MODULE โจ
The zsh/curses module makes available one builtin command and various parameters ๐
โจ Builtin โจ
zcurses init
zcurses end
zcurses addwin targetwin nlines ncols begin_y begin_x [ parentwin ]
zcurses delwin targetwin
zcurses refresh [ targetwin ... ]
zcurses touch targetwin ...
zcurses move targetwin new_y new_x
zcurses clear targetwin [ redraw | eol | bot ]
zcurses position targetwin array
zcurses char targetwin character
zcurses string targetwin string
zcurses border targetwin border
zcurses attr targetwin [ [+|-]attribute | fg_col/bg_col ] [...]
zcurses bg targetwin [ [+|-]attribute | fg_col/bg_col | @char ] [...]
zcurses scroll targetwin [ on | off | [+|-]lines ]
zcurses input targetwin [ param [ kparam [ mparam ] ] ]
zcurses mouse [ delay num | [+|-]motion ]
zcurses timeout targetwin intval
zcurses querychar targetwin [ param ]
zcurses resize height width [ endwin | nosave | endwin_nosave ]
Manipulate curses windows ๐ช All uses of this command should be bracketed by zcurses init to initialise use of curses, and zcurses end to end it; omitting zcurses end can cause the terminal to be in an unwanted state ๐ญ like, genuinely, don't skip it.
The subcommand addwin creates a window with nlines lines and ncols columns. Its upper left corner will be placed at row begin_y and column begin_x of the screen. targetwin is a string and refers to the name of a window that is not currently assigned. Note in particular the curses convention that vertical values appear before horizontal values ๐
If addwin is given an existing window as the final argument, the new window is created as a subwindow of parentwin. This differs from an ordinary new window in that the memory of the window contents is shared with the parent's memory. Subwindows must be deleted before their parent โ ๏ธ Note that the coordinates of subwindows are relative to the screen, not the parent, as with other windows.
Use the subcommand delwin to delete a window created with addwin. Note that end does not implicitly delete windows, and that delwin does not erase the screen image of the window.
The window corresponding to the full visible screen is called stdscr; it always exists after zcurses init and cannot be deleted with delwin ๐
The subcommand refresh will refresh window targetwin; this is necessary to make any pending changes (such as characters you have prepared for output with char) visible on the screen. refresh without an argument causes the screen to be cleared and redrawn. If multiple windows are given, the screen is updated once at the end โ efficient queen behavior โจ
The subcommand touch marks the targetwins listed as changed. This is necessary before refreshing windows if a window that was in front of another window (which may be stdscr) is deleted.
The subcommand move moves the cursor position in targetwin to new coordinates new_y and new_x. Note that the subcommand string (but not the subcommand char) advances the cursor position over the characters added ๐ฆ
The subcommand clear erases the contents of targetwin. One (and no more than one) of three options may be specified ๐ With the option redraw, in addition the next refresh of targetwin will cause the screen to be cleared and repainted. With the option eol, targetwin is only cleared to the end of the current cursor line. With the option bot, targetwin is cleared to the end of the window, i.e. everything to the right and below the cursor is cleared ๐ซ
The position subcommand writes a whole lil bundle of positions into the array named array. In order, bestie:
- the
yandxcoordinates of the cursor relative to the top left oftargetwin - the
yandxcoordinates of the top left oftargetwinon the screen - the size of
targetwininyandxdimensions
Outputting characters and strings is handled by char and string respectively. ๐
Wanna draw a border around targetwin? That's border, iconic. But heads up: the border is not handled specially afterwards โ it's literally just a set of characters output at the edge of the window. So it can be overwritten, it can scroll off the window, etc. It's giving "decorative, not structural." ๐
The attr subcommand sets targetwin's attributes or the foreground/background color pair for any successive character output. Each attribute given on the line may be prepended by a + to set it or a - to unset it; + is assumed if absent. The attributes supported are blink, bold, dim, reverse, standout, and underline.
Each fg_col/bg_col attribute (read it as fg_col on bg_col) sets the foreground and background color for character output. The color default is sometimes available (in particular if the library is ncurses), specifying the foreground or background color the terminal started with. The color pair default/default is always available. To use more than the 8 named colors (red, green, etc.) construct the fg_col/bg_col pairs where fg_col and bg_col are decimal integers, e.g. 128/200. The maximum color value is 254 if the terminal supports 256 colors. ๐
bg overrides the color and other attributes of all characters in the window. Its usual use is to set the background initially, but it will overwrite the attributes of any characters at the time when it's called. In addition to the arguments allowed with attr, an argument @char specifies a character to be shown in otherwise blank areas of the window. Owing to limitations of curses this cannot be a multibyte character (use of ASCII characters only is recommended). And since the specified set of attributes override the existing background, turning attributes off in the arguments isn't useful โ though this does not cause an error. No cap. ๐
The scroll subcommand can be used with on or off to enable or disable scrolling of a window when the cursor would otherwise move below the window due to typing or output. It can also take a positive or negative integer to scroll the window up or down the given number of lines without changing the current cursor position (which therefore appears to move in the opposite direction relative to the window). In that second case, if scrolling is off it's temporarily turned on to allow the window to be scrolled. โจ
The input subcommand reads a single character from the window without echoing it back. If param is supplied the character is assigned to the parameter param, else it's assigned to the parameter REPLY.
If both param and kparam are supplied, the key is read in keypad mode. In this mode special keys such as function keys and arrow keys return the name of the key in the parameter kparam. The key names are the macros defined in the curses.h or ncurses.h with the prefix KEY_ removed; see also the description of the parameter zcurses_keycodes below. Other keys cause a value to be set in param as before. On a successful return only one of param or kparam contains a non-empty string; the other is set to an empty string. ๐ซถ
If mparam is also supplied, input attempts to handle mouse input. This is only available with the ncurses library; mouse handling can be detected by checking for the exit status of zcurses mouse with no arguments. If a mouse button is clicked (or double- or triple-clicked, or pressed or released with a configurable delay from being clicked) then kparam is set to the string MOUSE, and mparam is set to an array consisting of the following elements:
- An identifier to discriminate different input devices; this is only rarely useful.
- The
x,yandzcoordinates of the mouse click relative to the full screen, as three elements in that order (i.e. theycoordinate is, unusually, after thexcoordinate). Thezcoordinate is only available for a few unusual input devices and is otherwise set to zero. - Any events that occurred as separate items; usually there will be just one. An event consists of
PRESSED,RELEASED,CLICKED,DOUBLE_CLICKEDorTRIPLE_CLICKEDfollowed immediately (in the same element) by the number of the button. - If the shift key was pressed, the string
SHIFT. - If the control key was pressed, the string
CTRL. - If the alt key was pressed, the string
ALT.
Not all mouse events may be passed through to the terminal window; most terminal emulators handle some mouse events themselves. Also, the ncurses manual implies that using input both with and without mouse handling may cause the mouse cursor to appear and disappear. ๐
The mouse subcommand configures the use of the mouse. There's no window argument โ mouse options are global. zcurses mouse with no arguments returns status 0 if mouse handling is possible, else status 1. Otherwise, the possible arguments (which may be combined on the same command line) are as follows:
delaynum โ sets the maximum delay in milliseconds between press and release events to be considered as a click; the value0disables click resolution, and the default is one sixth of a second.motionproceeded by an optional+(the default) or-โ turns on or off reporting of mouse motion in addition to clicks, presses and releases, which are always reported. However, it appears reports for mouse motion are not currently implemented. ๐
The timeout subcommand specifies a timeout value for input from targetwin. If intval is negative, zcurses input waits indefinitely for a character to be typed โ this is the default. If intval is zero, zcurses input returns immediately; if there is typeahead it's returned, else no input is done and status 1 is returned. If intval is positive, zcurses input waits intval milliseconds for input and if there's none at the end of that period returns status 1. โญ
The querychar subcommand queries the character at the current cursor position. The return values are stored in the array named param if supplied, else in the array reply. The first value is the character (which may be a multibyte character if the system supports them); the second is the color pair in the usual fg_col/bg_col notation, or 0 if color is not supported. Any attributes other than color that apply to the character, as set with the subcommand attr, appear as additional elements. ๐ฆ
The resize subcommand resizes stdscr and all windows to the given dimensions (windows that stick out from the new dimensions are resized down). The underlying curses extension (resize_term call) can be unavailable. To verify, zeroes can be used for height and width. If the result of the subcommand is 0, resize_term is available (2 otherwise). Tests show that resizing can normally be accomplished by calling zcurses end and zcurses refresh. The resize subcommand is provided for versatility. Multiple system configurations have been checked and zcurses end and zcurses refresh are still needed for correct terminal state after resize. To invoke them with resize, use the endwin argument. Using the nosave argument will cause new terminal state to not be saved internally by zcurses. This is also provided for versatility and should normally not be needed. ๐ง
๐งธ Parameters ๐งธ
ZCURSES_COLORSโ Readonly integer. The maximum number of colors the terminal supports. This value is initialised by the curses library and is not available until the first timezcurses initis run.ZCURSES_COLOR_PAIRSโ Readonly integer. The maximum number of color pairsfg_col/bg_colthat may be defined inzcurses attrcommands; note this limit applies to all color pairs that have been used whether or not they're currently active. This value is initialised by the curses library and is not available until the first timezcurses initis run.zcurses_attrsโ Readonly array. The attributes supported byzsh/curses; available as soon as the module is loaded. โจzcurses_colorsโ Readonly array. The colors supported byzsh/curses; available as soon as the module is loaded.zcurses_keycodesโ Readonly array. The values that may be returned in the second parameter supplied tozcurses inputin the order in which they are defined internally by curses. Not all function keys are listed, onlyF0; curses reserves space forF0up toF63.zcurses_windowsโ Readonly array. The current list of windows, i.e. all windows that have been created withzcurses addwinand not removed withzcurses delwin. ๐
๐ THE ZSH/DATETIME MODULE ๐
okay so the zsh/datetime module gives you exactly one builtin command, bestie:
โจ the strftime builtin โจ
strftime [ -s scalar | -n ] format [ epochtime [ nanoseconds ] ]
strftime -r [ -q ] [ -s scalar | -n ] format timestring
It outputs the date in the format you specify. With no epochtime, it uses the current system date/time; optionally, epochtime can specify the number of seconds since the epoch, and nanoseconds can additionally specify the number of nanoseconds past the second (otherwise that number is assumed to be 0). See strftime(3) for the details. The zsh extensions described in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1) are also available. ๐ฐ๏ธ
-nโ suppress printing a newline after the formatted string.-qโ run quietly; suppress printing of all error messages described below. Errors for invalidepochtimevalues are always printed.-rโ with the option-r(reverse), useformatto parse the input stringtimestringand output the number of seconds since the epoch at which the time occurred. The parsing is implemented by the system functionstrptime; seestrptime(3). This means zsh format extensions are not available, but for reverse lookup they are not required.
In most implementations of strftime any timezone in the timestring is ignored and the local timezone declared by the TZ environment variable is used; other parameters are set to zero if not present.
If timestring does not match format the command returns status 1 and prints an error message. If timestring matches format but not all characters in timestring were used, the conversion succeeds but also prints an error message.
If either of the system functions strptime or mktime is not available, status 2 is returned and an error message is printed.
-sscalar โ assign the date string (or epoch time in seconds if-ris given) to scalar instead of printing it.
โ ๏ธ heads up, bestie: depending on the system's declared integral time type,strftimemay produce incorrect results for epoch times greater than2147483647which corresponds to2038-01-19 03:14:07 +0000. ๐ญ
๐ readonly parameters ๐
The zsh/datetime module also makes available several parameters; all are readonly ๐
:
EPOCHREALTIMEโ a floating point value representing the number of seconds since the epoch. The notional accuracy is to nanoseconds if theclock_gettimecall is available and to microseconds otherwise, but in practice the range of double precision floating point and shell scheduling latencies may be significant effects.EPOCHSECONDSโ an integer value representing the number of seconds since the epoch.epochtimeโ an array value containing the number of seconds since the epoch in the first element and the remainder of the time since the epoch in nanoseconds in the second element. To ensure the two elements are consistent the array should be copied or otherwise referenced as a single substitution before the values are used. The following idiom may be used:
for secs nsecs in $epochtime; do
...
done
๐๏ธ THE ZSH/DB/GDBM MODULE ๐๏ธ
The zsh/db/gdbm module is used to create "tied" associative arrays that interface to database files. If the GDBM interface is not available, the builtins defined by this module will report an error. This module is also intended as a prototype for creating additional database interfaces, so the ztie builtin may move to a more generic module in the future. ๐
The builtins in this module are:
โจ ztie โจ
ztie -d db/gdbm -f filename [ -r ] arrayname
Open the GDBM database identified by filename and, if successful, create the associative array arrayname linked to the file. To create a local tied array, the parameter must first be declared, so commands similar to the following would be executed inside a function scope:
local -A sampledb
ztie -d db/gdbm -f sample.gdbm sampledb
The -r option opens the database file for reading only, creating a parameter with the readonly attribute. Without this option, using ztie on a file for which the user does not have write permission is an error. If writable, the database is opened synchronously so fields changed in arrayname are immediately written to filename. ๐ฅ
Changes to the file modes filename after it has been opened do not alter the state of arrayname, but typeset -r arrayname works as expected.
โจ zuntie โจ
zuntie [ -u ] arrayname ...
Close the GDBM database associated with each arrayname and then unset the parameter. The -u option forces an unset of parameters made readonly with ztie -r. ๐ซถ
This happens automatically if the parameter is explicitly unset or its local scope (function) ends. Note that a readonly parameter may not be explicitly unset, so the only way to unset a global parameter created with ztie -r is to use zuntie -u.
โจ zgdbmpath โจ
zgdbmpath parametername
Put path to database file assigned to parametername into REPLY scalar. ๐
โจ zgdbm_tied โจ
Array holding names of all tied parameters.
The fields of an associative array tied to GDBM are neither cached nor otherwise stored in memory, they are read from or written to the database on each reference. Thus, for example, the values in a readonly array may be changed by a second writer of the same database file. not a typo, bestie โ that's literally what it says. ๐
๐ซ THE ZSH/DELTOCHAR MODULE ๐ซ
The zsh/deltochar module makes available two ZLE functions:
delete-to-charโ read a character from the keyboard, and delete from the cursor position up to and including the next (or, with repeat count n, the *n*th) instance of that character. Negative repeat counts mean delete backwards.zap-to-charโ this behaves likedelete-to-char, except that the final occurrence of the character itself is not deleted. โจ
๐ธ THE ZSH/EXAMPLE MODULE ๐ธ
The zsh/example module makes available one builtin command:
โจ example โจ
example [ -flags ] [ args ... ]
Displays the flags and arguments it is invoked with. ๐
The purpose of the module is to serve as an example of how to write a module. It's literally there to show you how to write a module, periodt. ๐ง
๐ธ THE ZSH/FILES MODULE ๐ธ
okay so the zsh/files module is giving "builtin glow-up for the classic file commands" โ it hands you a bunch of common file-manipulation commands as builtins. Are you gonna need these in your everyday little life? Honestly probably not for most normal situations ๐ but they are lowkey iconic for emergency recovery situations where your resources are all constrained and sad. Big caveat bestie: these commands do not implement all features now required by relevant standards committees. So they're the fun version, not the standards-compliant version. ๐
For all commands, a variant beginning zf_ is also available and loaded automatically โจ Using the features capability of zmodload will let you load only those names you want. And btw, it's possible to load only the builtins with zsh-specific names using this:
zmodload -m -F zsh/files b:zf_\*
The commands loaded by default are:
๐ซถ chgrp [ -hRs ] group filename ...
Changes group of files specified. This is equivalent to chown with a user-spec argument of :group. that's it, that's the whole vibe ๐
๐
chmod [ -Rs ] mode filename ...
Changes mode of files specified.
The specified mode must be in octal. no decimal nonsense, we don't do that here.
-Rโ causeschmodto recursively descend into directories, changing the mode of all files in the directory after changing the mode of the directory itself.-sโ a zsh extension tochmodfunctionality. It enables paranoid behaviour, intended to avoid security problems involving achmodbeing tricked into affecting files other than the ones intended. It will refuse to follow symbolic links, so that (for example)chmod 600 /tmp/foo/passwdcan't accidentally chmod/etc/passwdif/tmp/foohappens to be a link to/etc. It will also check where it is after leaving directories, so that a recursivechmodof a deep directory tree can't end up recursively chmoding/usras a result of directories being moved up the tree. ๐ต๏ธโโ๏ธ she's watching, she's checking, she's not getting played.
๐ chown [ -hRs ] user-spec filename ...
Changes ownership and group of files specified.
The user-spec can be in four forms:
userโ change owner to user; do not change groupuser::โ change owner to user; do not change groupuser:โ change owner to user; change group to user's primary groupuser:groupโ change owner to user; change group to group:groupโ do not change owner; change group to group
In each case, the : may instead be a . โจ The rule is that if there is a : then the separator is :; otherwise if there is a . then the separator is .; otherwise there is no separator. memorize it, there will be a quiz.
Each of user and group may be either a username (or group name, as appropriate) or a decimal user ID (group ID). Interpretation as a name takes precedence, if there is an all-numeric username (or group name). so the names win the argument, okurrr ๐
-hโ if the target is a symbolic link, causeschownto set the ownership of the link instead of its target.-Rโ causeschownto recursively descend into directories, changing the ownership of all files in the directory after changing the ownership of the directory itself.-sโ a zsh extension tochownfunctionality. It enables paranoid behaviour, intended to avoid security problems involving achownbeing tricked into affecting files other than the ones intended. It will refuse to follow symbolic links, so that (for example)chown luser /tmp/foo/passwdcan't accidentally chown/etc/passwdif/tmp/foohappens to be a link to/etc. It will also check where it is after leaving directories, so that a recursivechownof a deep directory tree can't end up recursively chowning/usras a result of directories being moved up the tree. ๐ฆ same paranoid queen energy, different syscall.
๐ ln [ -dfhins ] filename dest
ln [ -dfhins ] filename dest
ln [ -dfhins ] filename ... dir
Creates hard (or, with -s, symbolic) links. In the first form, the specified destination is created, as a link to the specified filename. In the second form, each of the filenames is taken in turn, and linked to a pathname in the specified dir that has the same last pathname component.
Normally, ln will not attempt to create hard links to directories. This check can be overridden using the -d option. Typically only the super-user can actually succeed in creating hard links to directories. This does not apply to symbolic links in any case. (symbolic links said "not my problem" ๐)
By default, existing files cannot be replaced by links.
-iโ causes the user to be queried about replacing existing files.-fโ causes existing files to be silently deleted, without querying. and yes,-ftakes precedence.-hand-nโ these are identical and both exist for compatibility; either one indicates that if the target is a symlink then it should not be dereferenced. Typically this is used in combination with-sfso that if an existing link points to a directory then it will be removed, instead of followed. If this option is used with multiple filenames and the target is a symbolic link pointing to a directory then the result is an error. ๐ read that again before you ship it.
๐ mkdir [ -p ] [ -m mode ] dir ...
Creates directories. With the -p option, non-existing parent directories are first created if necessary, and there will be no complaint if the directory already exists (she's chill like that ๐งโโ๏ธ). The -m option can be used to specify (in octal) a set of file permissions for the created directories, otherwise mode 777 modified by the current umask (see umask(2)) is used.
โญ mv [ -fi ] filename dest
mv [ -fi ] filename dest
mv [ -fi ] filename ... dir
Moves files. In the first form, the specified filename is moved to the specified dest. In the second form, each of the filenames is taken in turn, and moved to a pathname in the specified dir that has the same last pathname component.
By default, the user will be queried before replacing any file that the user cannot write to, but writable files will be silently removed.
-iโ causes the user to be queried about replacing any existing files.-fโ causes any existing files to be silently deleted, without querying. and yeah,-ftakes precedence.
โ ๏ธ note that thismvwill not move files across devices. Historical versions ofmv, when actual renaming is impossible, fall back on copying and removing files; if this behaviour is desired, usecpandrmmanually. This may change in a future version. so like, don't come for her when your cross-device move doesn't move, she told you upfront ๐
๐ฅ rm [ -dfiRrs ] filename ...
Removes files and directories specified.
Normally, rm will not remove directories (except with the -R or -r options). The -d option causes rm to try removing directories with unlink (see unlink(2)), the same method used for files. Typically only the super-user can actually succeed in unlinking directories in this way. -d takes precedence over -R and -r.
By default, the user will be queried before removing any file that the user cannot write to, but writable files will be silently removed.
-iโ causes the user to be queried about removing any files.-fโ causes files to be silently deleted, without querying, and suppresses all error indications.-ftakes precedence.-Rand-rโ causermto recursively descend into directories, deleting all files in the directory before removing the directory with thermdirsystem call (seermdir(2)).-sโ a zsh extension tormfunctionality. It enables paranoid behaviour, intended to avoid common security problems involving a root-runrmbeing tricked into removing files other than the ones intended. It will refuse to follow symbolic links, so that (for example)rm /tmp/foo/passwdcan't accidentally remove/etc/passwdif/tmp/foohappens to be a link to/etc. It will also check where it is after leaving directories, so that a recursive removal of a deep directory tree can't end up recursively removing/usras a result of directories being moved up the tree. ๐ก๏ธ the bodyguard of flags, no cap.
๐ rmdir dir ...
Removes empty directories specified. that's the whole job. empty ones only, she's not doing charity work ๐
๐ง sync
Calls the system call of the same name (see sync(2)), which flushes dirty buffers to disk. It might return before the I/O has actually been completed. so like... it might be lying to you a little bit about being done ๐ญ not her fault, that's the system call's vibe.
โจ THE ZSH/LANGINFO MODULE โจ
The zsh/langinfo module makes available one parameter:
langinfoโ an associative array that maps langinfo elements to their values. ๐บ๏ธ literally a whole dictionary of locale lore.
Your implementation may support a number of the following keys:
CODESET, D_T_FMT, D_FMT, T_FMT, RADIXCHAR, THOUSEP, YESEXPR, NOEXPR, CRNCYSTR, ABDAY_{1..7}, DAY_{1..7}, ABMON_{1..12}, MON_{1..12}, T_FMT_AMPM, AM_STR, PM_STR, ERA, ERA_D_FMT, ERA_D_T_FMT, ERA_T_FMT, ALT_DIGITS
(and that {1..7} / {1..12} brace-expansion energy is so zsh of them ๐ซถ)
๐๏ธ THE ZSH/MAPFILE MODULE
Okay bestie, the zsh/mapfile module is genuinely one of the most underrated little slay machines in the whole shell. It gives you exactly one special associative array parameter, and the parameter is literally also called mapfile. Same name, no notes. ๐
mapfileโ so here's the vibe: the keys of this associative array are file names, and the values are the contents of those files. The value is treated identically to any other text coming from a parameter. But here's the iconic part โ you can also assign to it, and the file in question gets written (whether or not it originally existed). And if youunsetan element? The file gets deleted. Poof. ๐ซถ
Like, for example, vared 'mapfile[myfile]' works exactly as expected, editing the file myfile. Cute, right?
Okay but now the โจ plot twist โจ โ when the array is accessed as a whole, the keys are the names of files in the current directory, and the values are empty (to save a huge overhead in memory). So:
${(k)mapfile}
has the same effect as the glob operator *(D), since files beginning with a dot are not special here. ๐
โ ๏ธ Care must be taken with expressions such asrm ${(k)mapfile}, which will delete every file in the current directory without the usualrm *test. That is not a drill, bestie. That's every file. Gone. ๐
The parameter mapfile may be made read-only; in that case, files referenced may not be written or deleted. Protective era. ๐
A file may conveniently be read into an array as one line per element with the form:
array=("${(f@)mapfile[filename]}")
The double quotes and the @ are necessary to prevent empty lines from being removed. No cap. Note that if the file ends with a newline, the shell will split on the final newline, generating an additional empty field; this can be suppressed by using:
array=("${(f@)${mapfile[filename]%$'\n'}}")
See how that little %$'\n' just quietly trims the vibe? Chef's kiss. ๐ฅ
๐ง Limitations
So, lowkey, there are some things you should know. Although reading and writing of the file in question is efficiently handled, zsh's internal memory management may be arbitrarily baroque. Like, it's giving rococo. However, mapfile is usually very much more efficient than anything involving a loop.
Note in particular that the whole contents of the file will always reside physically in memory when accessed (possibly multiple times, due to standard parameter substitution operations). In particular, this means handling of sufficiently long files (greater than the machine's swap space, or than the range of the pointer type) will be incorrect. ๐ญ So maybe don't try this with a 400GB file, bestie, I'm begging.
No errors are printed or flagged for non-existent, unreadable, or unwritable files, as the parameter mechanism is too low in the shell execution hierarchy to make this convenient. So it's just gonna silently do its thing. ๐
It is unfortunate that the mechanism for loading modules does not yet allow the user to specify the name of the shell parameter to be given the special behaviour. Sad but true. ๐ฆ
๐งฎ THE ZSH/MATHFUNC MODULE
The zsh/mathfunc module provides standard mathematical functions for use when evaluating mathematical formulae. The syntax agrees with normal C and FORTRAN conventions, for example:
(( f = sin(0.3) ))
assigns the sine of 0.3 to the parameter f. Literally math class but make it fashion. โญ
Most functions take floating point arguments and return a floating point value. However, any necessary conversions from or to integer type will be performed automatically by the shell. Apart from atan with a second argument and the abs, int and float functions, all functions behave as noted in the manual page for the corresponding C function, except that any arguments out of range for the function in question will be detected by the shell and an error reported. So the shell is gonna catch you. ๐
The following functions take a single floating point argument:
acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, cos, cosh, erf, erfc, exp,
expm1, fabs, floor, gamma, j0, j1, lgamma, log, log10, log1p, log2, logb,
sin, sinh, sqrt, tan, tanh, y0, y1
The atan function can optionally take a second argument, in which case it behaves like the C function atan2. The ilogb function takes a single floating point argument, but returns an integer.
The function signgam takes no arguments, and returns an integer, which is the C variable of the same name, as described in gamma(3). Note that it is therefore only useful immediately after a call to gamma or lgamma. Note also that signgam() and signgam are distinct expressions. Iykyk. ๐
The functions min, max, and sum are defined not in this module but in the zmathfunc autoloadable function, described in the section Mathematical Functions in zshcontrib(1).
The following functions take two floating point arguments: copysign, fmod, hypot, nextafter.
The following take an integer first argument and a floating point second argument: jn, yn.
The following take a floating point first argument and an integer second argument: ldexp, scalb.
The function abs does not convert the type of its single argument; it returns the absolute value of either a floating point number or an integer. The functions float and int convert their arguments into a floating point or integer value (by truncation) respectively. Truncation era. ๐
Note that the C pow function is available in ordinary math evaluation as the ** operator and is not provided here. We already have power at home, bestie. โก
The function rand48 is available if your system's mathematical library has the function erand48(3). It returns a pseudo-random floating point number between 0 and 1. It takes a single string optional argument. ๐ฒ
If the argument is not present, the random number seed is initialised by three calls to the rand(3) function โ this produces the same random numbers as the next three values of $RANDOM.
If the argument is present, it gives the name of a scalar parameter where the current random number seed will be stored. On the first call, the value must contain at least twelve hexadecimal digits (the remainder of the string is ignored), or the seed will be initialised in the same manner as for a call to rand48 with no argument. Subsequent calls to rand48(param) will then maintain the seed in the parameter param as a string of twelve hexadecimal digits, with no base signifier. The random number sequences for different parameters are completely independent, and are also independent from that used by calls to rand48 with no argument. Separate vibes, separate timelines. ๐
For example, consider:
print $(( rand48(seed) ))
print $(( rand48() ))
print $(( rand48(seed) ))
Assuming $seed does not exist, it will be initialised by the first call. In the second call, the default seed is initialised; note, however, that because of the properties of rand() there is a correlation between the seeds used for the two initialisations, so for more secure uses, you should generate your own 12-byte seed. (Do not use the default seed for your crypto, babe, I am BEGGING. ๐) The third call returns to the same sequence of random numbers used in the first call, unaffected by the intervening rand48().
๐ THE ZSH/NEARCOLOR MODULE
The zsh/nearcolor module replaces colours specified as hex triplets with the nearest colour in the 88 or 256 colour palettes that are widely used by terminal emulators. By default, 24-bit true colour escape codes are generated when colours are specified using hex triplets. These are not supported by all terminals. The purpose of this module is to make it easier to define colour preferences in a form that can work across a range of terminal emulators. It's giving accessibility, it's giving compatibility, it's giving we listen and we don't judge. ๐
Aside from the default colour, the ANSI standard for terminal escape codes provides for eight colours. The bright attribute brings this to sixteen. These basic colours are commonly used in terminal applications due to being widely supported. Expanded 88 and 256 colour palettes are also common and, while the first sixteen colours vary somewhat between terminals and configurations, these add a generally consistent and predictable set of colours. ๐ฆ
In order to use the zsh/nearcolor module, it only needs to be loaded. Thereafter, whenever a colour is specified using a hex triplet, it will be compared against each of the available colours and the closest will be selected. The first sixteen colours are never matched in this process due to being unpredictable. ๐
โโ๏ธ
It isn't possible to reliably detect support for true colour in the terminal emulator. It is therefore recommended to be selective in loading the zsh/nearcolor module. For example, the following checks the COLORTERM environment variable:
[[ $COLORTERM = *(24bit|truecolor)* ]] || zmodload zsh/nearcolor
Note that some terminals accept the true color escape codes but map them internally to a more limited palette in a similar manner to the zsh/nearcolor module. Sneaky little icon behaviour. โจ
๐ง THE ZSH/NEWUSER MODULE
The zsh/newuser module is loaded at boot if it is available, the RCS option is set, and the PRIVILEGED option is not set (all three are true by default). This takes place immediately after commands in the global zshenv file (typically /etc/zsh/zshenv), if any, have been executed. If the module is not available it is silently ignored by the shell; the module may safely be removed from $MODULE_PATH by the administrator if it is not required. Bye bestie, no hard feelings. ๐ธ
On loading, the module tests if any of the start-up files .zshenv, .zprofile, .zshrc or .zlogin exist in the directory given by the environment variable ZDOTDIR, or the user's home directory if that is not set. The test is not performed and the module halts processing if the shell was in an emulation mode (i.e. had been invoked as some other shell than zsh). She knows she's zsh and she's not gonna pretend otherwise. ๐
If none of the start-up files were found, the module then looks for the file newuser first in a sitewide directory, usually the parent directory of the site-functions directory, and if that is not found the module searches in a version-specific directory, usually the parent of the functions directory containing version-specific functions. (These directories can be configured when zsh is built using the --enable-site-scriptdir=dir and --enable-scriptdir=dir flags to configure, respectively; the defaults are prefix/share/zsh and prefix/share/zsh/$ZSH_VERSION where the default prefix is /usr/local. ๐ ๏ธ)
If the file newuser is found, it is then sourced in the same manner as a start-up file. The file is expected to contain code to install start-up files for the user, however any valid shell code will be executed. Free real estate for your shell code. ๐ฅ
The zsh/newuser module is then unconditionally unloaded. She did her job, she's leaving. Iconic exit. ๐
Note that it is possible to achieve exactly the same effect as the zsh/newuser module by adding code to /etc/zsh/zshenv. The module exists simply to allow the shell to make arrangements for new users without the need for intervention by package maintainers and system administrators. Convenience era. ๐ซถ
The script supplied with the module invokes the shell function zsh-newuser-install. This may be invoked directly by the user even if the zsh/newuser module is disabled. Note, however, that if the module is not installed the function will not be installed either. They're a package deal. ๐ญ The function is documented in the section User Configuration Functions in zshcontrib(1).
๐ THE ZSH/PARAMETER MODULE ๐
okay bestie, so this module is literally a backstage pass ๐๏ธ โ it hands you the keys to a bunch of the shell's internal hash tables by defining some โจspecial parametersโจ. no cap, it's giving "peek behind the curtain" energy.
๐ options
The keys of this associative array are the names of the options you can set and unset with the setopt and unsetopt builtins. Each key's value is the string on if that option is currently set, or the string off if it's unset. Set a key to one of those strings and it's like setting or unsetting the option respectively โ cute, right? And unsetting a key in this array is like setting it to off. slay.
๐ commands
This array gives you access to the command hash table ๐
The keys are the names of external commands, and the values are the pathnames of the files that would be executed when that command gets invoked. Setting a key here defines a new entry in the table, exactly like the hash builtin does. And unsetting a key โ like so, unset "commands[foo]" โ removes the entry for that key from the command hash table. periodt.
๐ functions
This associative array maps names of enabled functions to their definitions. Setting a key in it is like defining a function whose name is the key and whose body is the value. Unsetting a key removes the definition of the function named by that key. iconic behavior honestly.
๐ dis_functions
Same vibe as functions, but for disabled functions ๐
๐ functions_source
This one's a readonly associative array โ no touchy! โ and it maps names of enabled functions to the name of the file containing the function's source. let me break it down:
- For an autoloaded function that has already been loaded, or one marked for autoload with an absolute path, or one whose path has been resolved with
functions -r: this is the file found for autoloading, resolved to an absolute path. - For a function defined inside the body of a script or a sourced file: this is the name of that file. In this case it's the exact path originally used for that file, which may be a relative path.
- For any other function โ including anything defined at an interactive prompt, or an autoload function whose path hasn't been resolved yet โ this is the empty string.
BUT (and this is the slay part) the hash element is reported as defined for as long as the function exists: the keys of this hash are the same as those of $functions. ๐
๐ dis_functions_source
Like functions_source, but for disabled functions. same deal, just the benched ones ๐ช
๐ builtins
This associative array gives you the tea โ on the builtin commands currently enabled. The keys are the names of the builtin commands, and the values are either undefined โ for builtins that'll automatically get loaded from a module if invoked โ or defined โ for builtins that are already loaded.
๐ dis_builtins
Like builtins, but for disabled builtin commands ๐
๐ reswords
This array contains the enabled reserved words. yes queen, keywords.
๐ dis_reswords
Like reswords, but for disabled reserved words.
๐ patchars
This array contains the enabled pattern characters โจ
๐ dis_patchars
Like patchars, but for disabled pattern characters.
๐ aliases
Maps the names of the regular aliases currently enabled to their expansions. classic.
๐ dis_aliases
Like aliases, but for disabled regular aliases.
๐ galiases
Like aliases, but for global aliases ๐
๐ dis_galiases
Like galiases, but for disabled global aliases.
๐ saliases
Like raliases, but for suffix aliases. (yes, that's exactly what the page says โ don't come for me ๐ซถ)
๐ dis_saliases
Like saliases, but for disabled suffix aliases.
๐ parameters
The keys in this associative array are the names of the parameters currently defined, and the values are strings describing the type of each parameter โ same format as the t parameter flag, so go peek at zshexpn(1) if you're curious ๐. Setting or unsetting keys in this array is not possible. nope, not allowed, hands off ๐
๐ modules
An associative array serving up info about modules ๐ฆ The keys are the names of modules that are loaded, registered to be autoloaded, or aliased. The value tells you which state the named module is in, and it's one of the strings loaded, autoloaded, or alias:name, where name is the name the module is aliased to.
Setting or unsetting keys in this array is not possible. nope ๐ โโ๏ธ
๐ dirstack
A normal array holding the elements of the directory stack ๐๏ธ Quick note though: the output of the dirs builtin command includes one more directory โ the current working directory. don't forget her ๐
๐ history
This associative array maps history event numbers to the full history lines. And here's the fun part: even though it's presented as an associative array, the array of all values (${history[@]}) is guaranteed to come back in order from most recent to oldest history event โ that is, by decreasing history event number. so organized ๐
โจ
๐ historywords
A special array holding the words stored in the history. These also show up in most-to-least-recent order. chronological queen ๐
๐ jobdirs
This associative array maps job numbers to the directories the job was started from โ which, heads up, may not be the job's current directory ๐
The keys are usually valid job numbers, and those are the values you get out with, for example, ${(k)jobdirs}. Non-numeric job references can be used when you're looking up a value โ for example, ${jobdirs[%+]} refers to the current job. nifty.
Also: check the jobs builtin for how job information gets provided in a subshell ๐
๐ jobtexts
This associative array maps job numbers to the texts of the command lines that were used to start those jobs.
Handling of the keys works exactly as described for jobdirs above โ๏ธ
And again โ see the jobs builtin for how job information is provided in a subshell.
๐ jobstates
This associative array gives you the whole status report on the jobs currently known ๐ The keys are the job numbers, and the values are strings shaped like this:
job-state:mark:pid=state...
Here's the breakdown, bestie:
- The job-state is the state the whole job is in right now โ one of
running,suspended, ordone. - The mark is
+for the current job,-for the previous job, and empty otherwise. - After that comes one
:pid=statefor every process in the job. The pids are, of course, the process IDs, and state describes the state of that process.
Handling of the keys is as described for jobdirs above โ๏ธ
And yep โ see the jobs builtin for how job information is provided in a subshell.
๐ nameddirs
This associative array maps the names of named directories to the pathnames they stand for ๐โจ
๐ userdirs
This associative array maps user names to the pathnames of their home directories ๐
๐ usergroups
This associative array maps names of the system groups that the current user is a member of to the corresponding group identifiers. The contents are literally the same as the groups output by the id command ๐ซถ
๐ funcfiletrace
This array contains the absolute line numbers and corresponding file names for the point where the current function, sourced file, or (if EVAL_LINENO is set) eval command was called.
The array is the same length as funcsourcetrace and functrace, but it differs from funcsourcetrace in that the line and file are the point of call, not the point of definition โ and it differs from functrace in that all the values are absolute line numbers in files, rather than relative to the start of a function, if any. iykyk ๐ง
๐ funcsourcetrace
This array contains the file names and line numbers of the points where the functions, sourced files, and (if EVAL_LINENO is set) eval commands currently being executed were defined.
The line number is the line where the function name or name () started. In the case of an autoloaded function, the line number is reported as zero. The format of each element is:
filename:lineno
For functions autoloaded from a file in native zsh format โ where only the body of the function occurs in the file โ or for files that have been executed by the source or . builtins, the trace information shows up as filename:0, since the entire file is the definition. The source file name gets resolved to an absolute path when the function is loaded, or when the path to it is otherwise resolved.
Most users will be more interested in the info in the funcfiletrace array instead ๐ just saying.
๐ funcstack
This array contains the names of the functions, sourced files, and (if EVAL_LINENO is set) eval commands currently being executed. The first element is the name of the function using the parameter.
The standard shell array zsh_eval_context can be used to figure out the type of shell construct being executed at each depth โ but note: that one's in the opposite order, with the most recent item last, and it's more detailed. For example it includes an entry for toplevel, the main shell code being executed either interactively or from a script, which isn't present in $funcstack. so there's that ๐ซ
๐ functrace
This array contains the names and line numbers of the callers corresponding to the functions currently being executed. The format of each element is:
name:lineno
Callers are also shown for sourced files โ the caller being the point where the source or . command was executed. no crumbs ๐
๐ธ THE ZSH/PCRE MODULE ๐ธ
Okay bestie, so the zsh/pcre module is the one that lets you do perl-compatible regex stuff right there in your shell, and it hooks you up with some builtins:
pcre_compile [ -aimxs ] PCREโ this one compiles a perl-compatible regular expression. Like, it gets it ready so you can match with it later. The flags are:-aโ forces the pattern to be anchored. No drifting allowed ๐-iโ compiles a case-insensitive pattern.ABCandabcare the same vibes now.-mโ compiles a multi-line pattern; meaning^and$will match newlines within the pattern. Iconic multiline behaviour.-xโ compiles an extended pattern, wherein whitespace and#comments are ignored. So you can make it pretty and comment it, slay.-sโ makes the dot metacharacter match all characters, including those that indicate newline. The.ate and left no crumbs.
pcre_studyโ studies the previously-compiled PCRE, which may result in faster matching. It's giving study session before the exam, but for your regex. ๐งpcre_match [ -v var ] [ -a arr ] [ -n offset ] [ -b ] stringโ returns successfully if string matches the previously-compiled PCRE. So you compile once, then match as many times as you want, no cap.
Upon successful match, if the expression captures substrings within parentheses, pcre_match will set the array match to those substrings โ unless the -a option is given, in which case it will set the array arr instead. Similarly, the variable MATCH will be set to the entire matched portion of the string, unless the -v option is given, in which case the variable var will be set. And listen: no variables are altered if there is no successful match. Zero. Nada. ๐
A -n option starts searching for a match from the byte offset position in string.
If the -b option is given, the variable ZPCRE_OP will be set to an offset pair string, representing the byte offset positions of the entire matched portion within string. For example, a ZPCRE_OP set to "32 45" indicates that the matched portion began on byte offset 32 and ended on byte offset 44. Here, byte offset position 45 is the position directly after the matched portion. Keep in mind that the byte position isn't necessarily the same as the character position when UTF-8 characters are involved โ so like, lowkey be careful. Consequently, the byte offset positions are only to be relied on in the context of using them for subsequent searches on string, using an offset position as an argument to the -n option. This is mostly used to implement the "find all non-overlapping matches" functionality.
A simple example of "find all non-overlapping matches":
string="The following zip codes: 78884 90210 99513"
pcre_compile -m "\d{5}"
accum=()
pcre_match -b -- $string
while [[ $? -eq 0 ]] do
b=($=ZPCRE_OP)
accum+=$MATCH
pcre_match -b -n $b[2] -- $string
done
print -l $accum
The zsh/pcre module also makes available the following test condition:
expr -pcre-match pcreโ matches a string against a perl-compatible regular expression. Fr fr, it's the moment.
For example:
[[ "$text" -pcre-match ^d+$ ]] &&
print text variable contains only "d's".
If the REMATCH_PCRE option is set, the =~ operator is equivalent to -pcre-match, and the NO_CASE_MATCH option may be used. But heads up bestie: NO_CASE_MATCH never applies to the pcre_match builtin โ instead use the -i switch of pcre_compile. Don't mix them up, iykyk. ๐
๐ THE ZSH/PARAM/PRIVATE MODULE ๐
So the zsh/param/private module is used to create parameters whose scope is limited to the current function body, and not to other functions called by the current function. Main character parameter energy: it knows its lane. โจ
This module provides a single autoloaded builtin:
private [ {+|-}AHUahlmrtux ] [ {+|-}EFLRZi [ n ] ] [ name[=value] ... ]โ theprivatebuiltin accepts all the same options and arguments aslocal(zshbuiltins(1)) except for the-Toption. Tied parameters may not be made private. Sorry to tied parameters, they're not invited.
The -p option is presently a no-op because the state of private parameters cannot reliably be reloaded. This also applies to printing private parameters with typeset -p. So like, don't rely on it, it's giving placeholder. ๐ซ
If used at the top level (outside a function scope), private creates a normal parameter in the same manner as declare or typeset. A warning about this is printed if WARN_CREATE_GLOBAL is set (zshoptions(1)). Used inside a function scope, private creates a local parameter similar to one declared with local, except having special properties noted below.
Special parameters which expose or manipulate internal shell state โ such as ARGC, argv, COLUMNS, LINES, UID, EUID, IFS, PROMPT, RANDOM, SECONDS, etc. โ cannot be made private unless the -h option is used to hide the special meaning of the parameter. This may change in the future, so stay tuned ๐.
As with other typeset equivalents, private is both a builtin and a reserved word, so arrays may be assigned with the parenthesized word list name=(value...) syntax. However, the reserved word private is not available until zsh/param/private is loaded, so care must be taken with order of execution and parsing for function definitions which use private. To compensate for this, the module also adds the option -P to the local builtin to declare private parameters. Iconic workaround, honestly.
For example, this construction fails if zsh/param/private has not yet been loaded when bad_declaration is defined:
bad_declaration() {
zmodload zsh/param/private
private array=( one two three )
}
This construction works because local is already a keyword, and the module is loaded before the statement is executed:
good_declaration() {
zmodload zsh/param/private
local -P array=( one two three )
}
The following is usable in scripts but may have trouble with autoload:
zmodload zsh/param/private
iffy_declaration() {
private array=( one two three )
}
The private builtin may always be used with scalar assignments and for declarations without assignments. Good to know, bestie.
Parameters declared with private have the following properties:
- Within the function body where it is declared, the parameter behaves as a local, except as noted above for tied or special parameters.
- The type of a parameter declared private cannot be changed in the scope where it was declared, even if the parameter is unset. Thus an array cannot be assigned to a private scalar, etc. It's locked in, periodt.
- Within any other function called by the declaring function, the private parameter does NOT hide other parameters of the same name, so for example a global parameter of the same name is visible and may be assigned or unset. This includes calls to anonymous functions, although that may also change in the future. However, the private name may not be created outside the local scope when it was not previously declared.
- An exported private remains in the environment of inner scopes but appears unset for the current shell in those scopes. Generally, exporting private parameters should be avoided. Like, just don't. ๐ โโ๏ธ
Note that this differs from the static scope defined by compiled languages derived from C, in that a new call to the same function creates a new scope โ i.e., the parameter is still associated with the call stack rather than with the function definition. It differs from ksh typeset -S because the syntax used to define the function has no bearing on whether the parameter scope is respected.
๐ฆ THE ZSH/REGEX MODULE ๐ฆ
The zsh/regex module makes available the following test condition:
expr -regex-match regexโ matches a string against a POSIX extended regular expression. On successful match, the matched portion of the string will normally be placed in theMATCHvariable. If there are any capturing parentheses within the regex, then thematcharray variable will contain those. If the match is not successful, then the variables will not be altered. Same energy as before: no match, no changes. ๐
For example:
[[ alphabetical -regex-match ^a([^a]+)a([^a]+)a ]] &&
print -l $MATCH X $match
If the option REMATCH_PCRE is not set, then the =~ operator will automatically load this module as needed and will invoke the -regex-match operator. So convenient, honestly.
If BASH_REMATCH is set, then the array BASH_REMATCH will be set instead of MATCH and match. Just so you know which variable is getting the goods. ๐
Note that the zsh/regex module logic relies on the host system. The same expr and regex pair could produce different results on different platforms if a regex with non-standard syntax is given. So like, vibe check your platform, bestie.
For example, no syntax for matching a word boundary is defined in the POSIX extended regular expression standard. GNU libc and BSD libc both provide such syntaxes as extensions (\b and [[:<:]]/[[:>:]] respectively), but neither of these syntaxes is supported by both of these implementations. So it's giving platform-exclusive DLC. ๐ญ
Refer to the regcomp(3) and re_format(7) manual pages on your system for locally-supported syntax. Go read them, they're literally the source of truth. ๐
THE ZSH/SCHED MODULE โฐ
okay so the zsh/sched module is your little personal assistant, bestie โ it gives you one builtin command and one parameter and lets you schedule stuff to run later. it's giving "I have a secretary and she's me" ๐
sched [-o] [+]hh:mm[:ss] command ...
sched [-o] [+]seconds command ...
sched [ -item ]
โจ What it does
Makes an entry in the scheduled list of commands to execute. The time can be specified in either absolute or relative time, and either as hours, minutes and (optionally) seconds separated by a colon, or seconds alone.
An absolute number of seconds indicates the time since the epoch (1970/01/01 00:00) โ which is super useful in combination with the features in the zsh/datetime module, see the zsh/datetime module entry in zshmodules(1). ๐ฐ๏ธ
โจ The three moods of sched
- No arguments โ prints the list of scheduled commands, bestie. And if the scheduled command has the
-oflag set, that shows up at the start of the command. ๐ - The argument
-itemโ removes the given item from the list. careful though: the numbering of the list is continuous and entries are in time order, so the numbering can totally change when entries are added or deleted. ๐ญ - With a time and a command โ schedules it, obviously. main character behaviour.
โจ When do these things actually run
Commands are executed either immediately before a prompt, or while the shell's line editor is waiting for input. In the latter case it's super useful to be able to produce output that doesn't interfere with the line being edited. Providing the option -o causes the shell to clear the command line before the event and redraw it afterwards. ๐
Use -o with any scheduled event that produces visible output to the terminal! It's not needed, for example, with output that updates a terminal emulator's title bar. iykyk.
To effect changes to the editor buffer when an event executes, use the zle command with no arguments to test whether the editor is active, and if it is, then use zle widget to access the editor via the named widget. ๐ง
โจ availability tea โ
The sched builtin is not made available by default when the shell starts in a mode emulating another shell. You can make it available with the command:
zmodload -F zsh/sched b:sched
โจ zsh_scheduled_events
A readonly array corresponding to the events scheduled by the sched builtin. ๐ฅ
The indices of the array correspond to the numbers shown when sched is run with no arguments (provided that the KSH_ARRAYS option is not set). The value of the array consists of:
- the scheduled time in seconds since the epoch (see the section
The zsh/datetime Modulefor facilities for using this number), - followed by a colon,
- followed by any options (which may be empty but will be preceded by a
-otherwise), - followed by a colon,
- followed by the command to be executed.
Bestie, use the sched builtin for manipulating the events. Note that this will have an immediate effect on the contents of the array, so that indices may become invalid. Don't come crying to me when index 3 is suddenly index 2 ๐
THE ZSH/NET/SOCKET MODULE ๐
The zsh/net/socket module makes available one builtin command:
zsocket [ -altv ] [ -d fd ] [ args ]
zsocket is implemented as a builtin to allow full use of shell command line editing, file I/O, and job control mechanisms. literally iconic โ a socket command that plays nice with your whole shell setup ๐
Outbound Connections ๐ค
zsocket [ -v ] [ -d fd ] filename
Open a new Unix domain connection to filename. The shell parameter REPLY will be set to the file descriptor associated with that connection. Currently, only stream connections are supported. ๐ฆ
- If
-dis specified, its argument will be taken as the target file descriptor for the connection. - In order to elicit more verbose output, use
-v.
File descriptors can be closed with normal shell syntax when no longer needed, for example:
exec {REPLY}>&-
Inbound Connections ๐ฅ
zsocket -l [ -v ] [ -d fd ] filename
zsocket -l will open a socket listening on filename. The shell parameter REPLY will be set to the file descriptor associated with that listener. The file descriptor remains open in subshells and forked external executables. ๐
- If
-dis specified, its argument will be taken as the target file descriptor for the connection. - In order to elicit more verbose output, use
-v.
zsocket -a [ -tv ] [ -d targetfd ] listenfd
zsocket -a will accept an incoming connection to the socket associated with listenfd. The shell parameter REPLY will be set to the file descriptor associated with the inbound connection. The file descriptor remains open in subshells and forked external executables. ๐ซถ
- If
-dis specified, its argument will be taken as the target file descriptor for the connection. - If
-tis specified,zsocketwill return if no incoming connection is pending. Otherwise it will wait for one. (no cap,-tis the "don't just stand there" flag ๐) - In order to elicit more verbose output, use
-v.
โจ THE ZSH/STAT MODULE โจ
Okay bestie so this module is literally the plug for the stat system call, and it gives you one builtin command that answers to two possible names. Two names, one icon ๐
:
zstat [ -gnNolLtTrs ] [ -f fd ] [ -H hash ] [ -A array ] [ -F fmt ]
[ +element ] [ file ... ]
stat ...
It's a front end to the stat system call (peep stat(2) if you want the receipts). Same command, two names โ but because stat is super often used by an external command, it's recommended you only use the zstat form. You can set that up by loading the module with:
zmodload -F zsh/stat b:zstat
If the stat call fails, the appropriate system error message gets printed and status 1 is returned. The fields of struct stat give you info about the files you passed as arguments. And on top of the stuff from the stat call, there's one extra element, link. Here's the whole lineup:
deviceโ the number of the device the file lives on.inodeโ the unique number of the file on this device (the "inode" number).modeโ the mode of the file, i.e. its type and access permissions. With the-soption this comes back as a string matching the first column in the display of thels -lcommand.nlinkโ how many hard links point at the file.uidโ the user ID of the file's owner. With-s, this shows up as a user name.gidโ the group ID of the file. With-s, displayed as a group name.rdevโ the raw device number. Only useful for special devices, lowkey niche but valid.sizeโ the size of the file in bytes.atime,mtime,ctimeโ the last access, modification and inode change times of the file, respectively, as the number of seconds since midnight GMT on 1st January, 1970. With-sthese print as strings for the local time zone; the format can be altered with-F, and with-gthe times are in GMT.blksizeโ the number of bytes in one allocation block on the device the file resides on.blockโ the number of disk blocks used by the file.linkโ if the file is a link and-Lis in effect, this contains the name of the file linked to; otherwise it's empty. Note that if this element is selected (zstat +link) then-Lis automatically used. Sneaky but slay.
You pick a particular element by including its name preceded by a + in the option list โ only one element is allowed, bestie, don't get greedy. The element may be shortened to any unique set of leading characters. Otherwise, all elements get shown for all files. Periodt.
๐ธ Options ๐ธ
-Aarray โ instead of displaying results on standard output, assign them to an array, onestruct statelement per array element for each file in order. In this case neither the name of the element nor the name of the files appears in array unless the-tor-noptions were given, respectively. If-tis given, the element name appears as a prefix to the appropriate array element; if-nis given, the file name appears as a separate array element preceding all the others. Other formatting options are respected.-Hhash โ similar to-A, but instead assign the values to hash. The keys are the elements listed above. If the-noption is provided then the name of the file is included in the hash with keyname.-ffd โ use the file on file descriptor fd instead of named files; no list of file names is allowed in this case.-Ffmt โ supplies astrftime(seestrftime(3)) string for the formatting of the time elements. The format string supports all of the zsh extensions described in the section EXPANSION OF PROMPT SEQUENCES inzshmisc(1). In particular,-F %s.%Ncan be used to show timestamps with nanosecond precision if supported by the system. The-soption is implied.-gโ show the time elements in the GMT time zone. The-soption is implied.-lโ list the names of the type elements (to standard output or an array as appropriate) and return immediately; arguments, and options other than-A, are ignored.-Lโ perform anlstat(seelstat(2)) rather than astatsystem call. In this case, if the file is a link, information about the link itself rather than the target file is returned. This option is required to make thelinkelement useful. It's important to note that this is the exact opposite fromls(1), etc. (Yes, really. Don't @ me, that's just how it is ๐)-nโ always show the names of files. Usually these are only shown when output is to standard output and there's more than one file in the list.-Nโ never show the names of files.-oโ if a raw file mode is printed, show it in octal, which is more useful for human consumption than the default of decimal. A leading zero will be printed in this case. Note that this does not affect whether a raw or formatted file mode is shown โ that's controlled by the-rand-soptions โ nor whether a mode is shown at all.-rโ print raw data (the default format) alongside string data (the-sformat); the string data appears in parentheses after the raw data.-sโ print mode,uid,gidand the three time elements as strings instead of numbers. In each case the format is like that ofls -l.-tโ always show the type names for the elements ofstruct stat. Usually these are only shown when output is to standard output and no individual element has been selected.-Tโ never show the type names of thestruct statelements.
๐ฆ THE ZSH/SYSTEM MODULE ๐ฆ
The zsh/system module hands you a whole lil collection of builtin commands and parameters. Grab a snack, we're going in.
Builtins
๐ syserror
syserror [ -e errvar ] [ -p prefix ] [ errno | errname ]
This command prints out the error message associated with errno, a system error number, followed by a newline to standard error.
Instead of the error number, a name errname, for example ENOENT, may be used. The set of names is the same as the contents of the array errnos, see below. iykyk.
If the string prefix is given, it's printed in front of the error message, with no intervening space โ snuggle those two together.
If errvar is supplied, the entire message, without a newline, is assigned to the parameter named errvar and nothing is output. Silent but useful โจ
Return status tea โ:
0โ the message was successfully printed (although it may not be useful if the error number was out of the system's range).1โ there was an error in the parameters.2โ the error name was not recognised (no message is printed for this, so don't sit there waiting for one).
๐ sysopen
sysopen [ -arw ] [ -m permissions ] [ -o options ]
-u fd file
This command opens a file. The -r, -w and -a flags indicate whether the file should be opened for reading, writing and appending, respectively. The -m option lets the initial permissions used when creating a file be specified in octal form. The file descriptor is specified with -u. Either an explicit file descriptor in the range 0 to 9 can be specified, or a variable name can be given, to which the file descriptor number will be assigned.
The -o option lets you specify various system specific options as a comma-separated list. Here's the possible lineup โ note that, depending on the system, some may not be available:
cloexecโ mark file to be closed when other programs are executed (else the file descriptor remains open in subshells and forked external executables).create,creatโ create file if it does not exist.exclโ create file, error if it already exists.noatimeโ suppress updating of the fileatime.nofollowโ fail if file is a symbolic link.nonblockโ the file is opened in nonblocking mode.syncโ request that writes wait until data has been physically written.truncate,truncโ truncate file to size0.
To close the file, use one of these bad boys:
exec {fd}<&-
exec {fd}>&-
๐ sysread
sysread [ -c countvar ] [ -i infd ] [ -o outfd ]
[ -s bufsize ] [ -t timeout ] [ param ]
Perform a single system read from file descriptor infd, or zero if that's not given. The result of the read is stored in param or REPLY if that's not given. If countvar is given, the number of bytes read is assigned to the parameter named by countvar.
The maximum number of bytes read is bufsize, or 8192 if that's not given โ however, the command returns as soon as any number of bytes was successfully read. So like, it's not gonna sit there waiting to fill the whole buffer, okay?
If timeout is given, it specifies a timeout in seconds, which may be zero to poll the file descriptor. This is handled by the poll system call if available, otherwise the select system call if available.
If outfd is given, an attempt is made to write all the bytes just read to the file descriptor outfd. If this fails โ because of a system error other than EINTR, or because of an internal zsh error during an interrupt โ the bytes read but not written are stored in the parameter named by param if supplied (no default is used in this case), and the number of bytes read but not written is stored in the parameter named by countvar if that is supplied. If it was successful, countvar contains the full number of bytes transferred, as usual, and param is not set. ๐ซถ
The error EINTR (interrupted system call) is handled internally so that shell interrupts are transparent to the caller. Any other error causes a return.
The possible return statuses are:
0โ at least one byte of data was successfully read and, if appropriate, written. ๐1โ there was an error in the parameters to the command. This is the only error for which a message is printed to standard error.2โ there was an error on the read, or on polling the input file descriptor for a timeout. The parameterERRNOgives the error.3โ data were successfully read, but there was an error writing them to outfd. The parameterERRNOgives the error. ๐ญ4โ the attempt to read timed out. Note this does not setERRNO, because like, it's not a system error, bestie.5โ no system error occurred, but zero bytes were read. This usually indicates end of file. The parameters are set according to the usual rules; no write to outfd is attempted.
sysseek [ -u fd ] [ -w start|end|current ] offset
The current file position at which future reads and writes will take place is adjusted to the specified byte offset. The offset is evaluated as a math expression. The -u option lets you specify the file descriptor. By default the offset is specified relative to the start of the file, but with the -w option it's possible to say the offset should be relative to the current position or the end of the file. ๐ฏ
syswrite [ -c countvar ] [ -o outfd ] data
The data (a single string of bytes) are written to the file descriptor outfd, or 1 if that's not given, using the write system call. Multiple write operations may be used if the first doesn't write all the data. ๐พ
If countvar is given, the number of bytes written is stored in the parameter named by countvar; this may not be the full length of data if an error occurred.
The error EINTR (interrupted system call) is handled internally by retrying; otherwise an error causes the command to return. For example, if the file descriptor is set to non-blocking output, an error EAGAIN (on some systems, EWOULDBLOCK) may result in the command returning early.
The return status may be 0 for success, 1 for an error in the parameters to the command, or 2 for an error on the write; no error message is printed in the last case, but the parameter ERRNO will reflect the error that occurred.
zsystem flock [ -t timeout ] [ -i interval ] [ -f var ] [-er] file
zsystem flock -u fd_expr
The builtin zsystem's subcommand flock performs advisory file locking (via the fcntl(2) system call) over the entire contents of the given file. This form of locking requires the processes accessing the file to cooperate; its most obvious use is between two instances of the shell itself. ๐
In the first form the named file, which must already exist, is locked by opening a file descriptor to the file and applying a lock to the file descriptor. The lock terminates when the shell process that created the lock exits; it's therefore often convenient to create file locks within subshells, since the lock is automatically released when the subshell exits. Note that use of the print builtin with the -u option will, as a side effect, release the lock โ as will redirection to the file in the shell holding the lock. To work around this use a subshell, e.g. (print message) >> file. Status 0 is returned if the lock succeeds, else status 1.
In the second form the file descriptor given by the arithmetic expression fd_expr is closed, releasing a lock. The file descriptor can be queried by using the -f var form during the lock; on a successful lock, the shell variable var is set to the file descriptor used for locking. The lock will be released if the file descriptor is closed by any other means, for example using exec {var}>&-; however, the form described here performs a safety check that the file descriptor is in use for file locking. ๐ซถ
By default the shell waits indefinitely for the lock to succeed. The option -t timeout specifies a timeout for the lock in seconds; fractional seconds are allowed. During this period, the shell will attempt to lock the file every interval seconds if the -i interval option is given, otherwise once a second. (This interval is shortened before the last attempt if needed, so that the shell waits only until the timeout and not longer.) If the attempt times out, status 2 is returned. โฐ
(Note: timeout is limited to2^30-1seconds (about 34 years), and interval to0.999 * LONG_MAXmicroseconds (only about 35 minutes on 32-bit systems).)
If the option -e is given, the file descriptor for the lock is preserved when the shell uses exec to start a new process; otherwise it is closed at that point and the lock released.
If the option -r is given, the lock is only for reading, otherwise it is for reading and writing. The file descriptor is opened accordingly.
zsystem supports subcommand
The builtin zsystem's subcommand supports tests whether a given subcommand is supported. It returns status 0 if so, else status 1. It operates silently unless there was a syntax error (i.e. the wrong number of arguments), in which case status 255 is returned. Status 1 can indicate one of two things: subcommand is known but not supported by the current operating system, or subcommand is not known (possibly because this is an older version of the shell from before it was implemented). ๐ต๏ธ
๐งฎ Math Functions ๐งฎ
systell(fd)
The systell math function returns the current file position for the file descriptor passed as an argument. That's it, that's the whole function, and honestly? iconic minimalism. โจ
๐ฆ Parameters ๐ฆ
errnos
A readonly array of the names of errors defined on the system. These are typically macros defined in C by including the system header file errno.h. The index of each name (assuming the option KSH_ARRAYS is unset) corresponds to the error number. Error numbers num before the last known error which have no name are given the name Enum in the array. ๐
Note that aliases for errors are not handled; only the canonical name is used.
sysparams
A readonly associative array. The keys are:
pidโ returns the process ID of the current process, even in subshells. Compare$$, which returns the process ID of the main shell process. ๐ชชppidโ returns the current process ID of the parent of the current process, even in subshells. Compare$PPID, which returns the process ID of the initial parent of the main shell process.procsubstpidโ returns the process ID of the last process started for process substitution, i.e. the<(...)and>(...)expansions. ๐
โจ THE ZSH/NET/TCP MODULE โจ
bestie this module gives you exactly one builtin and it's a whole networking era:
ztcp [ -acflLtv ] [ -d fd ] [ args ]
ztcp is implemented as a builtin so you get full use of shell command line editing, file I/O, and job control mechanisms. it's giving "netcat but make it a shell builtin" energy ๐
- if you run
ztcpwith no options, it just outputs the contents of its session table (like a little guest list of your connections ๐) - if you run it with only the option
-L, it outputs the contents of the session table in a format suitable for automatic parsing. the option is ignored if given with a command to open or close a session. the output is a set of lines, one per session, each containing the following elements separated by spaces: - File descriptor โ the file descriptor in use for the connection. for normal inbound (
I) and outbound (O) connections this may be read and written by the usual shell mechanisms. however, it should only be closed withztcp -c. - Connection type โ a letter indicating how the session was created:
Zโ a session created with thezftpcommand.Lโ a connection opened for listening withztcp -l.Iโ an inbound connection accepted withztcp -a.Oโ an outbound connection created withztcp host ....
- The local host โ this is usually set to an all-zero IP address, because the address of the localhost is irrelevant (we simply do not care ๐).
- The local port โ this is likely to be zero unless the connection is for listening.
- The remote host โ the fully qualified domain name of the peer, if available, else an IP address. it is an all-zero IP address for a session opened for listening.
- The remote port โ this is zero for a connection opened for listening.
๐ธ Outbound Connections ๐ธ
ztcp [ -v ] [ -d fd ] host [ port ]
open a new TCP connection to host. if the port is omitted, it will default to port 23. the connection gets added to the session table, and the shell parameter REPLY is set to the file descriptor associated with that connection. periodt โจ
if -d is specified, its argument is taken as the target file descriptor for the connection.
in order to elicit more verbose output, use -v.
๐ฆ Inbound Connections ๐ฆ
ztcp -l [ -v ] [ -d fd ] port
ztcp -l opens a socket listening on TCP port. the socket gets added to the session table, and the shell parameter REPLY is set to the file descriptor associated with that listener. you're literally a server now, main character energy ๐
if -d is specified, its argument is taken as the target file descriptor for the connection.
in order to elicit more verbose output, use -v.
ztcp -a [ -tv ] [ -d targetfd ] listenfd
ztcp -a accepts an incoming connection to the port associated with listenfd. the connection gets added to the session table, and the shell parameter REPLY is set to the file descriptor associated with the inbound connection ๐ซถ
if -d is specified, its argument is taken as the target file descriptor for the connection.
if -t is specified, ztcp will return if no incoming connection is pending. otherwise it will wait for one (and yes that means it just sits there, blocking, living its truth ๐ญ).
in order to elicit more verbose output, use -v.
๐งน Closing Connections ๐งน
ztcp -cf [ -v ] [ fd ]
ztcp -c [ -v ] [ fd ]
ztcp -c closes the socket associated with fd. the socket gets removed from the session table. if fd is not specified, ztcp closes everything in the session table. goodbye to the whole friend group ๐
normally, sockets registered by zftp (see zshmodules(1)) cannot be closed this way. in order to force such a socket closed, use -f.
in order to elicit more verbose output, use -v.
๐ Example ๐
here's how to create a TCP connection between two instances of zsh. we need to pick an unassigned port; here we use the randomly chosen 5123.
on host1:
zmodload zsh/net/tcp
ztcp -l 5123
listenfd=$REPLY
ztcp -a $listenfd
fd=$REPLY
the second from last command blocks until there is an incoming connection (it's giving waiting-for-a-text-back energy ngl ๐).
now create a connection from host2 (which may, of course, be the same machine):
zmodload zsh/net/tcp
ztcp host1 5123
fd=$REPLY
now on each host, $fd contains a file descriptor for talking to the other. for example, on host1:
print This is a message >&$fd
and on host2:
read -r line <&$fd; print -r - $line
prints This is a message ๐
to tidy up, on host1:
ztcp -c $listenfd
ztcp -c $fd
and on host2:
ztcp -c $fd
โจ THE ZSH/TERMCAP MODULE โจ
this module makes available one builtin command:
echotc cap [ arg ... ]
output the termcap value corresponding to the capability cap, with optional arguments.
the zsh/termcap module also makes available one parameter:
termcapโ an associative array that maps termcap capability codes to their values. it's a whole lil dictionary of terminal lore, iykyk ๐ฅ
โจ THE ZSH/TERMINFO MODULE โจ
this module makes available one builtin command:
echoti cap [ arg ]
output the terminfo value corresponding to the capability cap, instantiated with arg if applicable.
the zsh/terminfo module also makes available one parameter:
terminfoโ an associative array that maps terminfo capability names to their values ๐
โจ THE ZSH/WATCH MODULE โจ
the zsh/watch module can be used to report when specific users log in or out. this is controlled via the following parameters โ it's literally surveillance but make it cute ๐ต๏ธโโ๏ธ
LOGCHECKโ the interval in seconds between checks for login/logout activity using thewatchparameter.watch <S> <Z> (WATCH <S>)โ an array (colon-separated list) of login/logout events to report.
if it contains the single word all, then all login/logout events are reported. if it contains the single word notme, then all events are reported as with all except $USERNAME (we stan not watching ourselves).
an entry in this list may consist of a username, an @ followed by a remote hostname, and a % followed by a line (tty). any of these may be a pattern (be sure to quote this during the assignment to watch so that it does not immediately perform file generation); the setting of the EXTENDED_GLOB option is respected. any or all of these components may be present in an entry; if a login/logout event matches all of them, it is reported.
for example, with the EXTENDED_GLOB option set, the following:
watch=('^(pws|barts)')
causes reports for activity associated with any user other than pws or barts. no cap, that's the whole trick โจ
WATCHFMTโ the format of login/logout reports if thewatchparameter is set. default is%n has %a %l from %m. it recognizes the following escape sequences:%nโ the name of the user that logged in/out.%aโ the observed action, i.e."logged on"or"logged off".%lโ the line (tty) the user is logged in on.%Mโ the full hostname of the remote host.%mโ the hostname up to the first.. if only the IP address is available or the utmp field contains the name of an X-windows display, the whole name is printed.
NOTE: the%mand%Mescapes will work only if there is a host name field in the utmp on your machine. otherwise they are treated as ordinary strings. so like, don't come for the module if your utmp is built different ๐
%F{color}(%f) โ start (stop) using a different foreground color.%K{color}(%k) โ start (stop) using a different background color.%S(%s) โ start (stop) standout mode.%U(%u) โ start (stop) underline mode.%B(%b) โ start (stop) boldface mode.%t,%@โ the time, in 12-hour, am/pm format.%Tโ the time, in 24-hour format.%wโ the date inday-ddformat.%Wโ the date inmm/dd/yyformat.%Dโ the date inyy-mm-ddformat.%D{string}โ the date formatted as string using thestrftimefunction, with zsh extensions as described by EXPANSION OF PROMPT SEQUENCES inzshmisc(1).%(x:true-text:false-text)โ specifies a ternary expression. the character following thexis arbitrary; the same character is used to separate the text for the "true" result from that for the "false" result. both the separator and the right parenthesis may be escaped with a backslash. ternary expressions may be nested. (nested ternaries, the chaos we love ๐ญ)
the test character x may be any one of l, n, m or M, which indicate a true result if the corresponding escape sequence would return a non-empty value; or it may be a, which indicates a true result if the watched user has logged in, or false if he has logged out. other characters evaluate to neither true nor false; the entire expression is omitted in this case.
if the result is true, then the true-text is formatted according to the rules above and printed, and the false-text is skipped. if false, the true-text is skipped and the false-text is formatted and printed. either or both of the branches may be empty, but both separators must be present in any case.
furthermore, the zsh/watch module makes available one builtin command:
log
list all users currently logged in who are affected by the current setting of the watch parameter ๐
โจ THE ZSH/ZFTP MODULE โจ
the zsh/zftp module makes available one builtin command:
zftp subcommand [ args ]
the zsh/zftp module is a client for FTP (file transfer protocol). it is implemented as a builtin to allow full use of shell command line editing, file I/O, and job control mechanisms. often, users will access it via shell functions providing a more powerful interface; a set is provided with the zsh distribution and is described in zshzftpsys(1). however, the zftp command is entirely usable in its own right ๐ซถโจ
- All the commands are just
zftpplus the name of a subcommand, bestie. Those subcommands are listed right below ๐ - The return status of each subcommand is supposed to reflect whether the remote operation slayed or flopped.
- Peep the description of the variable
ZFTP_VERBOSEfor more info on how responses from the server may be printed ๐
Subcommands
openโopen host[:port] [ user [ password [ account ] ] ]- Opens a brand-new FTP session to host, which can be the name of a TCP/IP-connected host or an IP number in the standard dot notation. Iconic.
- If the argument is shaped like
host:port, it opens a connection to TCP port port instead of the standard FTP port21. That port may be the name of a TCP service or a number โ see the description ofZFTP_PORTbelow for the tea ๐ต - If you're using IPv6 addresses in colon format, surround the host with quoted square brackets so it doesn't get confused with the port, like
'[fe80::203:baff:fe02:8b56]'. For consistency, this is allowed with all forms of host ๐ซถ - The remaining arguments get passed to the
loginsubcommand. But heads up: if you supply no arguments beyond host,openwill not automatically calllogin. And if you supply no arguments at all,openuses the parameters set by theparamssubcommand. - After a successful open, the shell variables
ZFTP_HOST,ZFTP_PORT,ZFTP_IPandZFTP_SYSTEMare available โ seeVariablesbelow โจ
login,userโlogin [ name [ password [ account ] ] ]/user [ name [ password [ account ] ] ]- Logs in the user name with parameters password and account. Any of the parameters can be left out, and will be read from standard input if needed (name is always needed, no cap).
- If standard input is a terminal, a prompt for each one gets printed on standard error, and password will not be echoed ๐
- If any of the parameters are not used, a warning message is printed.
- After a successful login, the shell variables
ZFTP_USER,ZFTP_ACCOUNTandZFTP_PWDare available โ seeVariablesbelow. - This command may be re-issued when a user is already logged in, and the server will first be reinitialized for a new user ๐ฅ
paramsโparams [ host [ user [ password [ account ] ] ] ]/params -- Stores the given parameters for a later
opencommand with no arguments. Only the ones you actually typed on the command line get remembered, periodt. - If no arguments are given, the parameters currently set are printed โ though the password shows up as a line of stars โญ The return status is one if no parameters were set, and zero otherwise.
- Any of the parameters may be specified as a
?, which may need to be quoted to protect it from shell expansion. In that case the appropriate parameter is read from stdin just like with theloginsubcommand, including the special handling of the password. - If the
?is followed by a string, that string is used as the prompt for reading the parameter instead of the default message (any necessary punctuation and whitespace should be included at the end of the prompt). - The first letter of the parameter (only) may be quoted with a
\โ hence an argument"\\$word"guarantees that the string from the shell parameter$wordwill be treated literally, whether or not it begins with a?๐ - If instead you give a single
-, the existing parameters (if any) are deleted. In that case, callingopenwith no arguments will cause an error ๐ญ - The list of parameters is not deleted after a
close, but it will be deleted if thezsh/zftpmodule is unloaded. - For example:
- Stores the given parameters for a later
zftp params ftp.elsewhere.xx juser '?Password for juser: '
- ...will store the host
ftp.elsewhere.xxand the userjuser, and then prompt the user for the corresponding password with the given prompt ๐
testโ tests the connection, bestie:- If the server has reported that it has closed the connection (maybe due to a timeout), it returns status
2. - If no connection was open anyway, it returns status
1. - Else it returns status
0๐ฆ - The
testsubcommand is silent, apart from messages printed by the$ZFTP_VERBOSEmechanism, or error messages if the connection closes. And there's no network overhead for this test โ free vibe check, we love to see it. - This test is only supported on systems with either the
select(2)orpoll(2)system calls; otherwise the messagenot supported on this systemis printed instead ๐ - The
testsubcommand will automatically be called at the start of any other subcommand for the current session when a connection is open.
- If the server has reported that it has closed the connection (maybe due to a timeout), it returns status
cdโcd directorychanges the remote directory to directory. Also alters the shell variableZFTP_PWDโจcdupโ changes the remote directory to the one higher in the directory tree. Note thatcd ..will also work correctly on non-UNIX systems ๐dirโdir [ arg ... ]gives a (verbose) listing of the remote directory. The args are passed directly to the server. The command's behaviour is implementation dependent, but a UNIX server will typically interpret args as arguments to thelscommand, and with no arguments return the result ofls -l. The directory is listed to standard output ๐ธlsโls [ arg ... ]gives a (short) listing of the remote directory. With no arg, it produces a raw list of the files in the directory, one per line. Otherwise, up to the vagaries of the server implementation, it behaves similar todir.typeโtype [ type ]changes the type for the transfer to type, or prints the current type if type is absent. The allowed values areA(ASCII),I(Image, i.e. binary), orB(a synonym forI) ๐- The FTP default for a transfer is ASCII. However, if
zftpfinds that the remote host is a UNIX machine with 8-bit byes, it will automatically switch to using binary for file transfers uponopen. This can subsequently be overridden. - The transfer type is only passed to the remote host when a data connection is established; this command involves no network overhead ๐ง
- The FTP default for a transfer is ASCII. However, if
asciiโ the same astype A.binaryโ the same astype I.modeโmode [ S | B ]sets the mode type to stream (S) or block (B). Stream mode is the default; block mode is not widely supported ๐ซremote,localโremote file .../local [ file ... ]- Prints the size and last modification time of the remote or local files.
- If there's more than one item on the list, the name of the file is printed first.
- The first number is the file size, and the second is the last modification time of the file in the format
CCYYMMDDhhmmSS, consisting of year, month, date, hour, minutes and seconds in GMT ๐ - Note that this format, including the length, is guaranteed, so time strings can be directly compared via the
[[builtin's<and>operators, even if they're too long to be represented as integers. Slay. - Not all servers support the commands for retrieving this information. In that case, the
remotecommand will print nothing and return status2โ compared with status1for a file not found ๐ญ - The
localcommand (but notremote) may be used with no arguments, in which case the information comes from examining file descriptor zero. This is the same file as seen by aputcommand with no further redirection.
getโget file ...retrieves all files from the server, concatenating them and sending them to standard output ๐putโput file ...reads, for each file, a file from standard input and sends that to the remote host with the given name.appendโappend file ...is likeput, but if the remote file already exists, data is appended to it instead of overwriting it ๐getat,putat,appendatโgetat file point/putat file point/appendat file point- These are versions of
get,putandappendwhich will start the transfer at the given point in the remote file. Super useful for appending to an incomplete local file. - However, note that this ability is not universally supported by servers (and is not quite the behaviour specified by the standard) ๐
- These are versions of
deleteโdelete file ...deletes the list of files on the server.mkdirโmkdir directorycreates a new directory directory on the server โจrmdirโrmdir directorydeletes the directory directory on the server.renameโrename old-name new-namerenames file old-name to new-name on the server.siteโsite arg ...sends a host-specific command to the server. You'll probably only need this if the server instructs you to use it ๐ฆquoteโquote arg ...sends the raw FTP command sequence to the server. You should be familiar with the FTP command set as defined inRFC959before doing this, fr fr. Useful commands may includeSTATandHELP.- Also note the mechanism for returning messages as described for the variable
ZFTP_VERBOSEbelow โ in particular, that all messages from the control connection are sent to standard error ๐
- Also note the mechanism for returning messages as described for the variable
close,quitโ closes the current data connection. This unsets the shell parametersZFTP_HOST,ZFTP_PORT,ZFTP_IP,ZFTP_SYSTEM,ZFTP_USER,ZFTP_ACCOUNT,ZFTP_PWD,ZFTP_TYPEandZFTP_MODE๐sessionโsession [ sessname ]lets you use multiple FTP sessions at once. The name of the session is an arbitrary string of characters; the default session is calleddefault๐ธ- If this command is called without an argument, it lists all the current sessions; with an argument, it either switches to the existing session called sessname, or creates a new session of that name.
- Each session remembers the status of the connection, the set of connection-specific shell parameters (the same set as are unset when a connection closes, as given in the description of
close), and any user parameters specified with theparamssubcommand ๐ - Changing to a previous session restores those values; changing to a new session initialises them in the same way as if
zftphad just been loaded. The name of the current session is given by the parameterZFTP_SESSION๐
๐ rmsession ๐
rmsession [ sessname ]
Okay so this one deletes a session, bestie. If you don't hand it a name, it nukes the current session. If you do delete the current one, the earliest existing session slides in and becomes the new current session โ otherwise the current session just stays put, no dramatics. And if the session you're deleting is the only one? A brand-new session called default gets created and becomes the current one. Heads up though: that's a new session, even if the one you just yeeted was also named default. ๐
It is recommended that sessions not be deleted while background commands which use zftp are still active. Like, genuinely, don't. ๐
โจ Parameters โจ
The following shell parameters are used by zftp. Currently none of them are special.
ZFTP_TMOUTโ Integer. The time in seconds to wait for a network operation to complete before returning an error. If this isn't set when the module is loaded, it gets the default value60. A value of zero turns timeouts off. If a timeout happens on the control connection, that connection gets closed. Seeing that too often? Bump the number up. โฐZFTP_IPโ Readonly. The IP address of the current connection, in dot notation.ZFTP_HOSTโ Readonly. The hostname of the current remote server. If the host was opened as an IP number,ZFTP_HOSTcontains that instead โ which saves the overhead of a name lookup, since IP numbers are most commonly used when a nameserver is unavailable.ZFTP_PORTโ Readonly. The number of the remote TCP port the connection is open to (even if the port was originally specified as a named service). Usually this is the standard FTP port,21.
In the unlikely event that your system doesn't have the appropriate conversion functions, this appears in network byte order. If your system is little-endian, the port then consists of two swapped bytes and the standard port will be reported as 5376. In that case, numeric ports passed to zftp open will also need to be in this format. ๐ญ
ZFTP_SYSTEMโ Readonly. The system type string returned by the server in response to an FTPSYSTrequest. The most interesting case is a string beginningUNIX Type: L8, which ensures maximum compatibility with a local UNIX host. ๐ZFTP_TYPEโ Readonly. The type to be used for data transfers, eitherAorI. Use thetypesubcommand to change this.ZFTP_USERโ Readonly. The username currently logged in, if any.ZFTP_ACCOUNTโ Readonly. The account name of the current user, if any. Most servers don't require an account name, so don't stress if it's empty, bestie.ZFTP_PWDโ Readonly. The current directory on the server.ZFTP_CODEโ Readonly. The three digit code of the last FTP reply from the server, as a string. This can still be read after the connection is closed, and it is not changed when the current session changes.ZFTP_REPLYโ Readonly. The last line of the last reply sent by the server. Same deal: still readable after the connection closes, and it doesn't change when the current session changes.ZFTP_SESSIONโ Readonly. The name of the current FTP session; see the description of thesessionsubcommand.ZFTP_PREFSโ A string of preferences for altering aspects of zftp's behaviour. Each preference is a single character. The following are defined:Pโ Passive: attempt to make the remote server initiate data transfers. This is slightly more efficient than sendport mode. If the letterSoccurs later in the string, zftp will use sendport mode if passive mode is not available.Sโ Sendport: initiate transfers by the FTPPORTcommand. If this occurs before anyPin the string, passive mode will never be attempted.Dโ Dumb: use only the bare minimum of FTP commands. This prevents the variablesZFTP_SYSTEMandZFTP_PWDfrom being set, and will mean all connections default to ASCII type. It may preventZFTP_SIZEfrom being set during a transfer if the server doesn't send it anyway (many servers do).
If ZFTP_PREFS is not set when zftp is loaded, it will be set to a default of PS, i.e. use passive mode if available, otherwise fall back to sendport mode. ๐
ZFTP_VERBOSEโ A string of digits between0and5inclusive, specifying which responses from the server should be printed. All responses go to standard error. If any of the numbers1to5appear in the string, raw responses from the server with reply codes beginning with that digit will be printed to standard error. The first digit of the three digit reply code is defined by RFC959 to correspond to:- A positive preliminary reply.
- A positive completion reply.
- A positive intermediate reply.
- A transient negative completion reply.
- A permanent negative completion reply.
It should be noted that, for unknown reasons, the reply Service not available, which forces termination of a connection, is classified as 421, i.e. transient negative โ an interesting interpretation of the word transient. ๐
The code 0 is special: it indicates that all but the last line of multiline replies read from the server will be printed to standard error in a processed format. By convention, servers use this mechanism for sending information for the user to read. The appropriate reply code, if it matches the same response, takes priority.
If ZFTP_VERBOSE is not set when zftp is loaded, it will be set to the default value 450, i.e., messages destined for the user and all errors will be printed. A null string is valid and specifies that no messages should be printed. ๐คซ
๐ซถ Functions ๐ซถ
zftp_chpwdโ If this function is set by the user, it is called every time the directory changes on the server, including when a user is logged in, or when a connection is closed. In that last case,$ZFTP_PWDwill be unset; otherwise it will reflect the new directory.zftp_progressโ If this function is set by the user, it will be called during aget,putorappendoperation each time sufficient data has been received from the host. During aget, the data is sent to standard output, so it is vital that this function should write to standard error or directly to the terminal, not to standard output. โ ๏ธ
When it is called with a transfer in progress, the following additional shell parameters are set:
ZFTP_FILEโ The name of the remote file being transferred from or to.ZFTP_TRANSFERโ AGfor agetoperation and aPfor aputoperation.ZFTP_SIZEโ The total size of the complete file being transferred: the same as the first value provided by theremoteandlocalsubcommands for a particular file. If the server cannot supply this value for a remote file being retrieved, it will not be set. If input is from a pipe the value may be incorrect and correspond simply to a full pipe buffer.ZFTP_COUNTโ The amount of data so far transferred; a number between zero and$ZFTP_SIZE, if that is set. This number is always available. โจ
The function is initially called with ZFTP_TRANSFER set appropriately and ZFTP_COUNT set to zero. After the transfer is finished, the function will be called one more time with ZFTP_TRANSFER set to GF or PF, in case it wishes to tidy up. It is otherwise never called twice with the same value of ZFTP_COUNT.
Sometimes the progress meter may cause disruption. It is up to the user to decide whether the function should be defined and to use unfunction when necessary. You got this. ๐
๐ญ Problems ๐ญ
A connection may not be opened in the left hand side of a pipe, because this occurs in a subshell and the file information is not updated in the main shell. In the case of type or mode changes, or closing the connection in a subshell, the information is returned but variables are not updated until the next call to zftp. Other status changes in subshells will not be reflected by changes to the variables (but should be otherwise harmless).
Deleting sessions while a zftp command is active in the background can have unexpected effects, even if it does not use the session being deleted. This is because all shell subprocesses share information on the state of all connections, and deleting a session changes the ordering of that information. ๐
On some operating systems, the control connection is not valid after a fork(), so that operations in subshells, on the left hand side of a pipeline, or in the background are not possible, as they should be. This is presumably a bug in the operating system. not the vibe. ๐
๐ฆ THE ZSH/ZLE MODULE ๐ฆ
The zsh/zle module contains the Zsh Line Editor. See zshzle(1). That's it, that's the whole module, she's iconic and she knows it. ๐
๐ธ THE ZSH/ZLEPARAMETER MODULE ๐ธ
The zsh/zleparameter module defines two special parameters that can be used to access internal information of the Zsh Line Editor (see zshzle(1)).
keymapsโ This array contains the names of the keymaps currently defined.widgetsโ This associative array contains one entry per widget. The name of the widget is the key and the value gives information about the widget. It is either- the string
builtinfor builtin widgets, - a string of the form
user:namefor user-defined widgets, where name is the name of the shell function implementing the widget, - a string of the form
completion:type:namefor completion widgets, - or a null value if the widget is not yet fully defined.
- the string
In the penultimate case, type is the name of the builtin widget the completion widget imitates in its behavior and name is the name of the shell function implementing the completion widget. ๐ง
โจ THE ZSH/ZPROF MODULE โจ
When loaded, zsh/zprof causes shell functions to be profiled. The profiling results can be obtained with the zprof builtin command made available by this module. There is no way to turn profiling off other than unloading the module. Like, that's the whole mood: once it's on, it's on until you unload it. ๐
๐ the zprof builtin ๐
zprof [ -c ]โ without-c,zproflists profiling results to standard output; with-c, it resets its internal counters and does not show the listing.
Without the -c option, zprof lists profiling results to standard output. The format is comparable to that of commands like gprof. iykyk โจ
At the top there is a summary listing all functions that were called at least once. This summary is sorted in decreasing order of the amount of time spent in each. The lines contain the number of the function in order, which is used in other parts of the list in suffixes of the form [num], then the number of calls made to the function. The next three columns list the time in milliseconds spent in the function and its descendants, the average time in milliseconds spent in the function and its descendants per call, and the percentage of time spent in all shell functions used in this function and its descendants. The following three columns give the same information, but counting only the time spent in the function itself. The final column shows the name of the function. ๐ซถ
After the summary, detailed information about every function that was invoked is listed, sorted in decreasing order of the amount of time spent in each function and its descendants. Each of these entries consists of descriptions for the functions that called the function described, the function itself, and the functions that were called from it. The description for the function itself has the same format as in the summary (and shows the same information). The other lines don't show the number of the function at the beginning and have their function named indented to make it easier to distinguish the line showing the function described in the section from the surrounding lines. ๐ธ
The information shown in this case is almost the same as in the summary, but only refers to the call hierarchy being displayed. For example, for a calling function the column showing the total running time lists the time spent in the described function and its descendants only for the times when it was called from that particular calling function. Likewise, for a called function, this columns lists the total time spent in the called function and its descendants only for the times when it was called from the function described. ๐ฆ
Also in this case, the column showing the number of calls to a function also shows a slash and then the total number of invocations made to the called function.
As long as the zsh/zprof module is loaded, profiling will be done and multiple invocations of the zprof builtin command will show the times and numbers of calls since the module was loaded. With the -c option, the zprof builtin command will reset its internal counters and will not show the listing. counter reset, no recap, periodt. ๐
๐ฆ THE ZSH/ZPTY MODULE ๐ฆ
The zsh/zpty module offers one builtin, and it's genuinely giving terminal-whisperer main character energy. ๐
๐ zpty ๐
zpty [ -e ] [ -b ] name [ arg ... ]โ runs a command under a newly assigned pseudo-terminal and gives it anameyou can use later.-eโ the pseudo-terminal is set up so that input characters are echoed.-bโ input to and output from the pseudo-terminal are made non-blocking.
The arguments following name are concatenated with spaces between, then executed as a command, as if passed to the eval builtin. The command runs under a newly assigned pseudo-terminal; this is useful for running commands non-interactively which expect an interactive environment. The name is not part of the command, but is used to refer to this command in later calls to zpty. name is the handle, not the command itself โ got it. โจ
The shell parameter REPLY is set to the file descriptor assigned to the master side of the pseudo-terminal. This allows the terminal to be monitored with ZLE descriptor handlers (see zshzle(1)) or manipulated with sysread and syswrite (see THE ZSH/SYSTEM MODULE in zshmodules(1)).
โ ๏ธ Warning: Use ofsysreadandsyswriteis not recommended; usezpty -randzpty -wunless you know exactly what you are doing. Like, exactly exactly.
zpty -d [ name ... ]โ deletes commands previously started, by supplying a list of their names.
The -d option is used to delete commands previously started, by supplying a list of their names. If no name is given, all commands are deleted. Deleting a command causes the HUP signal to be sent to the corresponding process. It is not a good idea to use this form in a subshell, as it will kill the command but leave the parent shell confused about the state, and it may try to kill another process that re-used the process ID. ๐ญ That's the messy part, bestie.
zpty -w [ -n ] name [ string ... ]โ sends the given strings to the commandnameas input, separated by spaces.-nโ if-nis not given, a newline is added at the end; if-nis given, that newline is not added.
The -w option can be used to send the to command name the given strings as input (separated by spaces). If the -n option is not given, a newline is added at the end.
If no string is provided, the standard input is copied to the pseudo-terminal; this may stop before copying the full input if the pseudo-terminal is non-blocking. The exact input is always copied: the -n option is not applied. ๐
Note that the command under the pseudo-terminal sees this input as if it were typed, so beware when sending special tty driver characters such as word-erase, line-kill, and end-of-file. typing vibes have consequences. ๐
zpty -r [ -mt ] name [ param [ pattern ] ]โ reads the output of the commandname.-mโ with apattern, the return status is zero only if the pattern matches.-tโ when combined with-r,zptytests whether output is available before trying to read.
The -r option can be used to read the output of the command name. With only a name argument, the output read is copied to the standard output. Unless the pseudo-terminal is non-blocking, copying continues until the command under the pseudo-terminal exits; when non-blocking, only as much output as is immediately available is copied. The return status is zero if any output is copied. ๐ซถ
When also given a param argument, at most one line is read and stored in the parameter named param. Less than a full line may be read if the pseudo-terminal is non-blocking. The return status is zero if at least one character is stored in param. ๐
If a pattern is given as well, output is read until the whole string read matches the pattern, even in the non-blocking case. The return status is zero if the string read matches the pattern, or if the command has exited but at least one character could still be read. If the option -m is present, the return status is zero only if the pattern matches. As of this writing, a maximum of one megabyte of output can be consumed this way; if a full megabyte is read without matching the pattern, the return status is non-zero. one megabyte max โ that's the limit, no cap. ๐ญ
In all cases, the return status is non-zero if nothing could be read, and is 2 if this is because the command has finished.
If the -r option is combined with the -t option, zpty tests whether output is available before trying to read. If no output is available, zpty immediately returns the status 1. When used with a pattern, the behaviour on a failed poll is similar to when the command has exited: the return value is zero if at least one character could still be read even if the pattern failed to match. ๐ฆ
zpty -t nameโ tests whether the commandnameis still running.
The -t option without the -r option can be used to test whether the command name is still running. It returns a zero status if the command is running and a non-zero value otherwise. Note that this does not indicate whether or not any output is available to read. running โ output ready, okay? ๐
zpty [ -L ]โ lists the commands currently defined; with-L, this is done in the form of calls to thezptybuiltin.
The last form, without any arguments, is used to list the commands currently defined. If the -L option is given, this is done in the form of calls to the zpty builtin. ๐
๐ธ THE ZSH/ZSELECT MODULE ๐ธ
okay so this module is a whole little moment and it gives you exactly one builtin command:
zselect [ -rwe ] [ -t timeout ] [ -a array ] [ -A assoc ] [ fd ... ]
The zselect builtin is basically a front-end to the select system call โ it blocks until a file descriptor is ready for reading or writing, or has an error condition, with an optional timeout. If select isn't available on your system, the command prints an error message and returns status 2 (normal errors return status 1). For more info, check your system's documentation for select(2). And bestie, listen: there is no connection with the shell builtin of the same name. none. zero. don't get it twisted ๐
Arguments and options may be intermingled in any order. Non-option arguments are file descriptors, which must be decimal integers. By default, file descriptors are tested for reading, i.e. zselect returns when data is available to be read from the file descriptor โ or more precisely, when a read operation from the file descriptor will not block. After a -r, -w and -e, the given file descriptors are tested for reading, writing, or error conditions respectively. These options and an arbitrary list of file descriptors may be given in any order. slay.
(The presence of an โerror conditionโ is not well defined in the documentation for many implementations of theselectsystem call. According to recent versions of the POSIX specification, it's really an exception condition, of which the only standard example is out-of-band data received on a socket. So zsh users are unlikely to find the-eoption useful.) lowkey tragic, but that's the lore ๐ซถ
-t timeoutโ specifies a timeout in hundredths of a second. This may be zero, in which case the file descriptors will simply be polled andzselectwill return immediately. It's possible to callzselectwith no file descriptors and a non-zero timeout for use as a finer-grained replacement forsleep; note, however, the return status is always 1 for a timeout.-a arrayโ indicates that array should be set to indicate the file descriptor(s) which are ready. If the option is not given, the arrayreplywill be used for this purpose. The array will contain a string similar to the arguments forzselect. For example:
zselect -t 0 -r 0 -w 1
might return immediately with status 0 and $reply containing -r 0 -w 1 to show that both file descriptors are ready for the requested operations. iconic honestly โจ
-A assocโ indicates that the associative array assoc should be set to indicate the file descriptor(s) which are ready. This option overrides the option-a, nor willreplybe modified. The keys of assoc are the file descriptors, and the corresponding values are any of the charactersrweto indicate the condition.
The command returns status 0 if some file descriptors are ready for reading. If the operation timed out, or a timeout of 0 was given and no file descriptors were ready, or there was an error, it returns status 1 and the array will not be set (nor modified in any way). If there was an error in the select operation the appropriate error message is printed. so if you're getting a 1, it's giving "nothing ready or something went sideways" โ check the vibe ๐
๐ฆ THE ZSH/ZUTIL MODULE ๐ฆ
The zsh/zutil module only adds some builtins, but one of them is the style system, so yeah, it's a main character:
zstyle [ -L [ metapattern [ style ] ] ]
zstyle [ -e | - | -- ] pattern style string ...
zstyle -d [ pattern [ style ... ] ]
zstyle -g name [ pattern [ style ] ]
zstyle -{a|b|s} context style name [ sep ]
zstyle -{T|t} context style [ string ... ]
zstyle -m context style pattern
This builtin command is used to define and lookup styles. Styles are pairs of names and values, where the values consist of any number of strings. They're stored together with patterns, and lookup is done by giving a string called the context, which is matched against the patterns. The definition stored for the most specific pattern that matches will be returned. periodt.
A pattern is considered to be more specific than another if it contains more components (substrings separated by colons) or if the patterns for the components are more specific โ where simple strings are considered to be more specific than patterns, and complex patterns are considered to be more specific than the pattern *. A * in the pattern will match zero or more characters in the context; colons are not treated specially in this regard. If two patterns are equally specific, the tie is broken in favour of the pattern that was defined first. first come, first served, no cap ๐
โจ Example โจ
For example, a fictional weather plugin might state in its documentation that it looks up the preferred-precipitation style under the :weather:continent:day-of-the-week:phase-of-the-moon context. According to this, you might set the following in your zshrc:
zstyle ':weather:europe:*' preferred-precipitation rain
zstyle ':weather:*:Sunday:*' preferred-precipitation snow
Then the plugin would run under the hood a command such as
zstyle -s ":weather:${continent}:${day_of_week}:${moon_phase}" preferred-precipitation REPLY
in order to retrieve your preference into the scalar variable $REPLY. On Sundays $REPLY would be set to snow; in Europe it would be set to rain; and on Sundays in Europe it would be set to snow again, because the patterns :weather:europe:* and :weather:*:Sunday:* both match the context argument to zstyle -s, are equally specific, and the latter is more specific โ because it has more colon-separated components. the way specificity works is honestly so satisfying when it clicks ๐ง
๐ Usage ๐
The forms that operate on patterns are the following.
zstyle [ -L [ metapattern [ style ] ] ]
Without arguments, lists style definitions. Styles are shown in alphabetic order and patterns are shown in the order zstyle will test them.
If the -L option is given, listing is done in the form of calls to zstyle. The optional first argument, metapattern, is a pattern which will be matched against the string supplied as pattern when the style was defined. Note: this means, for example, zstyle -L ":completion:*" will match any supplied pattern beginning :completion:, not just ":completion:*": use ':completion:\*' to match that. The optional second argument limits the output to a specific style (not a pattern). -L is not compatible with any other options. don't try to mix it with other flags, it will not eat ๐
zstyle [ - | -- | -e ] pattern style string ...
Defines the given style for the pattern with the strings as the value. If the -e option is given, the strings will be concatenated (separated by spaces) and the resulting string will be evaluated (in the same way as it is done by the eval builtin command) when the style is looked up. In this case the parameter reply must be assigned to set the strings returned after the evaluation. Before evaluating the value, reply is unset, and if it is still unset after the evaluation, the style is treated as if it were not set. so yeah, reply is the main character there ๐
zstyle -d [ pattern [ style ... ] ]
Delete style definitions. Without arguments all definitions are deleted, with a pattern all definitions for that pattern are deleted, and if any styles are given, then only those styles are deleted for the pattern. bye bye ๐
zstyle -g name [ pattern [ style ] ]
Retrieve a style definition. The name is used as the name of an array in which the results are stored. Without any further arguments, all patterns defined are returned. With a pattern the styles defined for that pattern are returned, and with both a pattern and a style, the value strings of that combination are returned. it's giving "fetch the receipts" ๐
The other forms can be used to look up or test styles for a given context.
zstyle -s context style name [ sep ]
The parameter name is set to the value of the style interpreted as a string. If the value contains several strings they are concatenated with spaces (or with the sep string if that is given) between them.
Return 0 if the style is set, 1 otherwise.
zstyle -b context style name
The value is stored in name as a boolean, i.e. as the string yes if the value has only one string and that string is equal to one of yes, true, on, or 1. If the value is any other string or has more than one string, the parameter is set to no.
Return 0 if name is set to yes, 1 otherwise.
zstyle -a context style name
The value is stored in name as an array. If name is declared as an associative array, the first, third, etc. strings are used as the keys and the other strings are used as the values.
Return 0 if the style is set, 1 otherwise.
zstyle -t context style [ string ... ]
zstyle -T context style [ string ... ]
Test the value of a style, i.e. the -t option only returns a status (sets $?). Without any string the return status is zero if the style is defined for at least one matching pattern, has only one string in its value, and that is equal to one of true, yes, on or 1. If any strings are given the status is zero if and only if at least one of the strings is equal to at least one of the strings in the value. If the style is defined but doesn't match, the return status is 1. If the style is not defined, the status is 2.
The -T option tests the values of the style like -t, but it returns status zero (rather than 2) if the style is not defined for any matching pattern. it's the chill version of -t, basically ๐
zstyle -m context style pattern
Match a value. Returns status zero if the pattern matches at least one of the strings in the value. yup, that's the whole thing โ match made in heaven โญ
๐ zformat โจ
zformat -f param format spec ...
zformat -F param format spec ...
zformat -a array sep spec ...
okay so this builtin is literally the formatting queen โ she does three different jobs and honestly she slays all of them ๐
The first form is the one you get with -f. Here's the vibe: your format string gets remixed by swapping out every sequence that starts with a percent sign for a string pulled from the specs. Each spec is shaped like char:string, and that makes every appearance of %char inside format get replaced by that string ๐ซถ
and bestie, the % sequence can also carry optional minimum and maximum field width specs โ they live between the % and the char, like %min.maxc. So minimum field width comes first, and if you're using a maximum field width it has to have a dot in front of it, no cap โจ
- give it a minimum field width and your result gets padded with spaces on the right if the string is shorter than the width you asked for ๐ธ
- want padding on the left instead? just hand over a negative minimum field width, easy ๐
- give it a maximum field width and the string gets truncated after that many characters โ๏ธ
Once all the % sequences for the given specs have been processed, the resulting string gets stored in the parameter param. and if you literally just need a percent sign to exist and NOT be interpreted โ %% is your girl, it produces a literal % ๐
The %-escapes also understand ternary expressions, in the exact same form prompts use โจ The % is followed by a ( and then an ordinary format specifier character as described above. There may be a set of digits either before or after the ( โ these specify a test number, which defaults to zero. Negative numbers are allowed too, she's flexible ๐
An arbitrary delimiter character follows the format specifier, then a piece of 'true' text, the delimiter character again, a piece of 'false' text, and a closing parenthesis ๐ The complete expression (without the digits) looks like %(X.text1.text2), except the . character is arbitrary โ you pick your own drama.
so how does it decide? the value you gave for the format specifier in the char:string expressions gets evaluated as a mathematical expression, then compared with the test number. same? text1 comes out. not the same? text2 comes out ๐
A parenthesis may be escaped inside text2 as %). And either of text1 or text2 may contain nested %-escapes โ yes, it's turtles all the way down, we love a recursive icon ๐
For example:
zformat -f REPLY "The answer is '%3(c.yes.no)'." c:3
outputs "The answer is 'yes'." to REPLY since the value for the format specifier c is 3, which agrees with the digit argument to the ternary expression ๐ (fr fr, she ate that)
With -F instead of -f, the ternary expressions choose between the 'true' or 'false' text based on whether the format specifier is present and non-empty โ not on any numeric matching. And a test number here means a minimum width for the value given in the format specifier ๐ Negative numbers reverse that whole situation, so the test becomes whether the value exceeds a maximum width ๐ฆ
The form using the -a option? that's the alignment one, and she is so good at making things line up ๐ญโจ Here, the specs are shaped like left:right where left and right are arbitrary strings. These strings get modified by replacing the colons with the sep string, and padding the left strings with spaces to the right so that the sep strings in the result (and hence the right strings after them) are all aligned if the strings are printed below each other ๐๐
- all strings without a colon are left unchanged ๐ธ
- all strings with an empty right string have the trailing colon removed ๐
- in both of those cases the lengths of the strings are not used to determine how the other strings are to be aligned โ so don't come for her about it ๐
A colon in the left string can be escaped with a backslash ๐ฅ And the resulting strings are stored in array, obviously.
๐ฆ zregexparse ๐ฆ
This one implements some internals of the _regex_arguments function. That's it, that's the whole summary โ she's mysterious, she's backstage, she's main character energy without needing the spotlight ๐โจ
๐ zparseopts ๐
zparseopts [ -D -E -F -K -M ] [ -a array ] [ -A assoc ] [ - ] spec ...
This builtin simplifies the parsing of options in positional parameters โ i.e. the whole set of arguments given by $* ๐ซถ And bestie, it's lowkey iconic for how much pain it saves you.
Each spec describes one option and must be shaped like opt[=array]. If an option described by opt is found in the positional parameters, it's copied into the array specified with the -a option; if the optional =array is given, it's instead copied into that array โ which should be declared as a normal array and never as an associative array ๐ธ important, don't do her dirty like that.
โญ heads up: it is an error to give any spec without an=arrayunless one of the-aor-Aoptions is used. no cap, she will complain.
Unless the -E option is given, parsing stops at the first string that isn't described by one of the specs โ Even with -E, parsing always stops at a positional parameter equal to - or --. See also -F below ๐
The opt description must be one of the following. Any of the special characters can appear in the option name provided it is preceded by a backslash ๐
name,name+โnameis the name of the option without the leading-. To specify a GNU-style long option, one of the usual two leading-must be included inname; for example, a--fileoption is represented by a name of-file. ๐
If a + appears after name, the option is appended to array each time it's found in the positional parameters; without the +, only the last occurrence of the option is preserved ๐ฅ
If one of these forms is used, the option takes no argument, so parsing stops if the next positional parameter doesn't also begin with - (unless the -E option is used) ๐ฆ
name:,name:-,name::โ if one or two colons are given, the option takes an argument; with one colon the argument is mandatory, and with two colons it's optional ๐ The argument is appended to the array after the option itself.
An optional argument is put into the same array element as the option name (note that this makes empty strings as arguments indistinguishable โ yeah, she said what she said ๐). A mandatory argument is added as a separate element unless the :- form is used, in which case the argument is put into the same element ๐ธ
A + as described above may appear between the name and the first colon ๐
In all cases, option-arguments must appear either immediately following the option in the same positional parameter, or in the next one โจ Even an optional argument may appear in the next parameter โ unless it begins with a -. And there's no special handling of = like those GNU-style argument parsers do; given the spec -foo:, the positional parameter --foo=bar is parsed as --foo with an argument of =bar ๐ญ (yes really, she's built different)
When the names of two options that take no arguments overlap, the longest one wins โ so parsing for the specs -foo -foobar (for example) is unambiguous ๐ However, because of that whole option-argument handling thing up there, ambiguities may arise when at least one overlapping spec takes an argument, as in -foo: -foobar. In that case, the last matching spec wins ๐
๐ซถ also important: the options ofzparseoptsitself cannot be stacked, because for example the stack-DEKis indistinguishable from a spec for the GNU-style long option--DEK. rude? maybe. true? absolutely.
The options of zparseopts itself are:
-a arrayโ as described above, this names the default array in which to store the recognised options ๐ธ-A assocโ if this is given, the options and their values are also put into an associative array, with the option names as keys and the arguments (if any) as the values ๐-Dโ if this option is given, all options found are removed from the positional parameters of the calling shell or shell function, up to but not including any not described by the specs. If the first such parameter is-or--, it's removed as well ๐ This is similar to using theshiftbuiltin. lowkey a glow-up forshiftngl.-Eโ this changes the parsing rules to not stop at the first string that isn't described by one of the specs ๐ฆ It can be used to test for, or (if used together with-D) extract, options and their arguments, ignoring all other options and arguments that may be in the positional parameters โจ As indicated above, parsing still stops at the first-or--not described by a spec โ but it is not removed when used with-D๐-Fโ if this option is given,zparseoptsimmediately stops at the first option-like parameter not described by one of the specs, prints an error message, and returns status1๐ฅ Removal (-D) and extraction (-E) are not performed, and option arrays are not updated. This provides basic validation for the given options ๐
Note that the appearance in the positional parameters of an option without its required argument always aborts parsing and returns an error as described above, regardless of whether this option is used ๐ญ so like, she's checking either way bestie.
-Kโ with this option, the arrays specified with the-aoption and with the=arrayforms are kept unchanged when none of the specs for them is used ๐ธ Otherwise the entire array is replaced when any of the specs is used. Individual elements of associative arrays specified with the-Aoption are preserved by-Kโจ This allows assignment of default values to arrays before callingzparseoptsโ so cute, so thoughtful ๐-Mโ this changes the assignment rules to implement a map among equivalent option names ๐ If any spec uses the=arrayform, the stringarrayis interpreted as the name of another spec, which is used to choose where to store the values. If no other spec is found, the values are stored as usual ๐ This changes only the way the values are stored, not the way$*is parsed โ so results may be unpredictable if thename+specifier is used inconsistently ๐ (fr, don't mix and match and then act surprised)
For example,
okay so last batch of zparseopts examples and then we're literally free ๐
these ones are about what lands in your arrays, so watch closely bestie:
set -- -a -bx -c y -cz baz -cend
zparseopts a=foo b:=bar c+:=bar
will have the effect of
foo=(-a)
bar=(-b x -c y -c z)
slay. notice -a went into foo all by itself, and bar caught -b x, -c y and -c z โ because c+:=bar is the repeatable-girlie spec and she ate every time she showed up ๐
The arguments frombazon will not be used. fr fr โ oncebazhits the scene, everything after it is just... not invited to the party ๐ no cap.
๐ธ the -E option, example-ified
As an example for the -E option, consider:
set -- -a x -b y -c z arg1 arg2
zparseopts -E -D b:=bar
will have the effect of
bar=(-b y)
set -- -a x -c z arg1 arg2
I.e., the option -b and its arguments are taken from the positional parameters and put into the array bar. ๐ซถ like, -b and y peaced out of set -- and moved into bar, and the rest of the positional params closed ranks like nothing happened. main character energy honestly.
๐ฆ the -M option, example-ified
The -M option can be used like this:
set -- -a -bx -c y -cz baz -cend
zparseopts -A bar -M a=foo b+: c:=b
to have the effect of
foo=(-a)
bar=(-a '' -b xyz)
look at that โ -a shows up in both arrays (iconic of her tbh), and -M let those babies get matched with those combined specs. xyz is literally x, y, z glued together and it's giving โจcraft projectโจ. ๐
and that's the whole zparseopts saga bestie โ go forth and parse responsibly ๐
okay we are SO done โ that's the whole page! ๐ this absolute unit of a manual is from zsh 5.9.2, dated July 12, 2026, and it's the ZSHMODULES(1) page ๐ ngl you read the entire thing and that's genuinely a flex ๐ go hydrate, you've earned it ๐งโโ๏ธโจ
๐ฆ where this page comes from
- arch rolling: zsh 5.9.2-1 ยท custom
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms