zash is a small, fast POSIX shell for z/OS UNIX System Services in the
Almquist tradition. This document specifies the language it accepts and
what each construct means, as numbered rules that the test suite cites
and that a later machine-checked model can follow one for one.

Contents

1.  1 Introduction

    1.  1.1 Scope
    2.  1.2 Notation
    3.  1.3 Rule identifiers

2.  2 Lexical structure

    1.  2.1 Input
    2.  2.2 Tokens
    3.  2.3 Quoting
    4.  2.4 Reserved words
    5.  2.5 Here-documents

3.  3 Aliases

4.  4 Grammar

    1.  4.1 Productions
    2.  4.2 Rules attached to the grammar

5.  5 Word expansion

    1.  5.1 Words and fields
    2.  5.2 Tilde expansion
    3.  5.3 Parameter expansion
    4.  5.4 Command substitution
    5.  5.5 Arithmetic expansion
    6.  5.6 Field splitting
    7.  5.7 Pathname expansion

6.  6 Patterns

7.  7 Arithmetic

    1.  7.1 Syntax
    2.  7.2 Values

8.  8 Commands

    1.  8.1 Exit status
    2.  8.2 Simple commands
    3.  8.3 Pipelines
    4.  8.4 Lists
    5.  8.5 Compound commands
    6.  8.6 Functions

9.  9 Conditional expressions [[ ]]

10. 10 Redirection

11. 11 Environment and variables

12. 12 Errors

13. 13 Traps and signals

14. 14 z/OS

15. 15 Differences from POSIX and other shells

16. 16 Mapping to a formal model

1 Introduction

This document specifies the language that zash accepts and what each
construct means. It is the reference for script writers and zash
reviewers. Each rule has an identifier that tests cite, and a later Lean
formalisation will encode each rule as a definition or a theorem.

The base is the Shell Command Language of POSIX.1-2024 (XCU chapter 2).
Where this document is silent, POSIX applies. Where zash differs from
POSIX or extends it, the rule says so and is listed again in Section 15.
The Korn shell constructs the z/OS /bin/sh (of the ksh88 line) offers
are part of the language too, because zash is that shell’s successor;
each is a rule of its own, marked with zash’s status.

1.1 Scope

In scope: the input language (lexical structure and grammar), word
expansion, the meaning of commands, redirections, the environment a
command runs in, exit statuses and errors.

Out of scope: the interactive line editor, history and completion; the
behaviour of individual builtins beyond what the language depends on;
z/OS file tagging and character conversion, which affect the bytes a
file holds but not what a script means (see Section 14).

1.2 Notation

- Grammar productions are in EBNF: a b is sequence, a | b alternation, [
  a ] optional, { a } zero or more, 'x' a literal token. Terminals in
  capitals (WORD, NAME, NEWLINE) are defined in Section 2.
- ⟦e⟧ is the meaning of the phrase e: the value of an arithmetic
  expression, or the list of fields a word expands to.
- A byte is an octet of the input. zash is built for ASCII or for
  IBM-1047 (EBCDIC); every character named in this document by its glyph
  (such as $ or newline) stands for that character’s code in the build’s
  character set. No rule depends on the numeric value of a code unless
  it says so.
- Numbered rules are normative. Note blocks are not.
- Open blocks mark questions this draft has not decided. Each must be
  answered by reading the implementation or by a test before the rule it
  belongs to is final.

1.3 Rule identifiers

Rules are numbered R-chapter-n. The chapter codes are LEX (lexical
structure), ALI (aliases), GRM (grammar), EXP (word expansion), ARI
(arithmetic), PAT (patterns), CMD (commands), CND (conditional
expressions), RED (redirection), ENV (environment and variables), ERR
(errors) and SIG (traps). An identifier, once published, is not reused
for a different statement.

2 Lexical structure

2.1 Input

R-LEX-1 The input is a sequence of bytes, read from a file, a string
(-c, eval, command substitution) or standard input. The byte value 0
(NUL) ends a line’s text; behaviour after it within the same line is
unspecified.

R-LEX-2 When the input is standard input, zash reads no byte beyond the
end of the command it is about to run. A command that reads standard
input therefore sees the rest of the script. Extension: POSIX allows a
shell to read ahead.
Tests: zash/stdin-script

R-LEX-3 A backslash immediately followed by newline, outside single
quotes and outside $'...', is removed together with the newline before
tokenisation (line continuation). Inside a here-document body it is
removed only when the delimiter was unquoted.

2.2 Tokens

The lexer turns input into a sequence of tokens. A token is an operator,
a word, an IO_NUMBER or NEWLINE.

R-LEX-4 The operators are exactly:

    control:      &   &&   (   )   ;   ;;   |   ||   NEWLINE
    redirection:  <   >   >|   >>   <>   <&   >&   <<   <<-

The longest operator that matches the input is taken. There is no ;&,
;;&, |&, &> or <<<.

R-LEX-5 Unquoted blanks (space and tab) separate tokens and are
otherwise discarded. An unquoted # at the start of a token begins a
comment that extends to, but does not include, the next newline.

R-LEX-6 A token consisting only of decimal digits, immediately followed
by < or > with no blank between, is an IO_NUMBER. Only the values 0 to 9
name descriptors a script may use; a larger IO_NUMBER is an error when
the redirection is performed (see Section 10).
Tests: posix/redir, posix/fdmap

R-LEX-7 Any other token is a WORD. A WORD that is a valid NAME followed
by = is an assignment word when it appears where Section 4 allows one. A
NAME is a non-empty sequence of letters, digits and underscores that
does not begin with a digit; letters are a–z and A–Z of the build’s
character set.

2.3 Quoting

Quoting determines which characters are literal. Each byte of a word
carries a quoted flag that survives until field splitting and pathname
expansion have used it (Section 5); nothing is encoded in the text.

R-LEX-8 Backslash. Outside quotes, \c makes c literal and quoted, for
any c but newline (line continuation, above).
Tests: posix/quoting

R-LEX-9 Single quotes. '...' makes every byte up to the next ' literal
and quoted. A single quote cannot occur inside.
Tests: posix/quoting

R-LEX-10 Double quotes. Inside "..." every byte is quoted. $ and
backquote keep their meaning. A backslash keeps its meaning only before
$, backquote, ", \ and newline; elsewhere it is literal. Inside "${...}"
a further pair of double quotes nests: "${x:-"}"}" is one word whose
default is the string }.
Tests: posix/quoting, posix/param-word

R-LEX-11 Dollar-single quotes. $'...' is a quoted string in which these
escapes are decoded when the word is read, and the result is literal and
quoted:

  ------------------------- --------------------------------------------------------
  \a \b \e \f \n \r \t \v   the control character so named (\e is escape)
  \\ \' \" \?               the character itself
  \ooo                      the byte with octal value ooo (one to three digits)
  \xhh                      the byte with hexadecimal value hh (one or two digits)
  \cX                       control-X, in ASCII builds only
  any other escape          kept as written, backslash included
  ------------------------- --------------------------------------------------------

$'...' is recognised only where $ would begin an expansion outside
double quotes. Inside double quotes and in here-documents it is not
special. Extension: POSIX.1-2024 has $'...'; the set of escapes is
zash’s.
Tests: zash/ansi-quote.ascii

Open. Does \u (and \U) in $'...' decode a code point? zash currently
keeps it literally; bash, ksh93 and mksh encode UTF-8 and dash rejects
it. Decide, then write the rule.

2.4 Reserved words

R-LEX-12 The reserved words are

    !  {  }  case  do  done  elif  else  esac  fi  for  function  if  in
    select  then  time  until  while  [[  ]]

A word is recognised as reserved only when it is unquoted, is the whole
token and appears where Section 4 expects that reserved word (in
particular, as the first word of a command, or in/do in the positions of
for and case). Elsewhere it is an ordinary word. Difference: function,
select, time, [[ and ]] are reserved in zash, so no command can be named
function.
Tests: posix/syntax, zash/function-kw, zash/cond

2.5 Here-documents

R-LEX-13 For each << or <<- operator, the word after it is the
delimiter. The body is read starting at the line after the next NEWLINE
token that is not itself inside a here-document, and consists of the
lines up to (not including) a line equal to the delimiter after quote
removal. Several here-documents on one line are read in order.
Tests: posix/heredoc, posix/heredoc-edge

R-LEX-14 If any part of the delimiter was quoted, the body is literal.
Otherwise the body is expanded as if in double quotes, except that " is
not special: parameter, command and arithmetic expansion are performed
and \ is special only before $, backquote, \ and newline.
Tests: posix/heredoc, posix/heredoc-edge

R-LEX-15 With <<-, leading tab characters are removed from each body
line and from the delimiter line before the comparison.
Tests: posix/heredoc

R-LEX-16 A command substitution has its own here-document queue. A
here-document started inside $(...) is read inside it, and one started
outside is not satisfied by lines inside it. A $(...) that appears in a
here-document body is parsed with the same rule.
Tests: posix/heredoc-cmdsub, zash/heredoc-fuzz

R-LEX-17 End of input before the delimiter line ends the body without
error. zash does not warn about it (bash does).
Tests: posix/heredoc

3 Aliases

R-ALI-1 When a WORD that is unquoted and a valid alias name occurs where
the first word of a simple command is expected, and an alias of that
name is defined, the word is replaced by the alias’s value, which is
then read as input.
Tests: zash/alias

R-ALI-2 If an alias’s value ends in a blank, the next word is also
checked for alias substitution.
Tests: zash/alias

R-ALI-3 Cycles. While substituting, each alias may be used at most once
in one chain of substitutions: a chain starts at a command word and
continues only through values that end in a blank or that consist of a
single word that is itself an alias. An alias already used in the
current chain is left as an ordinary word. Thus alias a=b b=a; a runs a
command named a (or b) and does not loop.
Tests: posix/alias-cycle

R-ALI-4 Alias substitution happens when a command is parsed, not when it
runs. An alias defined by a command takes effect for commands parsed
after that command has run, never for the rest of the line or compound
command that defined it.

4 Grammar

4.1 Productions

    program        = linebreak [ complete_list ] ;
    complete_list  = list [ separator ] ;
    list           = and_or { separator_op linebreak and_or } ;
    and_or         = pipeline { ( '&&' | '||' ) linebreak pipeline } ;
    pipeline       = [ 'time' [ '-p' ] ] [ '!' ] pipe_sequence
                   | 'time' [ '-p' ] ;                 (* time with no command *)
    pipe_sequence  = command { '|' linebreak command } ;

    command        = simple_command
                   | compound_command { redirection }
                   | function_definition ;

    compound_command
                   = brace_group | subshell | arith_command | cond_command
                   | for_clause | case_clause | if_clause
                   | while_clause | until_clause ;

    brace_group    = '{' compound_list '}' ;
    subshell       = '(' compound_list ')' ;
    arith_command  = '((' ARITH_TEXT '))' ;            (* see the (( rule *)
    cond_command   = '[[' cond_expr ']]' ;              (* see the [[ ]] chapter *)

    for_clause     = ( 'for' | 'select' ) NAME linebreak
                     [ 'in' { WORD } sequential_sep ] do_group ;
    case_clause    = 'case' WORD linebreak 'in' linebreak
                     { case_item } 'esac' ;
    case_item      = [ '(' ] pattern { '|' pattern } ')'
                     ( compound_list | linebreak )
                     ( ';;' linebreak | (* before esac *) ) ;
    pattern        = WORD ;
    if_clause      = 'if' compound_list 'then' compound_list
                     { 'elif' compound_list 'then' compound_list }
                     [ 'else' compound_list ] 'fi' ;
    while_clause   = 'while' compound_list do_group ;
    until_clause   = 'until' compound_list do_group ;
    do_group       = 'do' compound_list 'done' ;

    function_definition
                   = NAME '(' ')' linebreak function_body
                   | 'function' NAME linebreak function_body ;
    function_body  = compound_command { redirection } ;

    simple_command = prefix [ WORD { WORD | redirection } ]
                   | WORD { WORD | redirection } ;
    prefix         = ( ASSIGNMENT_WORD | redirection )
                     { ASSIGNMENT_WORD | redirection } ;
    redirection    = [ IO_NUMBER ] redir_op WORD ;
    redir_op       = '<' | '>' | '>|' | '>>' | '<>' | '<&' | '>&' | '<<' | '<<-' ;

    compound_list  = linebreak list [ separator ] ;
    separator_op   = '&' | ';' ;
    separator      = separator_op linebreak | newline_list ;
    sequential_sep = ';' linebreak | newline_list ;
    linebreak      = [ newline_list ] ;
    newline_list   = NEWLINE { NEWLINE } ;

4.2 Rules attached to the grammar

R-GRM-1 The grammar above is that of POSIX XCU 2.10 with these changes:
time and ! prefixes on a pipeline, the function form of a function
definition, arith_command, cond_command and select in place of for. A
program that the grammar does not derive is a syntax error (Section 12).
Tests: posix/syntax

R-GRM-2 An ASSIGNMENT_WORD is recognised only in prefix, that is, before
the command name. After the command name, NAME=value is an ordinary
argument.
Tests: posix/syntax

R-GRM-3 function NAME body and NAME() body define the same thing: a
function whose body is the compound command with its redirections. The
two forms are identical. Difference: ksh gives the function form local
traps and $0; zash does not.
Tests: zash/function-kw

R-GRM-4 In a case_clause, the last case_item may omit ;; before esac.
There is no fall-through operator.
Tests: posix/case-edge

R-GRM-5 for NAME do ... and for NAME; do ... without in iterate over the
positional parameters as they were when the loop started (Section 8).

R-GRM-6 (zash) select NAME [in WORD ...] do LIST done is the ksh88 menu
loop, and zash is that shell’s successor, so it is part of the language.
It is the for_clause with select in place of for, and it repeats:

1.  write the words to standard error, one per line, as the number of
    the word, a tab, and the word;
2.  write the value of PS3 (default #?) to standard error, with no
    newline, and flush;
3.  read one line from standard input into REPLY, with the rules of read
    without -r; end of input ends the loop;
4.  if the line is empty, repeat from the top;
5.  if the line is a number in range, assign that word to NAME;
    otherwise assign the empty string;
6.  run the list.

The menu is written again before every prompt, not once per loop.
Difference: no other shell in scope has select.
Tests: zash/select

R-GRM-7 Choosing between (( and ( (. When (( begins a command, the text
up to the matching )) is an arith_command unless one of the following
holds, in which case the input is read as a subshell whose first command
is itself a subshell:

1.  a ; occurs outside quotes before the matching ));
2.  a word character (letter, digit, _, $, ", ') follows a word that
    ended in a letter, digit, _ or }, with only blanks or newlines
    between them (two adjacent words: a command, not an expression);
3.  the text exceeds 4096 bytes;
4.  the text begins with more than 8 consecutive (;
5.  a ) that closes the outermost level is not immediately followed by a
    second ).

The scan for the matching )) honours quotes and backslashes. To be
certain of nested subshells, write ( (. Difference: a heuristic; POSIX
leaves (( unspecified.
Tests: zash/arith-ext, posix/subshell-edge

Note. The parser decides this with a bounded scan of the characters. A
formalisation should state the rule as a decidable predicate on the
character sequence and prove that the parser applies it.

R-GRM-8 $(( always begins arithmetic expansion. Write $( ( for a command
substitution that begins with a subshell.
Tests: posix/cmdsub

5 Word expansion

5.1 Words and fields

A word, as parsed, is a list of parts. A part is literal text, a
parameter expansion, a command substitution or an arithmetic expansion,
and each part carries a quoted flag. Expansion turns a word into a list
of fields; each byte of a field carries a quoted flag inherited from the
part that produced it.

Formally, let B be the set of bytes and Q = B × {0, 1} the set of
flagged bytes. A field is a finite sequence in Q^(*), and

⟦w⟧ : Word → (Field)^(*)

is computed in the four steps below. Quote removal is the projection π₁
from Q^(*) to B^(*) applied to every resulting field.

R-EXP-1 Order. For each word, the shell performs

1.  tilde expansion, parameter expansion, command substitution and
    arithmetic expansion, in one left-to-right pass over the parts;
2.  field splitting of the results of unquoted expansions (step 1 only);
3.  pathname expansion of each field that contains an unquoted pattern
    character;
4.  quote removal.

No byte that came from the text of the script is ever split, and no
quoted byte is ever split or treated as a pattern character.
Tests: posix/expand-edge, posix/edge

R-EXP-2 Contexts without splitting. In assignments (NAME=word), the word
of a case, the target of a redirection other than a here-document, the
operands of [[ ]] and the word in ${x op word}, steps 2 and 3 are not
performed and the result is one field. (A redirection target that would
expand to more than one field is still one field.)
Tests: posix/expand-edge

5.2 Tilde expansion

R-EXP-3 An unquoted ~ at the start of a word, followed by the characters
up to the first unquoted / (or the end of the word), is a tilde-prefix.
~ alone is replaced by $HOME; ~name by the home directory of user name.
If the user does not exist the prefix is left unchanged. The result is
quoted (it is not split or globbed).
Tests: posix/misc, posix/param-word

R-EXP-4 In an assignment word, tilde expansion is also performed after
each unquoted : in the value.
Tests: posix/misc

R-EXP-5 The word in ${x-word}, ${x=word}, ${x?word} and ${x+word} (and
their : forms) undergoes tilde expansion when it is not within double
quotes.
Tests: posix/param-word

5.3 Parameter expansion

R-EXP-6 A parameter is a NAME (a variable), a positional parameter (a
decimal number; more than one digit requires braces: ${10}), or one of
the special parameters @ * # ? - $ ! and 0.
Tests: posix/params

R-EXP-7 The conditional forms, for a parameter x and a word w, yield:

  --------- ------------------ -------------- ------------
  form      x set, non-empty   x set, empty   x unset
  ${x:-w}   x                  ⟦w⟧            ⟦w⟧
  ${x-w}    x                  empty          ⟦w⟧
  ${x:=w}   x                  assign ⟦w⟧     assign ⟦w⟧
  ${x=w}    x                  empty          assign ⟦w⟧
  ${x:?w}   x                  error          error
  ${x?w}    x                  empty          error
  ${x:+w}   ⟦w⟧                empty          empty
  ${x+w}    ⟦w⟧                ⟦w⟧            empty
  --------- ------------------ -------------- ------------

assign sets x to the value and yields it; a positional or special
parameter cannot be assigned to this way; attempting to do so is an
error. error writes ⟦w⟧, or a default message if w is empty, and is an
expansion error (Section 12). The word w is expanded only when its value
is used.
Tests: posix/params, posix/expand-edge

R-EXP-8 ${#x} is the length of the value of x in bytes, as a decimal
number. ${#*} and ${#@} are the number of positional parameters.
Tests: posix/params

R-EXP-9 Trimming. For a pattern p (the word, expanded, with its quoted
bytes literal):

- ${x#p} removes the shortest prefix of x that p matches;
- ${x##p} removes the longest such prefix;
- ${x%p} removes the shortest matching suffix;
- ${x%%p} removes the longest matching suffix.

If no prefix (suffix) matches, the value is unchanged. Matching is that
of Section 6, applied to the whole candidate prefix or suffix.

For ${@#p}, ${*#p} and the other three operators the trim applies to
each positional parameter on its own, before the results are joined the
way $@ and $* are joined below: quoted @ gives one field per parameter,
quoted * joins them with the first character of IFS, and an unquoted
expansion is split.
Tests: posix/params, zash/trim-long, zash/trim-all

Note. zash computes a trim in one pass for patterns of up to 63 elements
and tries each length otherwise. Both methods must give the shortest or
longest match this rule defines. That proof is the first theorem planned
for the Lean model.

R-EXP-10 With set -u, expanding an unset parameter other than @ and *,
except in a conditional form that handles unset, is an expansion error.
Tests: zash/ash-differences

R-EXP-11 $@ and $*. Unquoted, each positional parameter becomes a
separate field before field splitting, and each is then split. Quoted,
"$@" yields one field per positional parameter, with any adjacent text
of the word joined to the first and last of them, and no field at all
when there are none; "$*" yields one field: the parameters joined by the
first character of IFS (by nothing if IFS is empty, by a space if IFS is
unset).
Tests: posix/expand-edge, posix/split

Open. Unquoted $@ and $* in a here-document body and in other
no-splitting contexts. Differential testing showed zash treating quote
characters there differently from dash, bash and ksh93. Decide which
behaviour is intended, then write the rule.

5.4 Command substitution

R-EXP-12 $(list), and the older backquoted form, run list in a subshell
environment and are replaced by its standard output with every trailing
newline removed. $(...) is parsed when the enclosing word is read; the
backquoted form is parsed after backquote backslash processing.
Tests: posix/cmdsub

R-EXP-13 $(<file) is replaced by the contents of file, with trailing
newlines removed, as if by $(cat file). A file that cannot be opened is
an expansion error.
Tests: zash/purebuiltin, zash/cmdsub-file

Note. Whether a substitution creates a process is not part of the
language; zash runs many of them in the shell. The observable behaviour
must be that of a subshell: assignments and cd inside do not affect the
caller. The process-accounting tests (tests/proc/) check the cost, and
are not cited by rules.

5.5 Arithmetic expansion

R-EXP-14 $((expression)) is replaced by the decimal value of the
expression (Section 7). The text of the expression first undergoes
parameter expansion, command substitution and quote removal, as in
double quotes.
Tests: posix/arith

5.6 Field splitting

Let I be the value of IFS (if unset, space, tab and newline). Bytes of I
that are space, tab or newline are IFS white space; the others are IFS
delimiters.

R-EXP-15 Only unquoted bytes that came from an unquoted expansion are
considered. If I is empty, no splitting is done. Otherwise:

1.  IFS white space at the start and end of the expansion result is
    ignored;
2.  each IFS delimiter, with any IFS white space next to it, ends a
    field;
3.  each other sequence of IFS white space ends a field;
4.  a field is produced between two delimiters even if it is empty, but
    no empty field is produced at the end.

Tests: posix/split

R-EXP-16 A word whose expansion produces no bytes at all and contains no
quoted part produces no field (it disappears). A word with a quoted part
that is empty ("") produces one empty field.
Tests: posix/split

5.7 Pathname expansion

R-EXP-17 A field containing an unquoted *, ? or [ is a pattern
(Section 6) matched against pathnames. / is never matched by a pattern
character; each slash-separated component is matched separately. A
component beginning with . is matched only by a pattern component
beginning with an unquoted .. The matches replace the field, in the
collating order of Section 6. If nothing matches, the field is left as
it is.
Tests: posix/glob, posix/glob-edge

R-EXP-18 With set -f, pathname expansion is not performed.
Tests: posix/glob

6 Patterns

R-PAT-1 A pattern is a sequence of elements. Each unquoted byte is:

- *: matches any sequence of bytes, including the empty one;
- ?: matches any one byte;
- [: begins a bracket expression (below) if a matching ] follows;
  otherwise it is literal;
- anything else: matches itself.

A quoted byte always matches only itself.
Tests: posix/case-edge, posix/glob-edge

R-PAT-2 A bracket expression [...] matches one byte that is in its set.
If its first byte is ! or ^, it matches one byte that is not in the set.
A ] in the first position (immediately after any negation) is a literal
member. a-b is a range: all bytes whose code is between those of a and b
inclusive, in the build’s character set. [:class:] adds the bytes of a
character class: alnum alpha blank cntrl digit graph lower print punct
space upper xdigit. Difference: ^ as negation is not POSIX.
Tests: posix/case-edge, posix/charset

R-PAT-3 Ranges and the collating order of pathname expansion use byte
codes, not the locale. In an EBCDIC build [a-z] therefore contains more
than the 26 lower-case letters; scripts that must be portable use
[[:lower:]].
Tests: posix/collate.ascii

R-PAT-4 For a pattern p and a string s, match(p, s) holds when p matches
the whole of s. It is defined by:

$$\begin{matrix}
{\text{match}\left( {\varepsilon,s} \right)} & {\Longleftrightarrow s = \varepsilon} \\
{\text{match}\left( {\ast p',s} \right)} & {\Longleftrightarrow\exists i.\ \text{match}\left( {p',s\left\lbrack {i..} \right\rbrack} \right)} \\
{\text{match}\left( {ep',cs'} \right)} & {\Longleftrightarrow e\ \text{matches}\ c \land \text{match}\left( {p',s'} \right)}
\end{matrix}$$

where e is ?, a bracket expression or a literal byte.

7 Arithmetic

7.1 Syntax

    expr     = assign { ',' assign } ;
    assign   = cond | LVALUE assign_op assign ;
    assign_op= '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>='
             | '&=' | '^=' | '|=' ;
    cond     = lor [ '?' expr ':' cond ] ;
    lor      = land { '||' land } ;
    land     = bor  { '&&' bor } ;
    bor      = bxor { '|' bxor } ;
    bxor     = band { '^' band } ;
    band     = equ  { '&' equ } ;
    equ      = rel  { ( '==' | '!=' ) rel } ;
    rel      = shift { ( '<' | '<=' | '>' | '>=' ) shift } ;
    shift    = add  { ( '<<' | '>>' ) add } ;
    add      = mul  { ( '+' | '-' ) mul } ;
    mul      = unary { ( '*' | '/' | '%' ) unary } ;
    unary    = ( '+' | '-' | '!' | '~' ) unary
             | ( '++' | '--' ) LVALUE
             | postfix ;
    postfix  = primary | LVALUE ( '++' | '--' ) ;
    primary  = NUMBER | LVALUE | '(' expr ')' ;
    LVALUE   = NAME ;
    NUMBER   = decimal | '0' octal_digits | ( '0x' | '0X' ) hex_digits ;

Blanks and newlines between tokens are ignored.

7.2 Values

R-ARI-1 Values are 64-bit two’s-complement integers. Every operation is
computed modulo 2⁶⁴ and the result is taken as signed: overflow wraps
and is not an error. In particular

⟦a + b⟧ = signed((⟦a⟧ + ⟦b⟧)mod 2⁶⁴)

and likewise for -, *, unary - and <<.
Tests: posix/arith, posix/arith-edge

R-ARI-2 / truncates toward zero and % has the sign of the dividend. A
right operand of 0 for / or % is an error. The quotient of the most
negative value by −1 is the most negative value (it wraps).
Tests: posix/arith-edge

R-ARI-3 Shift counts are taken modulo 64. >> is an arithmetic shift.
Tests: posix/arith-edge

R-ARI-4 Relational, equality and logical operators yield 1 for true and
0 for false. &&, || and ?: evaluate their right (or untaken) operand
only when needed; an assignment in an operand that is not evaluated does
not happen.
Tests: posix/arith

R-ARI-5 Variables. A NAME in an expression stands for the value of that
variable: 0 if it is unset or empty; otherwise the value is itself
evaluated as an arithmetic expression. Such nested evaluation may go 16
levels deep; exceeding this depth is an error (“expression recursion too
deep”).
Tests: zash/arith-ext, zash/ash-differences

R-ARI-6 ++, --, the compound assignments and , are as in C. An
assignment stores the decimal value in the variable and yields it.
Assigning to a read-only variable is an error. Extension: POSIX requires
neither ++/-- nor ,.
Tests: zash/arith-ext

R-ARI-7 A NUMBER that does not fit in 64 bits, or text that the syntax
does not derive, is an error.
Tests: posix/arith-edge

R-ARI-8 Extension. base#number, as in bash and ksh93: the number is read
in base, 2 to 64, with the digits 0-9 (0 to 9), a-z (10 to 35), A-Z (36
to 61), @ (62) and _ (63). A base outside 2 to 64, no digits at all, a
digit not in the base, or a number that does not fit in 64 bits is an
error. POSIX requires none of this; 16#ff is the form scripts use.
Tests: zash/arith-base

8 Commands

8.1 Exit status

R-CMD-1 Every command has an exit status, an integer from 0 to 255. Zero
is true (success), anything else false. $? is the status of the most
recently completed pipeline.

R-CMD-2 For a simple command the status is the program’s exit status,
except: 127 if the command was not found; 126 if it was found but could
not be run; 128 + n if it was ended by signal n; 2 if a redirection on
it failed; the status of the last command substitution if the command
had no command name; 0 if it had neither.
Tests: posix/execfail

8.2 Simple commands

R-CMD-3 A simple command is performed in this order:

1.  the words that are not assignments or redirections are expanded
    (Section 5); the first field, if any, is the command name;
2.  redirections are performed, left to right (Section 10);
3.  each assignment is expanded and applied, left to right.

If there is no command name, the assignments affect the current shell
and redirections are performed and undone.
Tests: posix/vars, posix/redir

R-CMD-4 Command search. A command name without / is looked up in this
order: special builtin; function; regular builtin; then the directories
of PATH, left to right, selecting the first executable file found. An
empty PATH entry means the current directory. A name containing / is run
as that path. A path found in PATH is remembered; it is looked up again
if running it fails with “no such file” or “not a directory”.
Tests: posix/functions, posix/misc-builtins

R-CMD-5 If the system refuses to execute a file because it is not an
executable format, and the file begins with #!, the interpreter named on
that line is run with the file as its argument; otherwise zash runs the
file as a script in a new zash process, with the same arguments.
Tests: posix/execfail, scripts/library

R-CMD-6 Assignments before a command. For an external command they are
put in that command’s environment only. For a special builtin they
affect the current shell and persist. For a function or a regular
builtin they are in effect while it runs and are then undone.
Tests: posix/vars, posix/functions

R-CMD-7 The special builtins are : . break continue eval exec exit
export readonly return set shift times trap unset. An error in a special
builtin is a fatal error in a non-interactive shell (Section 12), except
when the builtin was run through command, in which case the error is
only the command’s status.
Tests: posix/command-special

8.3 Pipelines

R-CMD-8 In c1 | c2 | ... | cn, the standard output of each command is
connected to the standard input of the next. The commands run
concurrently. The status is that of cn, unless set -o pipefail is on, in
which case it is that of the last command that failed, or 0.
Tests: posix/pipes

R-CMD-9 The last stage. When job control is off, cn runs in the current
shell environment if it is not an external command: assignments and cd
in it persist after the pipeline. Every other stage runs in a subshell
environment. When job control is on (set -m), every stage runs in a
subshell environment. Difference: dash and bash run every stage in a
subshell; this is the ksh and z/OS /bin/sh behaviour.
Tests: zash/lastpipe, posix/pipes

R-CMD-10 ! pipeline has status 0 if the pipeline’s status is not 0, and
1 otherwise.
Tests: posix/control

R-CMD-11 time pipeline runs the pipeline and then writes to standard
error the real time and the user and system CPU time it used, shell and
children. -p selects the POSIX format. time alone reports the shell’s
own totals. The status is the pipeline’s.
Tests: zash/zos-options

8.4 Lists

R-CMD-12 a && b runs b only if a succeeded; a || b only if it failed.
The status is that of the last command run. ; and newline run commands
in sequence.
Tests: posix/control

R-CMD-13 c & runs c asynchronously in a subshell environment, with
standard input from /dev/null when job control is off and no input
redirection is given. $! is set to the process ID of c (of its last
stage, for a pipeline). The status of c & itself is 0.
Tests: zash/jobs

8.5 Compound commands

R-CMD-14 ( list ) runs list in a subshell environment: nothing it
changes (variables, functions, options, directory, traps, open files) is
visible afterwards. { list; } runs list in the current environment. The
status of each is that of list.
Tests: posix/subshell-edge

R-CMD-15 for x in w1 ... wn; do body; done expands the words (with field
splitting and pathname expansion) once, then for each resulting field
assigns it to x and runs body. Without in, the fields are the positional
parameters as they were when the loop started; changing them inside the
body (for example with set --) does not change the iteration. The status
is that of the last body run, or 0 if none ran.
Tests: posix/control, posix/for-set

R-CMD-16 case w in ... expands w once (without splitting or globbing)
and runs the body of the first item with a matching pattern (expanded
likewise; Section 6). Status: that of the body run, or 0 if none
matched.
Tests: posix/case-edge

R-CMD-17 if, while and until are as in POSIX. The status of a loop is
that of the last body run, or 0 if none ran.
Tests: posix/control

R-CMD-18 break n and continue n (default 1) leave, or go to the next
iteration of, the n-th enclosing loop. An n larger than the depth refers
to the outermost loop.
Tests: posix/control

R-CMD-19 (( expr )) evaluates expr (Section 7). Its status is 0 if the
value is not zero and 1 if it is zero; 2 on an error.
Tests: zash/arith-ext

8.6 Functions

R-CMD-20 Defining a function stores its body; running the definition has
status 0. Calling it runs the body with the positional parameters set to
the call’s arguments, and restores them afterwards. $0 is unchanged.
Tests: posix/functions, posix/func-edge

R-CMD-21 return n ends the function with status n modulo 256 (so return
300 gives 44); return alone uses $?.
Tests: posix/func-edge, zash/ash-differences

R-CMD-22 local NAME and typeset NAME inside a function make NAME local
to that call: its previous value and attributes are restored when the
function returns. Callees see the local value (dynamic scope).
Tests: zash/local, zash/typeset

9 Conditional expressions [[ ]]

    cond_expr    = cond_or ;
    cond_or      = cond_and { '||' cond_and } ;
    cond_and     = cond_not { '&&' cond_not } ;
    cond_not     = '!' cond_not | cond_prim ;
    cond_prim    = '(' cond_expr ')'
                 | UNARY_OP WORD
                 | WORD BINARY_OP WORD
                 | WORD ;
    UNARY_OP     = '-a' | '-b' | '-c' | '-d' | '-e' | '-f' | '-g' | '-G' | '-h'
                 | '-k' | '-L' | '-n' | '-o' | '-O' | '-p' | '-r' | '-s' | '-S'
                 | '-t' | '-u' | '-v' | '-w' | '-x' | '-z' ;
    BINARY_OP    = '=' | '==' | '!=' | '=~' | '<' | '>'
                 | '-eq' | '-ne' | '-lt' | '-le' | '-gt' | '-ge'
                 | '-nt' | '-ot' | '-ef' ;

Newlines are allowed before ]] and after && and ||. Inside [[ ]], <, >,
( and ) are operators, not redirections or subshells.

R-CND-1 The operands of [[ ]] are expanded without field splitting and
without pathname expansion, and only when the evaluation reaches them:
&& and || do not expand an operand they do not need.
Tests: zash/cond

R-CND-2 a = b, a == b and a != b: b is a pattern (Section 6), with its
quoted bytes literal. a =~ b: b is a POSIX extended regular expression,
matched anywhere in a; quoted parts of b are literal; an invalid
expression gives status 2.
Tests: zash/cond

R-CND-3 < and > compare by byte value. -eq and the other numeric
operators evaluate both operands as arithmetic expressions (Section 7).
-o name is true if the option is on; -v name if the variable is set; the
remaining unary operators are those of test. A lone WORD is true if it
is not empty.
Tests: zash/cond

R-CND-4 f1 -nt f2 is true if f1 exists and f2 does not, or both exist
and f1 is newer; -ot is the converse (POSIX.1-2024).
Tests: zash/ash-differences

R-CND-5 The status of [[ e ]] is 0 if e is true, 1 if false, 2 on a
syntax or evaluation error.
Tests: zash/cond

10 Redirection

R-RED-1 Redirections are performed left to right. The descriptor n is
the IO_NUMBER if given, otherwise 0 for <, <>, <&, <<, <<- and 1 for the
others. The target word is expanded as one field (Section 5).

  ------------- ----------------------------------------------------------------------------------
  n<f           open f for reading
  n>f           create or truncate f; an error if set -C is on and f is an existing regular file
  n>|f          as >, ignoring set -C
  n>>f          open f for appending, creating it if it does not exist
  n<>f          open f for reading and writing, creating it if it does not exist
  n<&m, n>&m    make n a copy of descriptor m; - closes n
  n<<d, n<<-d   open the here-document body for reading on descriptor n
  ------------- ----------------------------------------------------------------------------------

Tests: posix/redir, posix/redir-edge

R-RED-2 Descriptors 0 to 9 are available to scripts. A redirection of a
larger descriptor, or a duplication from a descriptor that is not open,
is a redirection error.
Tests: posix/fdmap

R-RED-3 A redirection on a compound command or a function definition
applies to the whole command each time it runs, and is undone after it.
Tests: posix/redir

R-RED-4 exec with only redirections applies them to the current shell
permanently.
Tests: posix/redir

11 Environment and variables

R-ENV-1 A variable has a name, a value (a byte string) and attributes:
exported, read-only, integer. Exported variables are passed in the
environment of commands the shell runs. At startup every environment
entry with a valid name becomes an exported variable.
Tests: posix/vars

R-ENV-2 Assigning to a read-only variable, or unsetting one, is an
error.
Tests: posix/vars

R-ENV-3 Assigning to an integer variable (typeset -i, integer) evaluates
the value as an arithmetic expression and stores the decimal result.
Tests: zash/typeset, zash/let

R-ENV-4 RANDOM yields a pseudo-random integer from 0 to 32767 on each
expansion; assigning to it sets the seed. SECONDS yields the whole
seconds since the shell started, or since it was last assigned plus the
assigned value. Unsetting either removes the special behaviour.
Tests: zash/dynvars

R-ENV-5 A shell started interactively, and not set-user-ID or
set-group-ID, expands ENV by parameter expansion and reads the resulting
file before its first command. A set-ID shell ignores ENV.

R-ENV-6 The options are those of set: -a -b -C -e -f -h -m -n -u -v -x,
and by name allexport errexit ignoreeof monitor noclobber noexec noglob
nolog notify nounset pipefail trackall verbose vi emacs xtrace. notify,
trackall and nolog are accepted and have no effect. The z/OS build adds
jobnames, shareas, msgid and pipetag (Section 14).
Tests: zash/options

12 Errors

R-ERR-1 The consequence of an error depends on its kind and on whether
the shell is interactive:

  ---------------------------------------- ----------------- ------------------------
  error                                    non-interactive   interactive
  syntax error                             exit, status 2    status 2, next command
  special builtin error                    exit              status, next command
  redirection error on a special builtin   exit              status 2
  redirection error on any other command   status 2          status 2
  variable assignment error                exit              status, next command
  expansion error                          exit              status, next command
  command not found                        status 127        status 127
  ---------------------------------------- ----------------- ------------------------

An error that exits the shell runs the EXIT trap first.
Tests: posix/errexit, posix/command-special, posix/invoke

R-ERR-2 (zash) Input that cannot be read. A script named on the command
line that cannot be opened is reported on standard error and the shell
exits at once: 127 if the name does not exist, 126 if it exists but
cannot be opened, including when it is a directory. Once a script, .
file or standard input is being read, a read error is a fatal error
(status 2, after the EXIT trap) and end of input is not.
Tests: zash/script-errors

R-ERR-3 errexit. With set -e, when a pipeline (or a single command)
fails, the shell exits with its status, unless the failing command is:
part of the condition of if, while or until; part of an && or || list
other than the last command; or preceded by !. The exemption extends to
everything executed within those positions, including function bodies.
Tests: posix/errexit, posix/errexit-edge

R-ERR-4 command before a special builtin makes errors inside it
(including errors in evaled or .-read text) set the status instead of
exiting the shell. exit still exits.
Tests: posix/command-special

R-ERR-5 (zash) ERR trap. When a command fails in a position where
errexit would apply, the ERR trap, if set, runs before errexit exits the
shell.
Tests: zash/errtrap

13 Traps and signals

R-SIG-1 trap action sig... sets action to run when a signal arrives. The
action runs after the command being executed completes, not in the
middle of it, and with $? equal to that command’s status; afterwards $?
is restored. An action of - resets to the default, and an empty action
ignores the signal.
Tests: posix/traps, scripts/signals

R-SIG-2 A trap that becomes due while the shell is reading a command
runs before that command and does not disturb the command being read.
Tests: posix/trap-input

R-SIG-3 A subshell resets traps to their defaults, except that ignored
signals stay ignored. Difference: in a pipeline stage or $( ), trap with
no arguments lists the parent shell’s traps until the subshell sets one
of its own.
Tests: posix/subshell-edge

R-SIG-4 The EXIT trap (signal 0) runs when the shell exits, whether by
exit, end of input or a fatal error.
Tests: posix/invoke

14 z/OS

These rules hold only for the z/OS builds. They affect only character
encoding and process creation, not script semantics.

R-ENV-7 (z/OS) The build is ASCII (ISO8859-1) or EBCDIC (IBM-1047),
fixed at compile time. Script text is interpreted in the build’s
character set. An untagged script whose first block looks like the other
character set is converted when it is read.

R-ENV-8 (z/OS) set -o jobnames, shareas, msgid, pipetag and the
variables _TAG_REDIR_IN, _TAG_REDIR_OUT, _TAG_REDIR_ERR, _BPX_SHAREAS,
_BPX_JOBNAME and ZOS_* change process attributes and file tags. They are
specified in DESIGN.md, “The z/OS layer”, not here.

15 Differences from POSIX and other shells

  ---------- -----------------------------------------------------------
  rule       difference
  R-LEX-2    standard input is never read ahead of the running command
  R-LEX-11   $'...' escapes, \cX in ASCII builds only
  R-LEX-12   function, time, [[, ]] are reserved
  R-GRM-3    function form has no ksh-style local traps or $0
  R-GRM-7    heuristic choice between (( and ( (
  R-PAT-2    [^...] negates
  R-PAT-3    ranges and sorting by byte code, not locale
  R-ARI-6    ++, -- and ,
  R-ARI-5    variable values evaluated as expressions, 16 levels deep
  R-CMD-9    last pipeline stage in the current shell
  R-CMD-21   return 300 gives 44
  R-CMD-22   local, typeset with dynamic scope
  R-CND-4    -nt true against a missing file
  R-ERR-5    ERR trap
  R-SIG-3    trap in a subshell lists the parent’s traps
  ---------- -----------------------------------------------------------

Note. The identifiers in this table are looked up from the rules
themselves, so they stay right when rules are added.

16 Mapping to a formal model

Each chapter becomes one Lean module. The first things to formalise:

  ----------------- -----------------------------------------------------------------------------------------------------------------------------------------------------
  chapter           what to formalise first
  Patterns          match as an inductive predicate (R-PAT-4); prove the trimming rule (R-EXP-9) correct for the shortest and longest match
  Arithmetic        the grammar as an inductive type and ⟦e⟧ as a total function into Int64; prove R-ARI-1 (wrapping) and R-ARI-4 (unevaluated operands have no effect)
  Field splitting   R-EXP-15 as a function on flagged bytes; prove that quoted bytes are never split (R-EXP-1)
  Grammar           the productions as an inductive type; the (( rule (R-GRM-7) as a decidable predicate
  Commands          a small-step semantics over an environment; last-stage and subshell isolation as theorems (R-CMD-9, R-CMD-14)
  ----------------- -----------------------------------------------------------------------------------------------------------------------------------------------------

Differential testing then checks the C code against the model, with the
existing suite and random inputs. CBMC checks the smallest pieces.
