man zsh30misc (Commandes) - Everything and then some
NAME
zshmisc - Everything and then some
SYNOPSIS
Everything I haven't put somewhere else
SHELL GRAMMAR
A simple command is a sequence of optional parameter assignments followed by blank-separated words, with optional redirections interspersed. The first word is the command to be executed, and the remaining words, if any, are arguments to the command. If a command name is given, the parameter assignments modify the environment of the command when it is executed. The value of a simple command is its exit status, or 128 plus the signal number if terminated by a signal.
A pipeline is a sequence of one or more commands separated by | or |&. |& is shorthand for 2>&1 |. The standard output of each command is connected to the standard input of the next command in the pipeline. If a pipeline is preceded by coproc, it is executed as a coprocess; a two-way pipe is established between it and the parent shell. The shell can read from or write to the coprocess by means of the >&p and <&p redirection operators. The value of a pipeline is the value of the last command. If a pipeline is preceded by a !, the value of that pipeline is the logical NOT of the value of the last command.
A sublist is a sequence of one or more pipelines separated by && or ||. If two pipelines are separated by &&, the second pipeline is executed only if the first is successful (returns a zero value). If two pipelines are separated by ||, the second is executed only if the first is unsuccessful (returns a nonzero value). Both operators have equal precedence and are left associative.
A list is a sequence of zero or more sublists separated by, and optionally terminated by, ;, &, &|, &! or a newline. Normally the shell waits for each list to finish before executing the next one. If a list is terminated by &, &| or &!, the shell executes it in the background, and does not wait for it to finish.
PRECOMMAND MODIFIERS
A simple command may be preceded by a precommand modifier which will alter how the command is interpreted. These modifiers are shell builtin commands with the exception of nocorrect which is a reserved word.
- - The command is executed with a - prepended to its argv[0] string.
- noglob Filename generation (globbing) is not performed on any of the words.
- nocorrect Spelling correction is not done on any of the words.
- exec The command is executed in the parent shell without forking.
- command The command word is taken to be the name of an external command, rather than a shell function or builtin.
COMPLEX COMMANDS
A complex command in zsh is one of the following:
- if list then list [ elif list then list ] ... [ else list ] fi
- The if list is executed, and, if it returns a zero exit status, the then list is executed. Otherwise, the elif list is executed and, if its value is zero, the then list is executed. If each elif list returns nonzero, the else list is executed.
- for name [ in word ... term ] do list done
- where term is one ore more newline or ;. Expand the list of words, and set the parameter name to each of them in turn, executing list each time. If the in word is omitted, use the positional parameters instead of the words.
- while list do list done
- Execute the do list as long as the while list returns a zero exit status.
- until list do list done
- Execute the do list as long as until list returns a nonzero exit status.
- repeat word do list done
- word is expanded and treated as an arithmetic expression, which must evaluate to a number n. list is then executed n times.
- case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
- Execute the list associated with the first pattern that matches word, if any. The form of the patterns is the same as that used for filename generation. See Filename Generation below.
- select name [ in word ... term ] do list done
- where term is one ore more newline or ;. Print the set of words, each preceded by a number. If the in word is omitted, use the positional parameters. The PROMPT3 prompt is printed and a line is read from standard input. If this line consists of the number of one of the listed words, then the parameter name is set to the word corresponding to this number. If this line is empty, the selection list is printed again. Otherwise, the value of the parameter name is set to null. The contents of the line read from standard input is saved in the parameter REPLY. list is executed for each selection until a break or end-of-file is encountered.
- ( list )
- Execute list in a subshell. Traps set by the trap builtin are reset to their default values while executing list.
- { list }
- Execute list.
- function word ... [ () ] [ term ] { list }
- word ... () [ term ] { list }
- word ... () [ term ] command
- where term is one or more newline or ;. Define a function which is referenced by any one of word. Normally, only one word is provided; multiple words are usually only useful for setting traps. The body of the function is the list between the { and }. See FUNCTIONS below.
If the option SH_GLOB is set for compatibility with other shells, then whitespace may appear between between the left and right parentheses when there is a single word; otherwise, the parentheses will be treated as forming a globbing pattern in that case.
- time [ pipeline ]
- The pipeline is executed, and timing statistics are reported on the standard error in the form specified by the TIMEFMT parameter. If pipeline is omitted, print statistics about the shell process and its children.
- [[ exp ]]
- Evaluates the conditional expression exp and return a zero exit status if it is true. See Conditional Expressions below for a description of exp.
ALTERNATE FORMS FOR COMPLEX COMMANDS
Many of zsh's complex commands have alternate forms. These particular versions of complex commands should be considered deprecated and may be removed in the future. The versions in the previous section should be preferred instead. The short versions below only work if sublist is of the form { list } or if the NO_SHORT_LOOPS option is not set.
- if list { list } [ elif list { list } ] ... [ else { list } ]
- An alternate form of if.
- if list sublist
- A short form of previous one.
- for name ( word ... ) sublist
- A short form of for.
- for name [ in word ... term ] sublist
- where term is one ore more newline or ;. Another short form of for.
- foreach name ( word ... ) list end
- Another form of for.
- while list { list }
- An alternative form of while.
- until list { list }
- An alternative form of until.
- repeat word sublist
- This is a short form of repeat.
- case word { [ [(] pattern [ | pattern ] ... ) list ;; ] ... }
- An alternative form of case.
- select name [ in word term ] sublist
- where term is one ore more newline or ;. A short form of select.
RESERVED WORDS
The following words are recognized as reserved words when used as the first word of a command unless quoted or disabled using disable -r:
do done esac then elif else fi for case if while function repeat time until select coproc nocorrect foreach end ! [[ { }
Additionally } is recognized in any position if the IGNORE_BRACES option is not set.
COMMENTS
In noninteractive shells, or in interactive shells with the INTERACTIVE_COMMENTS option set, a word beginning with the third character of the histchars parameter (`#' by default) causes that word and all the following characters up to a newline to be ignored.
ALIASING
Every token in the shell input is checked to see if there is an alias defined for it. If so, it is replaced by the text of the alias if it is in command position (if it could be the first word of a simple command), or if the alias is global. If the text ends with a space, the next word in the shell input is treated as though it were in command position for purposes of alias expansion. An alias is defined using the alias builtin; global aliases may be defined using the -g option to that builtin.
Alias substitution is done on the shell input before any other substitution except history substitution. Therefore, if an alias is defined for the word foo, alias substitution may be avoided by quoting part of the word, e.g. \foo. But there is nothing to prevent an alias being defined for \foo as well.
QUOTING
A character may be quoted (that is, made to stand for itself) by preceding it with a \. \ followed by a newline is ignored. All characters enclosed between a pair of single quotes ('') are quoted. A single quote cannot appear within single quotes. Inside double quotes (""), parameter and command substitution occurs, and \ quotes the characters \, `, ", and $.
REDIRECTION
Before a command is executed, its input and output may be redirected. The following may appear anywhere in a simple command or may precede or follow a complex command. Substitution occurs before word or digit is used except as noted below. If the result of substitution on word produces more than one filename, redirection occurs for each separate filename in turn.
- <word
- Open file word as standard input.
- <>word
- Open file word for reading and writing as standard input. If the file does not exist then it is created.
- >word
- Open file word as standard output. If the file does not exist then it is created. If the file exists, and the CLOBBER option is unset, this causes an error; otherwise, it is truncated to zero length.
- >| word
- >! word
- Same as >, except that the file is truncated to zero length if it exists, even if CLOBBER is unset.
- >>word
- Open file word as standard output. If the file exists then output is appended to it. If the file does not exist, and the CLOBBER option is unset, this causes an error; otherwise, the file is created.
- >>| word
- >>! word
- Same as >>, except that the file is created if it does not exist, even if CLOBBER is unset.
- <<[-] word
- The shell input is read up to a line that is the same as word, or to an end-of-file. No parameter substitution, command substitution or filename generation is performed on word. The resulting document, called a here-document, becomes the standard input. If any character of word is quoted with single or double quotes or a \, no interpretation is placed upon the characters of the document. Otherwise, parameter and command substitution occurs, \ followed by a newline is removed, and \ must be used to quote the characters \, $, `, and the first character of word. If <<- is used, then all leading tabs are stripped from word and from the document.
- <<<word
- Perform shell expansion on word and pass the result to standard input.
- <&digit
- The standard input is duplicated from file descriptor digit (see dup(2)). Similarly for standard output using >&digit.
- >&word
- Same as >word 2>&1.
- >>&word
- Same as >>word 2>&1.
- <&-
- Close the standard input.
- >&-
- Close the standard output.
- <&p
- The input from the coprocess is moved to the standard input.
- >&p
- The output to the coprocess is moved to the standard output.
If one of the above is preceded by a digit, then the file descriptor referred to is that specified by the digit (instead of the default 0 or 1). The order in which redirections are specified is significant. The shell evaluates each redirection in terms of the (file descriptor, file) association at the time of evaluation. For example:
... 1>fname 2>&1
first associates file descriptor 1 with file fname. It then associates file descriptor 2 with the file associated with file descriptor 1 (that is, fname). If the order of redirections were reversed, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had been) and then file descriptor 1 would be associated with file fname.
If the user tries to open a file descriptor for writing more than once, the shell opens the file descriptor as a pipe to a process that copies its input to all the specified outputs, similar to tee(1), provided the MULTIOS option is set. Thus:
date >foo >bar
writes the date to two files, named "foo" and "bar". Note that a pipe is an implicit indirection; thus
date >foo | cat
writes the date to the file "foo", and also pipes it to cat.
If the MULTIOS option is set, the word after a redirection operator is also subjected to filename generation (globbing). Thus
: > *
will truncate all files in the current directory, assuming there's at least one. (Without the MULTIOS option, it would create an empty file called "*".)
If the user tries to open a file descriptor for reading more than once, the shell opens the file descriptor as a pipe to a process that copies all the specified inputs to its output in the order specified, similar to cat(1), provided the MULTIOS option is set. Thus
sort <foo <fubar
or even
sort <f{oo,ubar}
is equivalent to "cat foo fubar | sort". Similarly, you can do
echo exit 0 >> *.sh
Note that a pipe is in implicit indirection; thus
cat bar | sort <foo
is equivalent to "cat bar foo | sort" (note the order of the inputs).
If the MULTIOS option is unset, each redirection replaces the previous redirection for that file descriptor. However, all files redirected to are actually opened, so
echo foo > bar > baz
when MULTIOS is unset will truncate bar, and write "foo" into baz.
If a simple command consists of one or more redirection operators and zero or more parameter assignments, but no command name, the command cat is assumed. Thus
< file
copies the contents of file to the standard output.
If a command is followed by & and job control is not active, then the default standard input for the command is the empty file /dev/null. Otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input/output specifications.
COMMAND EXECUTION
If a command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, the function is invoked as described below in FUNCTIONS. If there exists a shell builtin by that name, the builtin is invoked.
Otherwise, the shell searches each element of path for a directory containing an executable file by that name. If the search is unsuccessful, the shell prints an error message and returns a nonzero exit status.
If execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shell script. /bin/sh is spawned to execute it. If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program. The shell will execute the specified interpreter on operating systems that do not handle this executable format in the kernel.
FUNCTIONS
Shell functions are defined with the function reserved word or the special syntax "funcname()". The function reserved word is used to define shell functions. Shell functions are read in and stored internally. Alias names are resolved when the function is read. Functions are executed like commands with the arguments passed as positional parameters. (See Execution below).
Functions execute in the same process as the caller and share all files and present working directory with the caller. A trap on EXIT set inside a function is executed after the function completes in the environment of the caller.
The return builtin is used to return from function calls.
Function identifiers can be listed with the functions builtin. Functions can be undefined with the unfunction builtin.
The following functions, if defined, have special meaning to the shell:
- chpwd
- Executed whenever the current working directory is changed.
- precmd
- Executed before each prompt.
- preexec
- Executed just after a command has been read and is about to be executed. If the history mechanism is active, the string to be executed is passed as an argument.
- periodic
- If the parameter PERIOD is set, this function is executed every PERIOD seconds, just before a prompt.
- TRAPxxx
- If defined and non-null, this function will be executed whenever the shell catches a signal SIGxxx, where xxx is a signal name as specified for the kill builtin (see below). The signal number will be passed as the first parameter to the function. In addition, TRAPZERR is executed whenever a command has a non-zero exit status, TRAPDEBUG is executed after each command, and TRAPEXIT is executed when the shell exits, or when the current function exits if defined inside a function. If a function of this form is defined and null, the shell and processes spawned by it will ignore SIGxxx.
JOBS
If the MONITOR option is set, an interactive shell associates a job with each pipeline. It keeps a table of current jobs, printed by the jobs command, and assigns them small integer numbers. When a job is started asynchronously with &, the shell prints a line which looks like:
[1] 1234
indicating that the job which was started asynchronously was job number 1 and had one (top-level) process, whose process id was 1234.
If a job is started with &| or &!, then that job is immediately disowned. After startup, it does not have a place in the job table, and is not subject to the job control features described here.
If you are running a job and wish to do something else you may hit the key ^Z (control-Z) which sends a TSTP signal to the current job. The shell will then normally indicate that the job has been `suspended', and print another prompt. You can then manipulate the state of this job, putting it in the background with the bg command, or run some other commands and then eventually bring the job back into the foreground with the foreground command fg. A ^Z takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed.
A job being run in the background will suspend if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command ``stty tostop''. If you set this tty option, then background jobs will suspend when they try to produce output like they do when they try to read input.
There are several ways to refer to jobs in the shell. A job can be referred to by the process id of any process of the job or by one of the following:
- %number
- The job with the given number.
- %string
- Any job whose command line begins with string.
- %?string
- Any job whose command line contains string.
- %%
- Current job.
- %+
- Equivalent to %%.
- %-
- Previous job.
The shell learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible. If notify is not set, it waits until just before it prints a prompt before it informs you.
When the monitor mode is on, each background job that completes triggers any trap set for CHLD.
When you try to leave the shell while jobs are running or suspended, you will be warned that `You have suspended (running) jobs.' You may use the jobs command to see what they are. If you do this or immediately try to exit again, the shell will not warn you a second time; the suspended jobs will be terminated, and the running jobs will be sent a SIGHUP signal. To avoid having the shell terminate the running jobs, either use the nohup(1) command or the disown builtin (see below).
SIGNALS
The INT and QUIT signals for an invoked command are ignored if the command is followed by & and the job MONITOR option is not active. Otherwise, signals have the values inherited by the shell from its parent (but see the TRAPxxx special function above).
ARITHMETIC EVALUATION
An ability to perform integer arithmetic is provided with the builtin let. Evaluations are performed using long arithmetic. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers are of the form [base#]n where base is a decimal number between two and thirty-six representing the arithmetic base and n is a number in that base (for example, `16#ff' is 255 in hexadecimal). If base is omitted then base 10 is used. For backwards compatibility the form `[16]ff' is also accepted.
An arithmetic expression uses nearly the same syntax, precedence, and associativity of expressions in C. The following operators are supported (listed in decreasing order of precedence):
- + - ! ++ --
- unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement
- << >>
- bitwise shift left, right
- &
- bitwise AND
- ^
- bitwise XOR
- |
- bitwise OR
- **
- exponentiation
- * / %
- multiplication, division, modulus (remainder)
- + -
- addition, subtraction
- < > <= >=
- comparison
- == !=
- equality and inequality
- &&
- logical AND
- || ^^
- logical OR, XOR
- ? :
- ternary operator
- = += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **= assignment
- ,
- comma operator
The operators &&, ||, &&=, and ||= are short-circuiting, and only one of the latter two expressions in a ternary operator is evaluated. Note the precedence of the bitwise AND, OR, and XOR operators.
An expression of the form #\x where x is any character gives the ascii value of this character and an expression of the form #foo gives the ascii value of the first character of the value of the parameter foo.
Named parameters and subscripted arrays can be referenced by name within an arithmetic expression without using the parameter substitution syntax.
An internal integer representation of a named parameter can be specified with the integer builtin. Arithmetic evaluation is performed on the value of each assignment to a named parameter declared integer in this manner.
Since many of the arithmetic operators require quoting, an alternative form of the let command is provided. For any command which begins with a ((, all the characters until a matching )) are treated as a quoted expression. More precisely, ((...)) is equivalent to let "...".
CONDITIONAL EXPRESSIONS
A conditional expression is used with the [[ compound command to test attributes of files and to compare strings. Each expression can be constructed from one or more of the following unary or binary expressions:
- -a file
- true if file exists.
- -b file
- true if file exists and is a block special file.
- -c file
- true if file exists and is a character special file.
- -d file
- true if file exists and is a directory.
- -e file
- true if file exists.
- -f file
- true if file exists and is an ordinary file.
- -g file
- true if file exists and has its setgid bit set.
- -h file
- true if file exists and is a symbolic link.
- -k file
- true if file exists and has its sticky bit set.
- -n string
- true if length of string is non-zero.
- -o option
- true if option named option is on. option may be a single character, in which case it is a single letter option name. (See the SPECIFYING OPTIONS section of the zshoptions(1) man page.)
- -p file
- true if file exists and is a fifo special file or a pipe.
- -r file
- true if file exists and is readable by current process.
- -s file
- true if file exists and has size greater than zero.
- -t fd
- true if file descriptor number fd is open and associated with a terminal device. (note: fd is not optional)
- -u file
- true if file exists and has its setuid bit set.
- -w file
- true if file exists and is writable by current process.
- -x file
- true if file exists and is executable by current process. If file exists and is a directory, then the current process has permission to search in the directory.
- -z string
- true if length of string is zero.
- -L file
- true if file exists and is a symbolic link.
- -O file
- true if file exists and is owned by the effective user id of this process.
- -G file
- true if file exists and its group matches the effective group id of this process.
- -S file
- true if file exists and is a socket.
- -N file
- true if file exists and its access time is not newer than its modification time.
- file1 -nt file2
- true if file1 exists and is newer than file2.
- file1 -ot file2
- true if file1 exists and is older than file2.
- file1 -ef file2
- true if file1 and file2 exist and refer to the same file.
- string == pattern
- string = pattern
- true if string matches pattern. The first form is the preferred one. The other form is for backward compatibility and should be considered obsolete.
- string != pattern
- true if string does not match pattern.
- string1 < string2
- true if string1 comes before string2 based on ASCII value of their characters.
- string1 > string2
- true if string1 comes after string2 based on ASCII value of their characters.
- exp1 -eq exp2
- true if exp1 is equal to exp2.
- exp1 -ne exp2
- true if exp1 is not equal to exp2.
- exp1 -lt exp2
- true if exp1 is less than exp2.
- exp1 -gt exp2
- true if exp1 is greater than exp2.
- exp1 -le exp2
- true if exp1 is less than or equal to exp2.
- exp1 -ge exp2
- true if exp1 is greater than or equal to exp2.
- ( exp )
- true if exp is true.
- ! exp
- true if exp is false.
- exp1 && exp2
- true if exp1 and exp2 are both true.
- exp1 || exp2
- true if either exp1 or exp2 is true.
In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the test applied to the open file whose descriptor number is n, even if the underlying system does not support the /dev/fd directory.
COMPATIBILITY
Zsh tries to emulate sh or ksh when it is invoked as sh or ksh respectively. In this mode the following parameters are not special and not initialized by the shell: ARGC, argv, cdpath, fignore, fpath, HISTCHARS, mailpath, MANPATH, manpath, path, prompt, PROMPT, PROMPT2, PROMPT3, PROMPT4, psvar, status, watch.
The usual zsh starup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. Note that the PRIVILEGED option also affects the execution of startup files. See zshoptions(1) for more details.
The following options are set if the shell is invoked as sh or ksh: NO_BAD_PATTERN, NO_BANG_HIST, NO_BG_NICE, NO_EQUALS, NO_FUNCTION_ARGZERO, GLOB_SUBST, NO_HUP, INTERACTIVE_COMMENTS, KSH_ARRAYS, NO_MULTIOS, NO_NOMATCH, RM_STAR_SILENT, POSIX_BUILTINS, SH_FILE_EXPANSION, SH_GLOB, SH_OPTION_LETTERS, SH_WORD_SPLIT. Additionally the BSD_ECHO and the IGNORE_BRACES options are set if zsh is invoked as sh and the KSH_OPTION_PRINT, LOCAL_OPTIONS, PROMPT_SUBST and SINGLE_LINE_ZLE options are set if zsh is invoked as ksh.