zashThe Shell LanguageSpecificationDraft 1Describes zash at commit b4d7dc3 with the audit fixes appliedNovember 20, 2026zash 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.Sean Kurtz · BSD 2-Clause LicenseContents1Introduction .................................................................................................... ⁠21.1Scope ....................................................................................................... ⁠21.2Notation .................................................................................................... ⁠21.3Rule identifiers ............................................................................................. ⁠22Lexical structure ............................................................................................... ⁠32.1Input ....................................................................................................... ⁠32.2Tokens ...................................................................................................... ⁠32.3Quoting .................................................................................................... ⁠32.4Reserved words ............................................................................................ ⁠42.5Here-documents ........................................................................................... ⁠43Aliases .......................................................................................................... ⁠64Grammar ....................................................................................................... ⁠74.1Productions ................................................................................................ ⁠74.2Rules attached to the grammar ............................................................................ ⁠85Word expansion ............................................................................................... ⁠105.1Words and fields .......................................................................................... ⁠105.2Tilde expansion ........................................................................................... ⁠105.3Parameter expansion ..................................................................................... ⁠105.4Command substitution ................................................................................... ⁠125.5Arithmetic expansion .................................................................................... ⁠125.6Field splitting ............................................................................................. ⁠125.7Pathname expansion ..................................................................................... ⁠126Patterns ........................................................................................................ ⁠147Arithmetic ..................................................................................................... ⁠157.1Syntax ..................................................................................................... ⁠157.2Values ..................................................................................................... ⁠158Commands .................................................................................................... ⁠178.1Exit status ................................................................................................. ⁠178.2Simple commands ........................................................................................ ⁠178.3Pipelines .................................................................................................. ⁠178.4Lists ....................................................................................................... ⁠188.5Compound commands ................................................................................... ⁠188.6Functions ................................................................................................. ⁠199Conditional expressions [[ ]] .............................................................................. ⁠2010Redirection .................................................................................................... ⁠2111Environment and variables ................................................................................... ⁠2212Errors .......................................................................................................... ⁠2313Traps and signals ............................................................................................. ⁠2414z/OS ........................................................................................................... ⁠2515Differences from POSIX and other shells .................................................................... ⁠2616Mapping to a formal model ................................................................................... ⁠2611IntroductionThis 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.1.1ScopeIn 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.2Notation•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.•⟦𝑒⟧ is the meaning of the phrase 𝑒: 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 implemen­tation or by a test before the rule it belongs to is final.1.3Rule identifiersRules 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.22Lexical structure2.1InputR-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-scriptR-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.2TokensThe 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:      &   &&   (   )   ;   ;;   |   ||   NEWLINEredirection:  <   >   >|   >>   <>   <&   >&   <<   <<-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/fdmapR-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.3QuotingQuoting 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 continu­ation, above).Tests: posix/quoting3R-LEX-9 Single quotes. '...' makes every byte up to the next ' literal and quoted. A single quote cannot occur inside.Tests: posix/quotingR-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-wordR-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 \vthe control character so named (\e is escape)\\ \' \" \?the character itself\ooothe byte with octal value ooo (one to three digits)\xhhthe byte with hexadecimal value hh (one or two digits)\cXcontrol-X, in ASCII builds onlyany other escapekept 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.asciiOpen. 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.4Reserved wordsR-LEX-12 The reserved words are!  {  }  case  do  done  elif  else  esac  fi  for  function  if  inthen  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, time, [[ and ]] are reserved in zash, so no command can be named function.Tests: posix/syntax, zash/function-kw, zash/cond2.5Here-documentsR-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-edge4R-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-edgeR-LEX-15 With <<-, leading tab characters are removed from each body line and from the delimiter line before the comparison.Tests: posix/heredocR-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-fuzzR-LEX-17 End of input before the delimiter line ends the body without error.Tests: posix/heredoc53AliasesR-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/aliasR-ALI-2 If an alias’s value ends in a blank, the next word is also checked for alias substitution.Tests: zash/aliasR-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-cycleR-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.64Grammar4.1Productionsprogram        = 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' 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 ;7redir_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.2Rules attached to the grammarR-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 and cond_command. A program that the grammar does not derive is a syntax error (Section 12).Tests: posix/syntaxR-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/syntaxR-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-kwR-GRM-4 In a case_clause, the last case_item may omit ;; before esac. There is no fall-through operator.Tests: posix/case-edgeR-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 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-edge8Note. 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-7 $(( always begins arithmetic expansion. Write $( ( for a command substitution that begins with a subshell.Tests: posix/cmdsub95Word expansion5.1Words and fieldsA 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 𝐵 be the set of bytes and 𝑄=𝐵×{0,1} the set of flagged bytes. A field is a finite sequence in 𝑄∗, and⟦𝑤⟧:Word→(Field)∗is computed in the four steps below. Quote removal is the projection 𝜋1 from 𝑄∗ to 𝐵∗ applied to every resulting field.R-EXP-1 Order. For each word, the shell performs1.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/edgeR-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-edge5.2Tilde expansionR-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-wordR-EXP-4 In an assignment word, tilde expansion is also performed after each unquoted : in the value.Tests: posix/miscR-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-word5.3Parameter expansionR-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/params10R-EXP-7 The conditional forms, for a parameter 𝑥 and a word 𝑤, yield:form𝑥 set, non-empty𝑥 set, empty𝑥 unset${x:-w}𝑥⟦𝑤⟧⟦𝑤⟧${x-w}𝑥empty⟦𝑤⟧${x:=w}𝑥assign ⟦𝑤⟧assign ⟦𝑤⟧${x=w}𝑥emptyassign ⟦𝑤⟧${x:?w}𝑥errorerror${x?w}𝑥emptyerror${x:+w}⟦𝑤⟧emptyempty${x+w}⟦𝑤⟧⟦𝑤⟧emptyassign sets 𝑥 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 ⟦𝑤⟧, or a default message if 𝑤 is empty, and is an expansion error (Section 12). The word 𝑤 is expanded only when its value is used.Tests: posix/params, posix/expand-edgeR-EXP-8 ${#x} is the length of the value of 𝑥 in bytes, as a decimal number. ${#*} and ${#@} are the number of positional parameters.Tests: posix/paramsR-EXP-9 Trimming. For a pattern 𝑝 (the word, expanded, with its quoted bytes literal):•${x#p} removes the shortest prefix of 𝑥 that 𝑝 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.Tests: posix/params, zash/trim-longNote. 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-differencesR-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/split11Open. 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.4Command substitutionR-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/cmdsubR-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-fileNote. 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.5Arithmetic expansionR-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/arith5.6Field splittingLet 𝐼 be the value of IFS (if unset, space, tab and newline). Bytes of 𝐼 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 𝐼 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/splitR-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/split5.7Pathname expansionR-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 12beginning 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-edgeR-EXP-18 With set -f, pathname expansion is not performed.Tests: posix/glob136PatternsR-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-edgeR-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 𝑎 and 𝑏 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/charsetR-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.asciiR-PAT-4 For a pattern 𝑝 and a string 𝑠, match(𝑝,𝑠) holds when 𝑝 matches the whole of 𝑠. It is defined by:match(𝜀,𝑠)⟺𝑠=𝜀match(∗𝑝′,𝑠)⟺∃𝑖.match(𝑝′,𝑠[𝑖..])match(𝑒𝑝′,𝑐𝑠′)⟺𝑒matches𝑐∧match(𝑝′,𝑠′)where 𝑒 is ?, a bracket expression or a literal byte.147Arithmetic7.1Syntaxexpr     = 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.2ValuesR-ARI-1 Values are 64-bit two’s-complement integers. Every operation is computed modulo 264 and the result is taken as signed: overflow wraps and is not an error. In particular⟦𝑎+𝑏⟧=signed((⟦𝑎⟧+⟦𝑏⟧)mod264)and likewise for -, *, unary - and <<.Tests: posix/arith, posix/arith-edgeR-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-edgeR-ARI-3 Shift counts are taken modulo 64. >> is an arithmetic shift.Tests: posix/arith-edgeR-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/arith15R-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-differencesR-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-extR-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-edge168Commands8.1Exit statusR-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+𝑛 if it was ended by signal 𝑛; 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/execfail8.2Simple commandsR-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/redirR-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-builtinsR-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/libraryR-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/functionsR-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-special8.3PipelinesR-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 17on, in which case it is that of the last command that failed, or 0.Tests: posix/pipesR-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/pipesR-CMD-10 ! pipeline has status 0 if the pipeline’s status is not 0, and 1 otherwise.Tests: posix/controlR-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-options8.4ListsR-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/controlR-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/jobs8.5Compound commandsR-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-edgeR-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-setR-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-edgeR-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/control18R-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/controlR-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-ext8.6FunctionsR-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-edgeR-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-differencesR-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/typeset199Conditional 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/condR-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/condR-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/condR-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-differencesR-CND-5 The status of [[ e ]] is 0 if e is true, 1 if false, 2 on a syntax or evaluation error.Tests: zash/cond2010RedirectionR-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<fopen f for readingn>fcreate or truncate f; an error if set -C is on and f is an existing regular filen>|fas >, ignoring set -Cn>>fopen f for appending, creating it if it does not existn<>fopen f for reading and writing, creating it if it does not existn<&m, n>&mmake n a copy of descriptor m; - closes nn<<d, n<<-dopen the here-document body for reading on descriptor nTests: posix/redir, posix/redir-edgeR-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/fdmapR-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/redirR-RED-4 exec with only redirections applies them to the current shell permanently.Tests: posix/redir2111Environment and variablesR-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/varsR-ENV-2 Assigning to a read-only variable, or unsetting one, is an error.Tests: posix/varsR-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/letR-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/dynvarsR-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/options2212ErrorsR-ERR-1 The consequence of an error depends on its kind and on whether the shell is interactive:errornon-interactiveinteractivesyntax errorexit, status 2status 2, next commandspecial builtin errorexitstatus, next commandredirection error on a special builtinexitstatus 2redirection error on any other commandstatus 2status 2variable assignment errorexitstatus, next commandexpansion errorexitstatus, next commandcommand not foundstatus 127status 127An error that exits the shell runs the EXIT trap first.Tests: posix/errexit, posix/command-special, posix/invokeR-ERR-2 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-edgeR-ERR-3 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-specialR-ERR-4 (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/errtrap2313Traps and signalsR-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/signalsR-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-inputR-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-edgeR-SIG-4 The EXIT trap (signal 0) runs when the shell exits, whether by exit, end of input or a fatal error.Tests: posix/invoke2414z/OSThese 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 attrib­utes and file tags. They are specified in DESIGN.md, “The z/OS layer”, not here.2515Differences from POSIX and other shellsruledifferenceR-LEX-2standard input is never read ahead of the running commandR-LEX-11$'...' escapes, \cX in ASCII builds onlyR-LEX-12function, time, [[, ]] are reservedR-GRM-3function form has no ksh-style local traps or $0R-GRM-6heuristic choice between (( and ( (R-PAT-2[^...] negatesR-PAT-3ranges and sorting by byte code, not localeR-ARI-6++, -- and ,R-ARI-5variable values evaluated as expressions, 16 levels deepR-CMD-9last pipeline stage in the current shellR-CMD-21return 300 gives 44R-CMD-22local, typeset with dynamic scopeR-CND-4-nt true against a missing fileR-ERR-4ERR trapR-SIG-3trap in a subshell lists the parent’s trapsNote. The identifiers in this table are looked up from the rules themselves, so they stay right when rules are added.16Mapping to a formal modelEach chapter becomes one Lean module. The first things to formalise:chapterwhat to formalise firstPatternsmatch as an inductive predicate (R-PAT-4); prove the trimming rule (R-EXP-9) correct for the shortest and longest matchArithmeticthe grammar as an inductive type and ⟦𝑒⟧ as a total function into Int64; prove R-ARI-1 (wrapping) and R-ARI-4 (unevaluated operands have no effect)Field splittingR-EXP-15 as a function on flagged bytes; prove that quoted bytes are never split (R-EXP-1)Grammarthe productions as an inductive type; the (( rule (R-GRM-6) as a decidable predicateCommandsa 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.26