Documentos de Académico
Documentos de Profesional
Documentos de Cultura
1 2 3 4 5 6 7 8 9 10 11 12 13 Contents General information, references Grammar (shell syntax) Patterns: globbing and qualifiers Options Options cont.; option aliases, single letter options Expansion: basic forms, history, prompts Expansion: variables: forms and flags Shell variables: set by shell, used by shell Test operators; numeric expressions Completion: contexts, completers, tags Completion cont.: tags cont, styles Completion cont.: styles cont, utility functions Zsh line editor (zle)
Version 4.2
programs, links to external resources, and a glossary. Zsh manual pages To access documentation from within the shell, use the man command with one of the following arguments: Introduction, startup and shutdown zsh Syntax, redirection, functions, jobs, tests zshmisc Expansion and substitution zshexpn Parameters (variables) zshparam Options to the shell zshoptions Shell builtin commands zshbuiltins The line editor, excluding completion zshzle The low-level completion facitilities zshcompwid The new completion system (more readable) zshcompsys The old completion system (deprecated) zshcompctl zshmodules Modules loadable with zmodload Functions for using raw TCP via builtins zshtcpsys Functions for using FTP via builtins zshzftpsys Contributed functions for zle etc. zshcontrib Everything in one large manual page zshall Mailing lists zsh-users@zsh.org: users' mailing list for general questions and tips; to join, mail zsh-users-subscribe@zsh.org. zsh-workers@zsh.org: mailing list for bug reports, patches and developers' discussions; to join, mail zsh-workers-subscribe@zsh.org. New developers with some Unix/Linux experience are welcome.
Notes The descriptions here are very brief. You will not be able to learn shell syntax from them; see the various references below. In particular the completion system is extremely rich and the descriptions of its utility functions are the barest memory joggers. The start and end of each section is aligned with page boundaries, so you can print out only the parts you want to refer to. References Zsh manual: Supplied with the shell: should be installed in Unix manual page and info formats. Texinfo generates PS or PDF; available as separate doc bundle from same place as the shell.
Part3 (Extending the Shell) contains the following chapters: http://zsh.sourceforge.net/: Site with much 12 Variables information about zsh, including HTML manual and a more user(c.f. pages 7 and 8) friendly guide to the shell, as well as the FAQ. 13 Scripting and Functions (c.f. page 2) Zsh wiki: http://www.zshwiki.org/: Extensible zsh web 14 Writing Editor Commands pages written by users. (c.f page 13) 15 Writing Completion Functions From Bash to Z Shell: Conquering the Command Line, by (c.f. pages 10 through 12) Oliver Kiddle, Jerry Peek and Peter Stephenson, Apress, ISBN 1 59059 376 6. Introduction to interactive use of Unix shells in The three appendices contain short descriptions of standard Unix
Page 2
Grammar List is any sequence of sublists (including just one) separated by ; or newline. ; and newline are always interchangeable except in ;;. Sublist is any sequence of pipelines (including just one) connected by && or . Pipeline is any sequence of simple commands connected by .
Version 4.2
select name [ in word ]; do list; done Print menu of words, read a number, set name to selected word, execute list until end of input. Portable but rare. #list[;]$ Execute list in a subshell (a new process where nothing that happens affects the current shell). !list[;]" Execute list (no new process: simply separates list from whats around and can take redirections). function nameword ![;] list[;] " nameword #$ !%;& list[;] " Define function named nameword; executes list when run; running nameword word1 makes word1 available as '( etc. in function body. list must end with [;] or newline for portability. nameword can be repeated to define multiple functions (rare, non-portable). time [ pipeline ] Report time for pipeline if given else totals for current shell. %% condition && Evaluate condition (see below), gives status true or false.
for name [ in word ] do list; Command is either a simple command (a command word) done followed optionally by word or one of the special commands Execute list with variable name set to each of word in turn below. If in is omitted the positional parameters are used. Word is any text that produces a single word when expanded; word is any number of these separated by whitespace. Name is a shell identifier: an alphabetic character or _ followed by any sequence of alphanumeric characters or _. [ ] indicates optional; dots on their own line mean any number of repetitions of the line just above. Bold text is to be typed literally. Status true or false is determined by: for commands, the return status; for pipelines the last command; for sublists the last pipeline; for lists the last sublist that was executed. sublist1 && sublist2 [ && sublist3 ] Execute sublists until one is false. for name in word ; ! list " foreach name # word $ [;] list; end Non-portable alternative forms. while listw; do listd; done While listw is true execute listd. until listu; do listd; done Non-portable: while listu is not true execute listd. repeat numexp; do list; done repeat numexp sublist Non-portable: repeat list or sublist numexp times.
case word in [#] pattern1[ pattern2...]$ [;] list ;; sublist1 sublist2 [ sublist2 ] esac Execute sublists until one is true. Note strings of Try matching word against every pattern in turn until success. && sublists can contain sublists and vice versa; they are parsed Execute the corresponding list. ;& instead of && means fall left to right. through to next list. command1 command2 [ command3 ] Execute command1, sending its output to the input of command2, and so on (a pipeline). case word ! [#] pattern1[ pattern2...]$ [;] list ;;
Page 3
Basic patterns: ) * %class& %+class& ,num1-num2Pattern matching (globbing)
Version 4.2
Setgid ; Sticky bit t fspec Has chmod-style permissions spec Any string Evaluation string returns true status estring Any character =cmd Same but cmd must be alphanumeric or Any single character from class Device number de! (major*256 + minor) dde! Any single character not from class l%-=&num Link count is (less than, greater than) num Any number between num1 and num2 Owned by current effective UID Globbing flags with ./0.12.234567: I ,-num2- from 0; ,num1-- to infinity. Owned by current effective GID Match case insensitively 4 #9i$ Directories to any level ))/ Lower case matches upper case uuid Owned by given uid (may be ,name-) #9l$ Group patterns #pat1$ Match case sensitively #9?$ ggid Owned by given gid (may be ,name-) #pat1 pat2$ pat1 or pat2 (any number of s) #9b$ Parentheses set match, mbegin, mend a[@whms][-=]n Access time in given units (see below) Parentheses no longer set arrays #97$ m[@whms][-=]n Modification time in given units Character classes may contain any character or the following #9m$ Match in @A0B<, @7.4?1, @.12 c[@whms][-=]n Inode change time in given units special patterns in any mix; literal must be first; literal ^ must Size in given units (see below) 5[kmp][-=]n #9@$ Dont use @A0B< etc. not be first: Negate following qualifiers + Match with num approximations #9a num $ a-b A character in the range a to b Toggle following links (first one turns on) Match only at start of test string #9s$ An alphanumeric character %:alnum:& Mark directories @ Match only at end of test string #9e$ An alphabetic character %:alpha:& Mark directories, links, special files 0 #9C expr $ expr is a a set of glob qualifiers (below) A character in the ASCII character set %:ascii:& Whole pattern expands to empty if no match 1 A space or tab %:blank:& Leading dots may be matched 2 Glob qualifiers (in parentheses after file name pattern): A control character %:cntrl:& Sort numbers numerically n Directory / A decimal digit %:digit:& Order by given code (as below; may repeat) o [ n5lamcd ] D Non-empty directory; for empty use #/+D$ A printable character other than whitespace %:graph:& Order by reverse of given code 6[n5lamcd] Plain file . A lower case letter %:lower:& %num& Select numth file in current order Symbolic link @ A printable character %:print:& Select num1th to num2th file (as arrays) % num1 J num2 & Socket E A punctuation character %:punct:& : X History modifier X; may have more Name pipe (FIFO) p Any whitespace character %:space:& Executable plain file ) Time units are Month, week, hour, minute, second; default is day. An upper case letter %:upper:& Special file F Size units are kilobytes, megabytes or 512-byte blocks (p); default A hexadecimal digit %:xdigit:& Block special file Fb is bytes; upper case means the same as lower case. Character special file Fc Order codes are name (default), size, link count, access time, Extended patterns (option ./0.12.234567 must be set): Readable by owner (N.B. not current user) modification time, inode change time, directory depth. r Anything that doesnt match pat +pat Writeable by owner pat1+pat2 Match pat1 then anything other than pat2 w Executable by owner x Anything matching pat1 but not pat2 pat18pat2 Readable by members of files group A X9 Zero or more occurrences of element X Writeable by members of files group ? One or more occurrences of element X X99 Executable by members of files group . World readable G World writeable H World executable / Setuid s
Page 4
Options Set options with setopt, unset with unsetopt. Asterisk indicates on by default for native zsh. Expand aliases *A5?A;.; Export all variables to environment A553./K6G0 *A5HAL;35A;03KG6@K0 Completion lists after prompt On completion go to end of word A5HAL;3063.12 History appends to existing file *AKK.123<?;06GL AI063B2 Directory as command does cd AI063B610?1I. Jobs are continued when disowned List ambiguous completions *AI0635?;0 Menu complete after two tabs *AI063@.1I Variables always can be %~ abbrevs AI0631A@.32?G; Magic completion for parameters *AI063KAGA@3:.L; *AI063KAGA@3;5A;< 'dirname completes with / AI063KI;<2 cd uses directory stack too *AI063G.@6M.3;5A;< Trailing / in completion removed AI063G.;I@. cmd can resume job Fcmd Errors on pattern syntax; else literal *7A23KA00.G1 *7A143<?;0 > style history allowed Glob qualifiers with bare parens *7AG.345673NIA5 List completions on second tab 7A;<3AI0635?;0 Beep on all errors *7..K Background jobs at lower priority *7431?B. 7GAB.3BB5 /!ab" expands to /a /b 7;23.B<6 No echo escapes unles -e given Glob case sensitively *BA;.34567 B37A;.; Output hexadecimal with Ox B2A75.3MAG; cd !ar works if '!ar is directory B<A;.3260; Resolve .. in cd B<A;.35?1:; Resolve symbolic links in cd Check jobs before exiting shell *B<.B:3P67; Allow redirections to overwrite *B5677.G Completion uses unexpanded aliases B6@K5.0.3A5?A;.; Completion works inside words B6@K5.0.3?13H6G2 Correct spelling of commands B6GG.B0 Correct spelling of all arguments B6GG.B03A55 B;<3PI1:?.3<?;06GL Single > for previous command B;<3PI1:?.3566K; list; end for do...done No newlines in quotes B;<3PI1:?.3NI60.; Redirections with no commands fail B;<31I55B@2
Version 4.2
9 on interactive line for comment Indexing etc. for arrays like ksh Function file includes function name See globbing above Show all options plus on or off No word splitting in typeset etc. List completions when ambiguous Beep on ambiguous completion More compact completion lists List completions across File types listed in completion Options reset on function return Traps reset on function return Shell is login shell More verbose listing of jobs Special expansion after all E Warn if mail file timestamp changed Append / to globbed directories Cycle through ambiguous matches Shell has job control enabled Multiple redirections are special Error if glob fails to match Asynchronous job control messages Failed globs are removed from line Numbers in globs sorted numerically Leading zeros in integers force octal Start line editor in overstrike mode dir/cmd can be found in 'KA0< Illogical command behaviour Print all 8-bit characters directly Return status printed unless zero Special behaviour on setuid/setgid Special treatment of > in prompt Prompt always at start of line F escapes expanded in prompts ' expansion etc. in prompts Dont push dir multiply on stack Reverse sense of S and = in pushd No non-err messages from pushd pushd with no argument goes to 8
Page 5
GB3./KA123KAGA@ GB3NI60.; *GB; G.B3./AB0 G.;0G?B0.2 G@3;0AG3;?5.10 G@3;0AG3HA?0 ;<AG.3<?;06GL ;<3D?5.3./KA1;?61 ;<34567 ;<?13;02?1 ;<31I553B@2 ;<36K0?6135.00.G; *;<6G03566K; ;<3H6G23;K5?0 ;?145.3B6@@A12 ;?145.35?1.3R5. ;I13:.L76AG23<AB: 0GA1;?.103GKG6@K0 0GAK;3A;L1B 0LK.;.03;?5.10 *I1;.0 M.G76;. M? /0GAB. R5. /'arra# gives Xelt1 Xelt2 etc. TT inside single quotes gives T Run startup files Exact completion matches are good Shell has restricted capabilities Dont warn on rm ) Wait before asking if rm ) is OK Save and restore history per line 8 etc. expansion done early Disables non-extended zsh globs Shell input comes from stdin Commandless redirections like sh Single letter options are like sh for words; list works Split non-array variables yuckily Execute one command then exit Line editing on single line (bad tty) Unmatched U at end of line ignored Right prompt goes away after edit Traps may run when waiting Silent on typeset $oo Unset variables OK, treat as empty Output commands to be executed Same as bindkey -Q Show trace of execution with 'K;V Line editor used to input lines
Version 4.2
-l 564?1 -m @61?06G -n 163./.B -p KG?M?5.4.2 -r G.;0G?B0.2 -s ;<?13;02?1 -t ;?145.3B6@@A12 -u 163I1;.0 -Q M.G76;. -w B<A;.35?1:; -x /0GAB. -y ;<3H6G23;K5?0 Note also -A to set arrays, -b to end option processing, -c to pass a single command, -m to set pattern argument, -o to specify long name (may repeat), -s to sort positional parameters.
Option aliases (native zsh on right): 7GAB.3./KA12 163?416G.37GAB.; 26034567 45673260; <A;<3A55 <A;<3B@2; <?;03AKK.12 AKK.123<?;06GL <?;03./KA12 7A143<?;0 564 163<?;03163DI1B0?61; @A?53HAG1 @A?53HAG1?14 61.3B@2 ;?145.3B6@@A12 K<L;?BA5 B<A;.35?1:; KG6@K03MAG; KG6@K03;I7;0 ;02?1 ;<?13;02?1 0GAB:3A55 <A;<3B@2;
Page 6
Expansion Basic forms of expansion in the order they order: History expansion >expr Alias expansion alias Replaced by file with output from cmds ,#cmds$ E#cmds$ Same but can be reread (use for diff) -#cmds$ Replaced by file with input to cmds Variable substitution '!ar Same but protected, allows more options '!!ar" Replaced by output of cmds '#cmds$ Older form of same, harder to nest Ucmds% Arithmetic result of evaluating expr '##expr$$ X!aJb"& Xa& Xb# (N.B. does no pattern matching) X!(..X"& X(& XW# XX# X!O\..(O"& XO\& XO]# X(O# User home, named dir (dir is var name) 8user, 8dir /full/path/to/cmd Ecmd Glob file names, as above pattern History expansion: >> >!>" > >(X >-W >cmd >*str >9 Word selectors: >>:O >>:( >>:+ >>:' >:F >>:W-V >>:-V >>:) >>:W) >>:W-
Version 4.2
Full host name Host name to first dot or n dots Name of script, function, sourced file Name of user (same as 'I;.G1A@.) Start (stop) standout mode Time of day, 24-hour format Start (stop) underline mode (patchy support) nth component of 'psQar array Date as middle-endian ((/))/&& Date as )*& )) Login terminal without /deQ Parser state (continuation lines, debug) Like F/, Fd but with tilde substitution Escape sequence esc doesnt move cursor tstr if test X gives n, else $str Truncate to n on left, str on left if so Truncate to n on right, str on right if so
Immediately preceding line (all of it) Same but protected, may have args in {} Line just referred to, default !! Line numbered 13 (history shows nos.) Command two before current Last command beginning cmd Last command containing str Current command line so far
Test characters in FX#.tstr.$str$: > Privileged; 9 uid n; * last status n; 3 at least n nested constructs; / at least n 'KH2 elements; 8 same with 8 subst; 2 month is n; d day of month is n; Prompt expansion (with KG6@K03K.GB.10, on by default); may g effective gid is n; ^ at least n jobs; 5 ';<5M5 at least n; l at least n chars on line so far; ; ';.B612; at least n; 0 hours is n; take a decimal number n (default 0) immediately after the F: t minutes is n; Q at least n components in 'psQar; w day of Current history event number F> Fh week is n (Sunday = 0). F9 9 if superuser, else F A single F A $ (use with FX#.tstr.$str$) Time in 24-hour format with seconds 'KH2; n gives trailing parts, -n leading Deprecated alternatives, differ by default n Return status of last command Time of day in am/pm format Start (stop) bold face mode Date as &&-((-)), optional strftime spec Clear to end of line Script/function line number ('5?1.16) Number of jobs as listed by jobs Shell depth (';<5M5) Login terminal without /deQ or /deQ/tty
FF F$ F) F/ Fc Extract argument 0 (command word) Argument numbered 1 (first cmd arg) F* Also argument 1 F@ Last command argument F7 Word found by >*str (needs correct line) F2 Word 2 to 4 inclusive F. Words 0 to 4 inclusive Fi Words 1 to $ inclusive F^ Words 2 to $ inclusive F5 Words 2 to $-1 inclusive Fl
Fd F. FB Ft (Fb) F2!str"
Page 7
Parameter (Variable) Expansion Basic forms: str will also be expanded; most forms work on words of array separately: '!!ar" Substitute contents of !ar, no splitting 1 if !ar is set, else 0 '!=!ar" '!!ar:-str" '!ar if non-null, else str '!!ar-str" '!ar if set (even if null) else str '!!ar:Estr" '!ar if non-null, else str and set !ar to it '!!ar::Estr" Same but always use str '!!ar:*str" '!ar if non-null else error, abort '!!ar:=str" str if '!ar is non-null min match of pat removed from head '!!ar9pat" '!!ar99pat" max match of pat removed from head min match of pat removed from tail '!!arFpat" '!!arFFpat" max match of pat removed from tail '!!ar:9pat" '!ar unless pat matches, then empty One occurrence of p replaced by r '!!ar/p/r" '!!ar//p/r" All occurrences of p replaced by r Length of !ar in words (array) or bytes '!9!ar" Expand elements like brace expansion '!+!ar" Split words of result like lesser shells '!E!ar" Allow globbing, file expansion on result '!8!ar" '!'!!arFp"9+" Apply Fp then 9+ to '!ar
Version 4.2
Order of rules: 1. Nested substitution: from inside out 2. Subscripts: '!arr%X&" extract word; '!str%W&" extract character; '!arr%WJV&", '!str%VJ\&" extract range; -( is last word/char, -W previous etc. 3. '!#K$!ar" replaces name with value 4. `'arra#` joins array, may use #^:str:$ 5. Nested subscript e.g. '!'!!ar%WJV&"%(&" 6. 9, F, / etc. modifications 7. Join if not joined and #^:str:$, #D$ 8. Split if #s$, #z$, #z$, E 9. Split if ;<3H6G23;K5?0 10. Apply #u$ 11. Apply #o$, #6$ 12. Apply #e$ 13. Apply #l.str.$, #r.str.$ 14. If single word needed for context, join with '?D;%(&. Types shown with #t$ have basic type scalar, array, integer, float, assocation, then hyphen-separated words from following list: Parameter is local to function local left Left justified with typeset -5 right3blanks Right justified with typeset -G right3zeros Right justified with typeset -R lower Lower case forced with typeset -l upper Upper case forced with typeset -u readonly Read-only, typeset -r or readonly tag Tagged as typeset -t (no special effect) export Exported with export, typeset -x uniCue Elements unique with typeset -I hide Variable not special in func (typeset -h) hideQal typeset hides value (typeset -<) Variable special to shell special
Quote result with backslashes C Quote result with single quotes CC Quote result with double quotes CCC CCCC Quote result with 'T...T Strip quotes from result N Output type of variable (see below) t Unique: remove duplicates after first u Upper case result I Q Include value in result; may have #kQ$ Visible representation of special chars M w Count words with '!9!ar" Same but empty words count H Report parsing errors (normally ignored) / Split to words using shell grammar z p Following forms recognize print _-escapes ^:str: Join words with str between Pad with spaces on left to width x l:x: l:x::s(: Same but pad with repeated s1 Same but s2 used once before any s1s l:x::s(::sW: r:x::s(::sW: Pad on right, otherwise same as l forms s:str: Split to array on occurrences of str With patterns, search substrings ; ?:exp: With patterns, match expth occurrence With patterns, include match beginning 7 With patterns, include match end . Parameter flags in parentheses, immediately after left brace: With patterns, include matched portion @ F Expand Fs in result as in prompts With patterns, include length of match 1 Array expand even in double quotes @ With patterns, include unmatched part (rest) A Create array parameter with '!...E..." G Delimeters shown as :str: may be any pair of chars or matched a Array index order, so 6a is reversed parenthses #str$, !str", %str&, ,str-. c Count characters for '!9!ar" Capitalize result B Do parameter, comand, arith expansion e Split result to array on newlines f Join arrays with newlines between elements D i oi or 6i sort case independently For associative array, result is keys k Lower case result 5 n on or 6n sort numerically Sort into ascending order o Sort into descending order 6 Interpret result as parameter name, get value K
Page 8
Parameters (Variables) Parameters set by shell, denotes special to shell (may not be reused except by hiding with typeset -h in functions) Process ID of last background process > Number of arguments to script or function 9 Same AG4B Process ID of main shell process ' String of single letter options set Positional parameters ) Same argQ Same, but does splitting in double quotes @ Status of last command * Name of shell, usually reflects functions O Last argument of previous command 3 Machine type (run time) BKI0LK. Effective GID (via system call), set if root .4?2 Effective UID (via system call), set if root .I?2 Last system error number .GG16 Real group ID (via system call), set if root 4?2 The current history line number <?;0B@2 The host name <6;0 Line number in shell, function 5?1.16 Login name (exported by default) 5641A@. Machine type (compile time) @AB<0LK. Previous directory 652KH2 Argument for option handled by getopts 6K0AG4 Index of positional parameter in getopts 6K0?12 Operating system type (compile time) 6;0LK. Array giving statuses of last pipeline pipestatus Process ID of parent of main shell KK?2 Current directory KH2 A pseudo-random number, repeating GA126@ Seconds since shell started ;.B612; Depth of current shell ;<5M5 Array giving names of signals signals Status of last command status In always block, 1 if error in try block 0GL3756B:3 .GG6G Terminal associated with shell if any 00L Time for which terminal has been idle 00L?25. Real user ID (via system call), set if root I?2 I;.G1A@. M.126G R;<31A@. R;<3M.G;?61
Version 4.2
Printed at start of first line of output; see above for escape sequences for all K;s Printed for continuation lines Print within select loop For tracing execution (xtrace option) Used with FnQ in prompts Command used when only input redir given Show report if command takes this long (s) Used to return a value e.g. by read Used to return array value Printed on right of screen for first line Printed on right of screeen for continuation line Max number of history lines saved Prompt when correcting spelling Export with stty arguments to command Type of terminal in use (xterm etc.) Format for reporting usage with time Send ;?4A5G@ after seconds of inactivity Path prefix for shells temporary files List of users or all, notme to watch for Format of reports for 'watch Chars considered parts of word by zle String to replace beeps in line editor Used for startup files instead of 8 if set
Page 9
Version 4.2
: (true/false separator for ternary operator) E, =E, -E, )E, /E, FE, ))E, &E, +E, E, ,,E, --E, &&E, ++E, E J (as in C, evaluate both sides and return right hand side).
True if string a does not match pattern b >E Tests and numeric expressions True if string a sorts before string b Usually used after if, while, until or with && or ||, but the status , True if string a sorts after string b may be useful anywhere e.g. as implicit return status for function. -eC True if numerical expressions a and b are equal True if numerical expressions a and b are not equal -ne File tests, e.g. %% -e $ile &&: -lt True if a < b numerically -a True if $ile exists True if a > b numerically -gt True if $ile is block special -b -le True if a b numerically -c True if $ile is character special True if a b numerically -ge True if $ile is directory -d -e True if $ile exists True if $ile is a regular file (not special or directory Combining expressions: expr is any of the above, or the result of -f -g True if $ile has setgid bit set (mode includes 02000) any combination of the following: Group tests # expr $ True if $ile is symbolic link -h True if expr is false and vice versa -k True if $ile has sticky bit set (mode includes 02000) > expr expr* && expr- True if both expressions true True if $ile is named pipe (FIFO) -p expr* expr- True if either expression true -r True if $ile is readable by current process True if $ile has non-zero size -s -u True if $ile has setuid bit set (mode includes 04000) For complicated numeric tests use ## expr $$ where expr is True if $ile is writeable by current process a numeric expression: status is 1 if expr is non-zero else 0. Same -w -x True if $ile executable by current process syntax used in '## expr $$ substitution. Precedences of True if $ile is symbolic link -5 operators from highest to lowest are: -6 True if $ile owned by effective UID of current $unc#arg...$, numeric constant (e.g. X, -V, X.WV, process -(V.Ze-(O), !ar (does not require ' in front unless -4 True if $ile has effective GID of current process some substitution e.g. '!9!ar" is needed, ' is error if True if $ile is a socket (special communication file) -; !ar is to be modified) -1 True if $ile has access time no newer than mod time # expr $ >, 8, == (post- or preincrement), -- (post- or Other single argument tests, e.g. %% -n str &&: predecrement), unary =, unary True if str has non-zero length -n & -o True if option str is set + True if str (number) is open file descriptor -t -z True if str has zero length )) (exponentiation) ), /, F Multiple argument tests e.g. %% a -eC b &&: numerical binary =, binary expressions may be quoted formulae e.g. a()Wb: ,,, --nt True if file a is newer than file b ,, < , -, -E True if file a is older than file b -ot EE, >E -ef True if a and b refer to same file (i.e. are linked) && True if string a matches pattern b E , ++ Same but more modern (and still not often used) EE * (ternary operator)
For functions use zmodload -i zsh/mathfunc; functions available are as described in C math library manual: Single floating point argument, return floating point: acos, acosh, asin, asinh, atan (optional second argument like C atan2), atanh, cbrt, ceil, cos, cosh, erf, erfc, exp, expm(, fabs, floor, gamma, ^O, ^(, lgamma, log, log(O, log(p, logb, sin, sinh, sCrt, tan, tanh, yO, y( Single floating point argument, return integer: ilogb No arguments, return integer: signgam (remember parentheses) Two floating point arguments, return floating point: copysign, fmod, hypot, nextafter One integer, one floating point argument, return floating point: ^n, yn One floating point, one integer argument, return floating point: ldexp, scalb Either integer or floating point, return same type: abs Coerce to floating point: float Coerce to integer: int Optional string argument (read/write variable name), return floating point: randV\ Example use: zmodload -i zsh/mathfunc float x ## x E WZ.V ) sCrt#W$ $$ print '## log#x$/W $$
Page 10
Completion Load new completion system with: autoload -Iz compinit compinit Configuration: uses styles zstyle context st#le !aluec where context may be a pattern matching the following form: :completion:$unc:completer:cmd:arg:tag in which: completion Literal string always used by completion functions $unc Name of directly called widget, blank for contextual completion completer Method of completion e.g. complete; see below cmd Name of command being completed, or special command context arg Only valid with standard parsing: arg-n for nth argument option-opt-n for nth argument of option opt tag Indication of type of thing to be completed at this point. -braceparameter-assignparameter-command-condition-default-eCual-first-math-parameter-redirect-subscript-tilde-Qalue-
Version 4.2
Generic file matching tag X font names Files system types for mount etc. Shell functions, possibly other types Names of files matched by pattern UNIX groups Words from shell history Names of network hosts Indexes of arrays Shell jobs Network interfaces (as from ifconfig) ZLE keymaps Names of X keysyms Names of system libraries System resource limits Subdirectories of current directories Names of manual pages E-mail folders NIS maps etc. Used in format style for messages X modifiers Shell modules etc. Own accounts, with users-hosts style Directories named by a parameter Names of all sorts USENET newgroups Nicknames of NIS maps Options to commands Original when correcting, expanding Other accounts with users-hosts style RPM, Debian etc. packages Names of shell parameters Directories under $cdpath Used with assorted directory paths Perl documentation TCP, UDP prots URL etc. prefixes Names of print queues PIDs Names of processes in killall
Tags: accounts all-expansions all-files arguments arrays association-keys bookmarks Completers ( indicates modifiers existing or later completions): builtins characters 3all3matches Later completers add all matches colormapids Complete with errors in part so far 3approximate colors Basic completion 3complete commands Correct word already typed 3correct contexts Perform shell expansions 3expand corrections 3expand3alias Expand aliases only cursors Complete words from shell history 3history default Reinstate matches omitted 3ignored descriptions List on first completion, insert on second 3list deQices Complete using patterns from line 3match directories Menu completion, no menu selection 3menu Use existing list before generating new one directory-stack 3oldlist displays Complete ignoring whats after cursor 3prefix domains Command contexts: any command name plus the special contexts: expansions file-descriptors -array-Qalue- Element in array
For users-hosts style When expanding, everything at once All files rather than a subset Command arguments Names of array parameters Keys of associative arrays Bookmarks for URLs, ZFTP, etc. Names of builtin commands Character classes, stty characters X colormap IDs Names of colors, usually X External commands, subcommands Contexts in zstyle Possible approximations, corrections X cursor names Nothing specific in certain contexts Used in format style for matches Device special files Directories Entries in pushd directory stack X displays Network domain (DNS) names Individual expansions instead of all Numbers of open file descriptors
Page 11
seCuences sessions signals strings styles suffixes tags targets time-zones types urls users Qalues Qariant Qisuals warnings widgets windows zsh-options MH sequences etc. ZFTP sessions etc. System signal names, HUP etc. Assorted strings, e.g. second arg of cd Styles in zstyle Filename extensions Tags used with rpm etc. Targets inside Makefiles Time zones with TZ parameter etc. Assorted types of anything Used with web addresses Names of users Values in lists Used when picking variant of command X visuals Used in the format style for warnings Names of zsh widgets IDs of X windows Shell options
Version 4.2
Alternative for 8/.muttrc Prefer job numbers instead of name Retain list of matches (3oldlist) Use old match list (3all3matches) Keep list for meus (3oldlist) Add original match for approx/correct For arguments of Debian dpkg For X colors, path to rgb.txt Directory for PINE mailboxes TCP/IP services (/etc/serQices) Hide common prefix e.g. in options Common prefix must by typed by user Initial file patterns to leave alone Range of words in history to consider Complete regular aliases Control remote access for e.g. 3cQs Never complete duplicates in history Prompt shown in menu selection Lines to scroll in menu selection Manual sections used as part of tag Show progress of completers as msg Control 3ignore when single match Override sorting of matches Add . and .. to file list fo//ba is fo/ba not fo/)/ba Pause before looping shell history Remove display name from email addr Only take expansions from globbing When expanding, first try subst Only expand path with no /suffix Preference order for tags in context Determine where URLs are taken from Control caching for various commands Use comptl-style completions Use simpler Perl code for 3make List of user names List of user@"ost possibilities List of user@"ost:port Verbose output e.g. option descriptions Line changes based on current word
Styles ( indicates on by default): Accept exact match even if ambiguous accept-exact Add a space after expansions add-space Cursor after ambiguous path component ambiguous assign-list KA0<-style list on assignment auto-description String for option descs without specific aQoid-completer Avoid completer with 3all3matches Path to top of various caches cache-path Function to decide on cache rebuilding cache-policy If true, use external (slow) command call-command External command to call (+args) command command-path Override KA0< for commands to match Default sys init commands (start etc.) commands complete Complete aliases (3expand3alias) The list of completers to try (see above) completer Delay insertion of matches (_list) condition disabled Disabled aliases (3expand3alias) If set, _c!s uses ls instead of zsh/stat disable-stat domains Net domains (/etc/resolQ.conf) expand For prefix, suffix in multiple parts fake Add !alue:desc fake completions
Page 12
Using 3arguments for parsing standard command arguments: Three arguments give argument/option selector, message to output, action to take. Examples: (:msg:3comp First arg; show msg, exec 3comp Same for optional argument (::msg:3comp Arg number inferred from position :msg:3comp Any of the remaining args (rest args) ):msg:3comp )::msg:3comp words etc. set to normal args set to args for this chunk ):::msg:3comp -foo Complete option -foo =foo Complete option =foo -=foo Complete -foo or =foo Option may occur multiple times )-foo -foo-:esg:3comp Option has arg in same word -foo=:msg:3comp Option has arg in same or next word -fooE:msg:3comp Option arg -fooEbar or -foo bar -fooE-:msg:3comp Option arg is -fooEbar only -foo%desc& Option has description desc ):)pat:msg:3comp Complete words up to pat ):)pat::msg:3comp Modify words etc. for args #-goo -boo$-foo -foo excludes -goo, -boo #)$-foo -foo excludes rest args as matches #:$-foo -foo excludes normal args #-$-foo -foo excludes all options >-foo -foo should not be completed Show message but dont complete ):msg:,spaceMatches are listed items ):msg:#a b$ ):msg:##a_:dsc$$ Matches with descriptions ):msg:--string Array state has string if matched Shell code generates matches ):msg:!code" Insert dummy argument first ):msg:E action ):msg:3comp arg Call 3comp with additional args ):msg: 3comp arg Call 3comp with only given arg -a S set( -c - c Common and specific completion sets - d#set($d -c - c Mutually exclusive sets Allow combined single letters -s Same, even if option has args -sw -Guess options by using --help Same, ignoring options matching pat -- -i pat
Version 4.2
3all3labels tag expl descr compcommand 3next3label tag expl descr Implement loops over different labels for each 3reCuested tag
Page 13
Zsh line editor (zle) Builtin widgets, emacs binding, vicmd binding, viins binding; " denotes escape key: accept-and-hold ea accept-and-infer-next-history accept-and-menu-complete accept-line +@ +@ +@ accept-line-and-down-history +6 argument-base backward-char +7 backward-delete-char +< backward-delete-word backward-kill-line backward-kill-word +H backward-word eb beep beginning-of-buffer-or-history e, beginning-of-history beginning-of-line +A beginning-of-line-hist capitalize-word ec clear-screen +5 +5 +5 complete-word copy-preQ-word e+3 copy-preQ-shell-word copy-region-as-kill ew delete-char delete-char-or-list +2 delete-word describe-key-briefly digit-argument eO.. (..] down-case-word el down-history +n down-line-or-history +n ^ down down-line-or-search emacs-backward-word emacs-forward-word end-of-buffer-or-history eend-of-history end-of-line +. end-of-line-hist end-of-list exchange-point-and-mark +/+/
Version 4.2
+G +G
eh ... e+@ +4 +@ es +0 et +3 eu +p +p k
...
up
+d +4
e+/+6 eC +M eT ef
' 4 +/+D f t D
Page 14
Qi-find-preQ-char-skip Qi-first-non-blank Qi-forward-blank-word Qi-forward-blank-word-end Qi-forward-char Qi-forward-word Qi-forward-word-end Qi-goto-column Qi-goto-mark Qi-goto-mark-line Qi-history-search-backward Qi-history-search-forward Qi-indent Qi-insert Qi-insert-bol Qi-^oin Qi-kill-eol Qi-kill-line Qi-match-bracket Qi-open-line-aboQe Qi-open-line-below Qi-oper-swap-case Qi-pound-insert Qi-put-after Qi-put-before Qi-Cuoted-insert Qi-repeat-change Qi-repeat-find Qi-repeat-search Qi-replace Qi-replace-chars Qi-reQ-repeat-find Qi-reQ-repeat-search Qi-set-buffer Qi-set-mark Qi-substitute Qi-swap-case Qi-undo-change Qi-unindent Qi-up-line-or-history Qi-yank Qi-yank-eol Qi-yank-whole-line 0 + H . l w e
Version 4.2
Set 8th bit in character Control character e.g. _B-a Control character e.g. +a (same as +A) Delete Single backslash Like Emacs editor Like Vi editor in insert mode Like Vi editor in command mode Emergency keymap, not modifiable
U g / * i ? +/+P P 2 +/+7 F 6 o K p . ; 1 G r J h m s 8 u , y L
+I
+M
Special parameters inside user-defined widgets; indicates readonly: Entire editing buffer 7IDD.G Number of screen lines for full buffer 7IDD.G5?1.; B610./0 start, cont, select, Qared BIG;6G Index of cursor position into '7IDD.G Last item to be killed BI07IDD.G Currently history line being retrieved <?;016 Currently selected keymap :.L@AK Keys typed to invoke current widget :.L; Array of previously killed items, can resize killring Last search string in interactive search 5A;0;.AGB< Last widget to be executed 5A;0H?24.0 Part of buffer left of cursor 57IDD.G @AG: Index of mark position into '7IDD.G Numeric argument passed with widget 1I@.G?B Number of bytes still to be read K.12?14 Input already read (no longer being edited) KG.7IDD.G Text to display before editable buffer KG.2?;K5AL Text to display after editable buffer K6;02?;K5AL Part of buffer starting from cursor G7IDD.G Name of widget being executed H?24.0 H?24.0DI1B Name of function implementing 'H?24.0 Implementation style of completion widget H?24.0;0L5. Special characters in bindkey strings: Bell (alarm) _a Backspace _b Escape _e, _. Form feed _f Newline _n Carriage return _r Tab (horizontal) _t Tab (vertical) _Q _nnn Octal character e.g _O\( _xnn Hexadecimal character eg. _xV(
Examples of key binding: bindkey T+xtT gosmacs-transpose-chars bindkey T_e%W8T oQerwrite-mode bindkey -@ Qiins T+uT backward-kill-line bindkey -s T+x+zT T_eCsuspend_nT autoload -Iz replace-string zle -1 replace-string bindkey T_erT replace-string zle -1 replace-string replace-pattern bindkey T_eFT replace-pattern See man zshcontrib for supplied editing functions such as replace-string.