.. historic nodename: Shell Grammar

Shell Grammar
================================================================================
.. index:: single: shell grammar; Command

.. index:: single: grammar, shell; Command

.. historic nodename: Simple Commands & Pipelines

Simple Commands & Pipelines
--------------------------------------------------------------------------------
.. index:: single: simple commands; Command

.. index:: single: commands, simple; Command

A :emphasis:`simple command` is a sequence of optional parameter
assignments followed by blank-separated words,
with optional redirections interspersed.  For a description
of assignment, see the beginning of :manpage:`zshparam`.

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.
For example,

.. code-block:: zsh
   :class: example

    echo foo

is a simple command with arguments.

.. index:: single: pipeline; Command

A :emphasis:`pipeline` is either a simple command, or a sequence of two or more
simple commands where each command is separated from the next by ``|``
or ``|&``.  Where commands are separated by ``|``, the standard
output of the first command is connected to the
standard input of the next.  ``|&`` is shorthand for ``2>&1 |``, which
connects both the standard output and the standard error of the
command to the standard input of the next.  The value of a pipeline
is the value of the last command, unless the pipeline is preceded by
``!`` in which case the value is the logical inverse of the value of the
last command.
For example,

.. code-block:: zsh
   :class: example

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

is a pipeline, where the output (``foo`` plus a newline) of the first
command will be passed to the input of the second.

.. index:: single: coproc; Function

.. index:: single: coprocess; Command

If a pipeline is preceded by ``coproc``, it is executed as a coprocess;
a two-way pipe is established between it and the parent shell.  The
shell can read from or write to the coprocess by means of the ``>&p``
and ``<&p`` redirection operators or with ``print -p`` and ``read -p``.
A pipeline cannot be preceded by both ``coproc`` and ``!``.
If job control is active, the coprocess can be treated in other than input
and output as an ordinary background job.

.. index:: single: sublist; Command

A :emphasis:`sublist` is either a single pipeline, or a sequence of two or more
pipelines separated by ``&&`` or ``||``.  If two pipelines are separated
by ``&&``, the second pipeline is executed only if the first succeeds
(returns a zero status).  If two pipelines are separated by ``||``, the
second is executed only if the first fails (returns a nonzero status).
Both operators have equal precedence and are left associative.
The value of the sublist is the value of the last pipeline executed.
For example,

.. code-block:: zsh
   :class: example

    dmesg | grep panic && print yes

is a sublist consisting of two pipelines, the second just a simple command
which will be executed if and only if the ``grep`` command returns a zero
status.  If it does not, the value of the sublist is that return status, else
it is the status returned by the ``print`` (almost certainly zero).

.. index:: single: list; Command

A :emphasis:`list` is a sequence of zero or more sublists, in which each sublist
is terminated by ``;``, ``&``, ``&|``, ``&!``, or a newline.
This terminator
may optionally be omitted from the last sublist in the list when the
list appears as a complex command inside ``(...)``
or ``{...}``.  When a
sublist is terminated by ``;`` or newline, the shell waits for it to
finish before executing the next sublist.  If a sublist is terminated
by a ``&``, ``&|``, or ``&!``,
the shell executes the last pipeline in it in the background, and
does not wait for it to finish (note the difference from other shells
which execute the whole sublist in the background).
A backgrounded pipeline returns a status of zero.

More generally, a list can be seen as a set of any shell commands
whatsoever, including the complex commands below; this is implied wherever
the word \`list' appears in later descriptions.  For example, the commands
in a shell function form a special sort of list.

.. historic nodename: Precommand Modifiers

Precommand Modifiers
--------------------------------------------------------------------------------
.. index:: single: precommand modifiers; Command

.. index:: single: modifiers, precommand; Command

With the exception of ``nocorrect``, which is a reserved word that
affects further parsing when it is found in command position, each
of the following builtin commands is a :emphasis:`precommand modifier` which
may precede a simple command to alter how that command is interpreted.

.. index:: single: -; Function

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

.. index:: single: builtin; Function

``builtin``
    
    The command word is taken to be the name of a builtin command,
    rather than a shell function or external command.
    

.. index:: single: command; Function

``command`` [ ``-pvV`` ]
    
    The command word is taken to be the name of an external command,
    rather than a shell function or builtin.   If the ``POSIX_BUILTINS`` option
    is set, builtins will also be executed but certain special properties
    of them are suppressed. The ``-p`` flag causes a default path to be
    searched instead of that in ``$path``. With the ``-v`` flag, ``command``
    is similar to ``whence`` and with ``-V``, it is equivalent to ``whence
    -v``.
    

.. index:: single: exec; Function

``exec`` [ ``-cl`` ] [ ``-a`` :var:`argv0` ]
    
    The following command together with any arguments is run in place
    of the current process, rather than as a sub-process.  The shell does not
    fork and is replaced.  The shell does not invoke ``TRAPEXIT``, nor does it
    source ``zlogout`` files.
    The options are provided for compatibility with other shells.
    
    The ``-c`` option clears the environment.
    
    The ``-l`` option is equivalent to the ``-`` precommand modifier, to
    treat the replacement command as a login shell; the command is executed
    with a ``-`` prepended to its ``argv[0]`` string.  This flag has no effect
    if used together with the ``-a`` option.
    
    The ``-a`` option is used to specify explicitly the ``argv[0]`` string
    (the name of the command as seen by the process itself) to be used by the
    replacement command and is directly equivalent to setting a value
    for the ``ARGV0`` environment variable.
    

.. index:: single: nocorrect; Function

``nocorrect``
    
    Spelling correction is not done on any of the words.  This must appear
    before any other precommand modifier, as it is interpreted immediately,
    before any parsing is done.  It has no effect in non-interactive shells.
    

.. index:: single: noglob; Function

``noglob``
    
    Filename generation (globbing) is not performed on any of the words.
    

.. historic nodename: Complex Commands

Complex Commands
--------------------------------------------------------------------------------
.. index:: single: complex commands; Command

.. index:: single: commands, complex; Command

A :emphasis:`complex command` in zsh is one of the following:

.. index:: single: if; Function

.. index:: single: if construct; Command

``if`` :var:`list` ``then`` :var:`list` [ ``elif`` :var:`list` ``then`` :var:`list` ] ... [ ``else`` :var:`list` ] ``fi``
    
    The ``if`` :var:`list` is executed, and if it returns a zero exit status,
    the ``then`` :var:`list` is executed.
    Otherwise, the ``elif`` :var:`list` is executed and if its status is zero,
    the ``then`` :var:`list` is executed.
    If each ``elif`` :var:`list` returns nonzero status, the ``else`` :var:`list`
    is executed.
    

.. index:: single: for; Function

.. index:: single: for loops; Command

.. index:: single: loops, for; Command

``for`` :var:`name` ... [ ``in`` :var:`word` ... ] :var:`term` ``do`` :var:`list` ``done``
    
    Expand the list of :var:`word`\s, and set the parameter
    :var:`name` to each of them in turn, executing :var:`list`
    each time.  If the ``in`` :var:`word` is omitted,
    use the positional parameters instead of the :var:`word`\s.
    If any :var:`name` has been declared as a named reference,
    the corresponding :var:`word` is treated as the name of a
    parameter and :var:`name` is made a reference to that.
    Note that for the positional parameters, this treats the
    value of each positional as parameter name rather than
    creating a reference to the position.
    
    The :var:`term` consists of one or more newline or ``;``
    which terminate the :var:`word`\s, and are optional when the
    ``in`` :var:`word` is omitted.
    
    More than one parameter :var:`name` can appear before the list of
    :var:`word`\s.  If :var:`N` :var:`name`\s are given, then on each execution of the
    loop the next :var:`N` :var:`word`\s are assigned to the corresponding
    parameters.  If there are more :var:`name`\s than remaining :var:`word`\s, the
    remaining parameters are each set to the empty string.  Execution of the
    loop ends when there is no remaining :var:`word` to assign to the first
    :var:`name`.  It is only possible for ``in`` to appear as the first :var:`name`
    in the list, else it will be treated as marking the end of the list.
    

``for ((`` [:var:`expr1`] ``;`` [:var:`expr2`] ``;`` [:var:`expr3`] ``)) do`` :var:`list` ``done``
    
    The arithmetic expression :var:`expr1` is evaluated first (see
    :zshsectref:`Arithmetic Evaluation <below>`).  The arithmetic expression
    :var:`expr2` is repeatedly evaluated until it evaluates to zero and
    when non-zero, :var:`list` is executed and the arithmetic expression
    :var:`expr3` evaluated.  If any expression is omitted, then it behaves
    as if it evaluated to 1.
    

.. index:: single: while; Function

.. index:: single: while loops; Command

.. index:: single: loops, while; Command

``while`` :var:`list` ``do`` :var:`list` ``done``
    
    Execute the ``do`` :var:`list` as long as the ``while`` :var:`list`
    returns a zero exit status.
    

.. index:: single: until; Function

.. index:: single: until loops; Command

.. index:: single: loops, until; Command

``until`` :var:`list` ``do`` :var:`list` ``done``
    
    Execute the ``do`` :var:`list` as long as ``until`` :var:`list`
    returns a nonzero exit status.
    

.. index:: single: repeat; Function

.. index:: single: repeat loops; Command

.. index:: single: loops, repeat; Command

``repeat`` :var:`word` ``do`` :var:`list` ``done``
    
    :var:`word` is expanded and treated as an arithmetic expression,
    which must evaluate to a number :var:`n`.
    :var:`list` is then executed :var:`n` times.
    
    The ``repeat`` syntax is disabled by default when the
    shell starts in a mode emulating another shell.  It can be enabled
    with the command ``enable -r repeat``
    

.. index:: single: case; Function

.. index:: single: case selection; Command

.. index:: single: selection, case; Command

``case`` :var:`word` ``in`` [ [``(``] :var:`pattern` [ ``|`` :var:`pattern` ] ... ``)`` :var:`list` (``;;|;&|;|``) ] ... ``esac``
    
    Execute the :var:`list` associated with the first :var:`pattern`
    that matches :var:`word`, if any.  The form of the patterns
    is the same as that used for filename generation.  See
    :zshsectref:`Filename Generation <zshexpn>`.
    
    Note further that, unless the ``SH_GLOB`` option is set, the whole
    pattern with alternatives is treated by the shell as equivalent to a
    group of patterns within parentheses, although white space may appear
    about the parentheses and the vertical bar and will be stripped from the
    pattern at those points.  White space may appear elsewhere in the
    pattern; this is not stripped.  If the ``SH_GLOB`` option is set, so
    that an opening parenthesis can be unambiguously treated as part of the
    case syntax, the expression is parsed into separate words and these are
    treated as strict alternatives (as in other shells).
    
    If the :var:`list` that is executed is terminated with ``;&`` rather than
    ``;;``, the following list is also executed.  The rule for
    the terminator of the following list ``;;``, ``;&`` or ``;|`` is
    applied unless the ``esac`` is reached.
    
    If the :var:`list` that is executed is terminated with ``;|`` the
    shell continues to scan the :var:`pattern`\s looking for the next match,
    executing the corresponding :var:`list`, and applying the rule for
    the corresponding terminator ``;;``, ``;&`` or ``;|``.
    Note that :var:`word` is not re-expanded; all applicable :var:`pattern`\s
    are tested with the same :var:`word`.
    

.. index:: single: select; Function

.. index:: single: user selection; Command

.. index:: single: selection, user; Command

``select`` :var:`name` [ ``in`` :var:`word` ... :var:`term` ] ``do`` :var:`list` ``done``
    
    where :var:`term` is one or more newline or ``;`` to terminate the :var:`word`\s.
    .. index:: single: REPLY, use of; Variable
    
    
    Print the set of :var:`word`\s, each preceded by a number.
    If the ``in`` :var:`word` is omitted, use the positional parameters.
    The ``PROMPT3`` prompt is printed and a line is read from the line editor
    if the shell is interactive and that is active, or else standard input.
    If this line consists of the
    number of one of the listed :var:`word`\s, then the parameter :var:`name`
    is set to the :var:`word` corresponding to this number.
    If this line is empty, the selection list is printed again.
    Otherwise, the value of the parameter :var:`name` is set to null.
    The contents of the line read from standard input is saved
    in the parameter ``REPLY``.  :var:`list` is executed
    for each selection until a break or end-of-file is encountered.
    

.. index:: single: subshell; Command

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

``{`` :var:`list` ``}``
    
    Execute :var:`list`.
    

.. index:: single: always; Function

.. index:: single: always blocks; Command

.. index:: single: try blocks; Command

``{`` :var:`try-list` ``} always {`` :var:`always-list` ``}``
    
    First execute :var:`try-list`.  Regardless of errors, or ``break`` or
    ``continue`` commands encountered within :var:`try-list`,
    execute :var:`always-list`.  Execution then continues from the
    result of the execution of :var:`try-list`; in other words, any error,
    or ``break`` or ``continue`` command is treated in the
    normal way, as if :var:`always-list` were not present.  The two
    chunks of code are referred to as the \`try block' and the \`always block'.
    
    Optional newlines or semicolons may appear after the ``always``;
    note, however, that they may :emphasis:`not` appear between the preceding
    closing brace and the ``always``.
    
    An \`error' in this context is a condition such as a syntax error which
    causes the shell to abort execution of the current function, script, or
    list.  Syntax errors encountered while the shell is parsing the
    code do not cause the :var:`always-list` to be executed.  For example,
    an erroneously constructed ``if`` block in :var:`try-list` would cause the
    shell to abort during parsing, so that :var:`always-list` would not be
    executed, while an erroneous substitution such as ``${*foo*}`` would
    cause a run-time error, after which :var:`always-list` would be executed.
    
    An error condition can be tested and reset with the special integer
    variable ``TRY_BLOCK_ERROR``.  Outside an :var:`always-list` the value is
    irrelevant, but it is initialised to ``-1``.  Inside :var:`always-list`, the
    value is 1 if an error occurred in the :var:`try-list`, else 0.  If
    ``TRY_BLOCK_ERROR`` is set to 0 during the :var:`always-list`, the error
    condition caused by the :var:`try-list` is reset, and shell execution
    continues normally after the end of :var:`always-list`.  Altering the value
    during the :var:`try-list` is not useful (unless this forms part of an
    enclosing ``always`` block).
    
    Regardless of ``TRY_BLOCK_ERROR``, after the end of :var:`always-list` the
    normal shell status ``$?`` is the value returned from :var:`try-list`.
    This will be non-zero if there was an error, even if ``TRY_BLOCK_ERROR``
    was set to zero.
    
    The following executes the given code, ignoring any errors it causes.
    This is an alternative to the usual convention of protecting code by
    executing it in a subshell.
    
    
    .. code-block:: zsh
       :class: example

        {
            # code which may cause an error
          } always {
            # This code is executed regardless of the error.
            (( TRY_BLOCK_ERROR = 0 ))
        }
        # The error condition has been reset.
    
    
    When a ``try`` block occurs outside of any function, 
    a ``return`` or a ``exit`` encountered in :var:`try-list` does :emphasis:`not` cause
    the execution of :var:`always-list`.  Instead, the shell exits immediately
    after any ``EXIT`` trap has been executed.
    Otherwise, a ``return`` command encountered in :var:`try-list` will cause the
    execution of :var:`always-list`, just like ``break`` and ``continue``.
    
    
    

.. index:: single: function; Function

``function`` [ ``-T`` ] :var:`word` ... [ ``()`` ] [ :var:`term` ] ``{`` :var:`list` ``}``

:var:`word` ... ``()`` [ :var:`term` ] ``{`` :var:`list` ``}``

:var:`word` ... ``()`` [ :var:`term` ] :var:`command`
    
    where :var:`term` is one or more newline or ``;``.
    Define a function which is referenced by any one of :var:`word`.
    Normally, only one :var:`word` is provided; multiple :var:`word`\s
    are usually only useful for setting traps.
    The body of the function is the :var:`list` between
    the ``{`` and ``}``.  See :zshsectref:`Functions <below>`.
    
    The options of ``function`` have the following meanings:
    
    
    -T
        
        Enable tracing for this function, as though with ``functions -T``.  See the
        documentation of the ``-f`` option to the ``typeset`` builtin, in
        :zshsectref:`Shell Builtin Commands <zshbuiltins>`.
        
    
    
    
    If the option ``SH_GLOB`` is set for compatibility with other shells, then
    whitespace may appear between the left and right parentheses when
    there is a single :var:`word`;  otherwise, the parentheses will be treated as
    forming a globbing pattern in that case.
    
    In any of the forms above, a redirection may appear outside the
    function body, for example
    
    
    .. code-block:: zsh
       :class: example

        func() { ... } 2>&1
    
    
    The redirection is stored with the function and applied whenever the
    function is executed.  Any variables in the redirection are expanded
    at the point the function is executed, but outside the function scope.
    

.. index:: single: timing; Command

.. index:: single: time; Function

``time`` [ :var:`pipeline` ]
    
    The :var:`pipeline` is executed, and timing statistics are
    reported on the standard error in the form specified
    by the ``TIMEFMT`` parameter.
    If :var:`pipeline` is omitted, print statistics about the
    shell process and its children.
    

.. index:: single: conditional expression; Command

.. index:: single: [[; Function

``[[`` :var:`exp` ``]]``
    
    Evaluates the conditional expression :var:`exp`
    and return a zero exit status if it is true.
    See :zshsectref:`Conditional Expressions <below>`
    for a description of :var:`exp`.
    

.. historic nodename: Alternate Forms For Complex Commands

Alternate Forms For Complex Commands
--------------------------------------------------------------------------------
.. index:: single: alternate forms for complex commands; Command

.. index:: single: commands, alternate forms for complex; Command

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

The short versions below only work if :var:`sublist` is of the form ``{``
:var:`list` ``}`` or if the ``SHORT_LOOPS`` option is set.  For the ``if``,
``while`` and ``until`` commands, in both these cases the test part of the
loop must also be suitably delimited, such as by ``[[`` :var:`...` ``]]`` or
``((`` :var:`...` ``))``,
else the end of the test will not be recognized.  For the
``for``, ``repeat``, ``case`` and ``select`` commands no such special form
for the arguments is necessary, but the other condition (the special form
of :var:`sublist` or use of the ``SHORT_LOOPS`` option) still applies.
The ``SHORT_REPEAT`` option is available to enable the short version only
for the ``repeat`` command.

``if`` :var:`list` ``{`` :var:`list` ``}`` [ ``elif`` :var:`list` ``{`` :var:`list` ``}`` ] ... [ ``else {`` :var:`list` ``}`` ]
    
    An alternate form of ``if``.  The rules mean that
    
    
    .. code-block:: zsh
       :class: example

        if [[ -o ignorebraces ]] {
          print yes
        }
    
    
    works, but
    
    
    .. code-block:: zsh
       :class: example

        if true {  # Does not work!
          print yes
        }
    
    
    does :emphasis:`not`, since the test is not suitably delimited.
    

``if`` :var:`list` :var:`sublist`
    
    A short form of the alternate ``if``.  The same limitations on the form of
    :var:`list` apply as for the previous form.
    

``for`` :var:`name` ... ``(`` :var:`word` ... ``)`` :var:`sublist`
    
    A short form of ``for``.
    

``for`` :var:`name` ... [ ``in`` :var:`word` ... ] :var:`term` :var:`sublist`
    
    where :var:`term` is at least one newline or ``;``.
    Another short form of ``for``.
    

``for ((`` [:var:`expr1`] ``;`` [:var:`expr2`] ``;`` [:var:`expr3`] ``))`` :var:`sublist`
    
    A short form of the arithmetic ``for`` command.
    

.. index:: single: foreach; Function

``foreach`` :var:`name` ... ``(`` :var:`word` ... ``)`` :var:`list` ``end``
    
    Another form of ``for``.
    

``while`` :var:`list` ``{`` :var:`list` ``}``
    
    An alternative form of ``while``.  Note the limitations on the form of
    :var:`list` mentioned above.
    

``until`` :var:`list` ``{`` :var:`list` ``}``
    
    An alternative form of ``until``.  Note the limitations on the form of
    :var:`list` mentioned above.
    

``repeat`` :var:`word` :var:`sublist`
    
    This is a short form of ``repeat``.
    

``case`` :var:`word` ``{`` [ [``(``] :var:`pattern` [ ``|`` :var:`pattern` ] ... ``)`` :var:`list` (``;;|;&|;|``) ] ... ``}``
    
    An alternative form of ``case``.
    

``select`` :var:`name` [ ``in`` :var:`word` ... :var:`term` ] :var:`sublist`
    
    where :var:`term` is at least one newline or ``;``.
    A short form of ``select``.
    

``function`` :var:`word` ... [ ``()`` ] [ :var:`term` ] :var:`sublist`
    
    This is a short form of ``function``.
    

.. historic nodename: Reserved Words

Reserved Words
--------------------------------------------------------------------------------
.. index:: single: reserved words; Command

.. index:: single: disable, use of; Function

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

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

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

.. historic nodename: Errors

Errors
--------------------------------------------------------------------------------
.. index:: single: errors, handling of; Command

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

Fatal errors found in non-interactive shells include:

    
    * Failure to parse shell options passed when invoking the shell
    * Failure to change options with the ``set`` builtin
    * Parse errors of all sorts, including failures to parse
    mathematical expressions
    * Failures to set or modify variable behaviour with ``typeset``,
    ``local``, ``declare``, ``export``, ``integer``, ``float``
    * Execution of incorrectly positioned loop control structures
    (``continue``, ``break``)
    * Attempts to use regular expression with no regular expression
    module available
    * Failure to create a pipe needed for a pipeline
    * Failure to create a multio
    * Failure to autoload a module needed for a declared shell feature
    * Errors creating command or process substitutions
    * Syntax errors in glob qualifiers
    * File generation errors where not caught by the option ``BAD_PATTERN``
    * All bad patterns used for matching within case statements
    * File generation failures where not caused by ``NOMATCH`` or
    similar options
    * All file generation errors where the pattern was used to create a
    multio
    * Memory errors where detected by the shell
    * Invalid subscripts to shell variables
    * Attempts to assign read-only variables
    * Logical errors with variables such as assignment to the wrong type
    * Use of invalid variable names
    * Errors in variable substitution syntax
    * Failure to convert characters in ``$'...'`` expressions

If the ``POSIX_BUILTINS`` option is set, more errors associated with
shell builtin commands are treated as fatal, as specified by the POSIX
standard.

.. historic nodename: Comments

Comments
--------------------------------------------------------------------------------
.. index:: single: comments; Command

.. index:: single: INTERACTIVE_COMMENTS, use of; Program

.. index:: single: histchars, use of; Variable

In non-interactive shells, or in interactive shells with the
``INTERACTIVE_COMMENTS`` option set, a word beginning
with the third character of the ``histchars`` parameter
(``#`` by default) causes that word and all the following
characters up to a newline to be ignored.

.. historic nodename: Aliasing

Aliasing
--------------------------------------------------------------------------------
.. index:: single: aliasing; Command

Every eligible :emphasis:`word` 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 replacement text ends with a space, the next word in the shell input
is always eligible for purposes of alias expansion.

It is an error for the function name, :var:`word`, in the sh-compatible function
definition syntax :var:`word` ``()`` ... to be a word that resulted
from alias expansion, unless the ``ALIAS_FUNC_DEF`` option is set.

.. index:: single: alias, use of; Function

.. index:: single: aliases, global; Command

An alias is defined using the ``alias`` builtin; global aliases
may be defined using the ``-g`` option to that builtin.

A :emphasis:`word` is defined as:

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

Alias expansion is done on the shell input before any other expansion
except history expansion.  Therefore, if an alias is defined for the
word ``foo``, alias expansion may be avoided by quoting part of the
word, e.g. ``\foo``.  Any form of quoting works, although there is
nothing to prevent an alias being defined for the quoted form such as
``\foo`` as well.

In particular, note that quoting must be used when using ``unalias`` to remove
global aliases:

.. code-block:: zsh
   :class: example

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

When ``POSIX_ALIASES`` is set, only plain unquoted strings are eligible
for aliasing.  The ``alias`` builtin does not reject ineligible aliases,
but they are not expanded.

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

Alias Difficulties
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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

Any set of characters not listed as a word above is not a word, hence no
attempt is made to expand it as an alias, no matter how it is defined
(i.e. via the builtin or the special parameter ``aliases`` described in
:zshsectref:`The zsh/parameter Module <zshmodules>`).
However, as noted in the case of ``POSIX_ALIASES`` above, the shell does
not attempt to deduce whether the string corresponds to a word at the
time the alias is created.

For example, an expression containing an ``=`` at the start of
a command line is an assignment and cannot be expanded as an alias;
a lone ``=`` is not an assignment but can only be set as an alias
using the parameter, as otherwise the ``=`` is taken part of the
syntax of the builtin command.

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

There is a commonly encountered problem with aliases
illustrated by the following code:

.. code-block:: zsh
   :class: example

    alias echobar='echo bar'; echobar

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

.. historic nodename: Quoting

Quoting
--------------------------------------------------------------------------------
.. index:: single: quoting; Command

A character may be :emphasis:`quoted` (that is, made
to stand for itself) by preceding it with a ``\``.
``\`` followed by a newline is ignored.

A string enclosed between ``$``' and ````' is
processed the same way as the string arguments of the
``print`` builtin, and the resulting string is considered to be
entirely quoted.  A literal ````' character can be included in the
string by using the ``\``' escape.

.. index:: single: RC_QUOTES, use of; Program

All characters enclosed between a pair of single quotes (``''``) that
is not preceded by a ``$`` are quoted.  A single quote cannot appear
within single quotes unless the option ``RC_QUOTES`` is set, in which case
a pair of single quotes are turned into a single quote.  For example,

.. code-block:: zsh
   :class: example

    print ''''

outputs nothing apart from a newline if ``RC_QUOTES`` is not set, but one
single quote if it is set.

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