v0.2.4

Documentation version

v0.2.4v0.3.2
en

Documentation language

en

Search documentation

ESC

Documentation search

What are you working on?

Find a guide, configuration option, action, or ESH topic.

Browse documentation
DocsLanguage Reference

Language Reference

ESH is a deterministic shell language for project automation. It parses its own source and resolves its own built-ins before invoking an external command. ESH defines the semantics of its language constructs; external commands and operating-system interactions remain host-dependent. Linux is currently the supported platform for local development, CI, and release artifacts. Start with Learn ESH for guided examples; use the ESH Runtime Reference for individual command and keyword contracts.

POSIX foundation and ESH contract

POSIX shell syntax and semantics are the foundation where they fit ESH's embedded automation runtime. The following contract distinguishes adopted behavior, deliberate ESH rules, extensions, and excluded scope. It is normative for ESH; it does not claim full POSIX conformance.

AreaStatusESH contract & rationale
Simple & compound commandsAdopt baselineKeep familiar simple commands, if/elif/else/fi, case, for, while, until, brace groups, subshells, functions, pipelines, and substitutions where practical.
select menu loopESH extensionAdds the familiar numbered menu loop with PS3, REPLY, and standard-input selection. select is not POSIX syntax.
Alias substitutionExcluded by designalias and unalias are excluded so source tokens are never rewritten from mutable definitions; keeps parsing static and inspectable.
Scalar expansionDeliberate divergenceScalar expansions remain a single argument without implicit IFS splitting or pathname expansion. In a for list only, an unquoted standalone command substitution splits on newlines into items (preserving internal spaces and empty interior lines; empty output yields zero items after trailing-newline removal). Quoting preserves one item. Use arrays or glob for multi-argument expansion. Leading unquoted ~ and ~/ expand via HOME; ~user prefixes stay literal.
Command substitutionAdopt POSIX formsSupport both $(command-list) and legacy backticks in words, double quotes, and unquoted here-documents (including escaped nested backticks). Removes trailing newlines while preserving embedded newlines, CRs, and NUL bytes.
Pipelines & negationAdopt & extendSupport | and !; last-stage status by default and pipefail when enabled. Newlines may continue after |, &&, and ||; ESH also allows a newline after ! before the pipeline.
Parallel execution (&|)ESH extension&| is a structured parallel join: branches run concurrently, buffer streams, and commit output and first nonzero status in source order before execution continues.
Async list (&)Excluded by designStandalone & is rejected at lex time to avoid unsupervised background jobs and unclear cancellation/ownership semantics. $! remains literal.
set & shell optionsAdopt subset; define semanticsSupport -a/allexport, -e, -u, -x, -f, -C, pipefail, + disabling, -o/+o listing, $- (fixed aeufxC order), -- positional replacement, and set - (disables xtrace without altering positionals). Bare set does not dump variables. Reject -h, -k, -m, -n, -p, -t, -v, and -1 with status 2.
Prefix assignmentsDeliberate divergenceApplied in source order before expanding command arguments and redirection targets so both observe the same temporary values. Scalars are exported to external commands; arrays stay shell-local. Cleanup restores only prefixed names, letting unrelated builtin effects (e.g., export OTHER=val) persist. Assignment-only commands persist.
POSIX special builtinsDefined subset; no special classCatalog provides ., :, break, continue, exit, export, return, set, shift, trap, and unset. eval, exec, readonly, and times are excluded. Special builtins use ESH's uniform prefix-assignment scoping and return status 2 on usage/context errors (obeying set -e, never triggering POSIX fatal special-builtin aborts).
Other POSIX builtinsPartial coverage; explicit exclusionsProvides cd, command, getopts, hash, pwd, read, wait, type, true, and false. ESH implements true and false as builtins, so they take precedence over same-named executables on PATH. Excludes alias/unalias, bg/fg/jobs, fc, kill, newgrp, ulimit, and umask (process-wide mask mutation would leak across concurrent &| branches); kill and newgrp may still resolve through PATH when host executables are present.
trapLifecycle subsetSupports EXIT (and POSIX alias 0), ESH ERR, and cancellation-driven INT; ERR runs for command failures even in if conditions, non-final &&/`
test / [Expression & file subsetSupports !, -a, -o precedence, quoted ( ... ), decimal integers, Unicode lexical </>, and file/time/mode predicates (-S included). Excludes -t (returns status 2 with descriptor operand; lone test -t is a true nonempty string).
printf & echoAdopt & extendprintf requires a format operand, implements POSIX conversions (including floating-point and %a/%A extensions), repeated formats, and \0ddd raw byte emission in %b, while using locale-independent formatting and Unicode scalar widths for %s/%c. echo defines -n, -e, -E, -f, and -- as ESH extensions.
readAdopt POSIX.1-2024 core; extendSupports IFS splitting, default backslash protection, -r, and -d (including '' for NUL). Defaults to REPLY when no variable is given; preserves target variables on immediate EOF; adds prompt, secret, menu, timeout (-t), and default extensions.
waitNo-job contractReturns 0 with no operands (&| already joins); returns 127 for unknown numeric PIDs; rejects job-ID or malformed operands with status 2.
case & shell patternsAdopt & extendShares ESH's locale-independent pattern engine (*, ?, [...], ranges, ! and ESH ^ negation, ASCII POSIX named classes) with parameter removal. / and leading . are ordinary characters (unlike glob). Supports ;; plus ESH ;& and ;;&.
RedirectionsStandard-stream boundarySupports </0<, >/1>, >|/1>|, >>/1>>, 2>, 2>>, 2>&1, 1>&2, <<, <<-, plus ESH &>, &>>, and <<<. Excludes <>, arbitrary descriptor numbers, and descriptor closure (>&-).
Here-documentsCommon subsetSupports << and <<- tab stripping, delimiter quote removal without delimiter expansion, expansion suppression when any delimiter char is quoted, FIFO multi-doc collection, and backslash/continuation rules.
ParametersAdopt & extendSupports $0–$9, ${10+}, $#, $?, $-, $@/"$@", $*/"$*" (literal-space join regardless of IFS), and :-/-/=/:=/+/:+/?/:?/#/##/%/%%/${#...}. $$ and $! remain literal. Adds arrays, maps, keys (${!NAME[@]}), slicing, and replacement.
Functions & scopesAdopt & extendSupports name() compound-command and ESH function name. Functions isolate positional parameters while preserving $0. local is dynamically scoped across active function frames.
Interactive & job controlOut of scopeNon-interactive script runtime (file or -c); never reads script source from stdin and has no general interactive shell prompt or fg/bg. Script commands such as read and select can consume runtime stdin.

Source and commands

Source is UTF-8. Newlines and ; terminate commands. Carriage returns are whitespace, so CRLF source files run without adding carriage returns to words; Bash POSIX mode retains them as word bytes. An unquoted # starts a comment when it begins a word; inside a word it is literal, as in value#suffix. A command consists of optional assignments, a command name, arguments, and optional redirections. An assignment-only command updates the current shell scope. Prefix assignments before a command are applied before its arguments and redirection targets are expanded, so both see the same temporary values. Scalar values are exported to an external command's environment; array values remain local to ESH. Prefix values are discarded when the command finishes, while assignment-only commands persist in the current shell scope. Other shell changes made by a builtin still take effect, including when its output is redirected; for example, TEMP=value export OTHER=value > /dev/null restores TEMP but keeps OTHER exported. Stateful builtins such as set, shift, and trap keep their own effects while the prefix value is restored. If a prefixed command changes the working directory, PWD and OLDPWD are updated to describe that directory change after the prefix scope is restored. The prefix scope is restored before lifecycle traps run, so TEMP=prefix exit does not make prefix visible to the EXIT handler. export NAME=value assigns an existing name in its current scope; a previously unset name is created in the root shell scope, so that export persists after a function or temporary command scope ends.

Control words such as if, then, for, select, and done keep their literal spelling when they occur as command arguments or redirection targets. Their structural role is determined by the parser's current construct.

Prefix assignments use this same temporary scope for all builtins, including POSIX special-builtin names such as :. ESH does not preserve a : prefix assignment after the command finishes.

MODE=release cargo build --release
echo "finished"; echo "next step"

Single quotes preserve text literally. Double quotes allow variable, command, and arithmetic expansion. A scalar expansion remains one argument; ESH does not perform implicit word splitting or pathname expansion. Use glob when wildcard expansion is intentional.

Command substitution supports $(...) and legacy backticks. It captures standard output, removes trailing newline characters, preserves embedded newlines, trailing carriage returns, and NUL bytes. POSIX leaves command-substitution output containing NUL bytes unspecified; ESH retains them in shell values.

An unquoted ~ or ~/ at the start of a word expands from HOME, including assignment values and redirection targets. The result stays in that word even when HOME contains spaces. If HOME is unset, both forms remain literal. Quoted or escaped tildes and tildes after other text remain literal; prefixes such as ~alice, ~+, and ~- are not expanded. POSIX tilde expansion also defines ~+ and ~- as the current and previous directories; ESH keeps these spellings literal.

Outside quotes, a backslash quotes the next character; backslash-newline is removed as a line continuation. Inside double quotes, backslash quotes $, \, ", and backtick, and backslash-newline is removed. Other backslashes inside double quotes remain literal. Single-quoted text does not interpret backslashes.

This is an intentional shell design choice: spaces and wildcard characters in a scalar value do not silently change the argument list. Use indexed arrays when a value represents multiple arguments, or glob when filesystem matching is intended.

DEST="release build files"
mkdir -p "$DEST"

for FILE in $(glob "./assets/*.svg"); do
  echo "$FILE"
done

Commands, status, and execution

ESH expands the command word before resolving it, then checks shell functions, built-ins and language constructs, and external commands in that order. Prefix assignments do not affect command-word expansion; they are applied before arguments and redirection targets are expanded. External command search uses the current shell value of PATH even when that variable is not exported; exporting controls only whether child processes receive it. Empty PATH components search the current directory, and an unset PATH falls back to the current directory. Built-ins run in-process; an external command is invoked through the host only when no ESH command has that name. An unresolved command returns status 127; a found command that cannot be executed returns 126. Every command returns an integer status: 0 means success and a non-zero value means failure.

ESH does not implement POSIX alias/unalias substitution. Command words are resolved from the parsed script; ESH does not rewrite source tokens using mutable alias definitions.

&& runs its right side only after success. || runs its right side only after failure. The two operators have equal precedence and associate from left to right, matching POSIX shell behavior. $? expands to the latest completed status, including while assignment-only command values are being expanded. An assignment-only command returns the status of its last command substitution in an assignment value, or 0 when none was performed; command substitutions in redirection targets do not affect that status.

ESH extends || for a brace group used directly as its left operand: the group stops at its first failing command, records failure context, and runs the right operand as a fallback. For example, { prepare; build; } || recover skips commands after a failed prepare. POSIX shells normally finish the brace group and choose the right operand from the group's final status.

ESH uses &| for a structured parallel join: all branches run concurrently and ESH waits for their results before continuing. A standalone & background list is not part of the ESH language; scripts should use a join so child work remains supervised by the current execution.

json -v package.json && echo "valid package"
test -f ./config.yaml || exit 1

set -a (allexport) marks subsequent scalar assignments for export to external commands; disabling it with set +a does not remove export attributes already set. ESH arrays remain internal values and are not exported as strings. set -e stops the current failure boundary after an unhandled nonzero result. if and loop-test failures are exempt, including failures inside a function called as one of those tests. A negated pipeline runs its inner command under failure shielding so compound commands and functions can finish; ESH then checks the inverted result against errexit. The final status of an &&/|| expression is also checked, even when a non-final operand failed (for example, false && action stops execution). These rules deliberately use a simpler model than POSIX's contextual exceptions. set -u makes an unset scalar expansion an error, including a read of an unset variable in arithmetic; short-circuited arithmetic operands are not read. Expanding an unset array or map value/key list with [@] produces no items, including in a for list. set -o pipefail makes a pipeline fail when a stage fails. set -x writes an execution trace to standard error. The POSIX special form set - disables xtrace without changing positional parameters. ESH also supports -f (noglob) and -C (noclobber). The POSIX options -h, -k, -m, -n, -p, -t, and -v are unsupported and return status 2 as unknown options: command hashing, keyword assignments, job control, no-execution parsing, privileged mode, one-command execution, and verbose input tracing do not fit ESH's embedded automation runtime. Their corresponding set -o names are unsupported too.

Values and expansion

When $@ is used as a scalar in an assignment or redirection target, ESH joins positional parameters with literal spaces, independent of IFS. A standalone $@ or "$@" command argument expands to multiple arguments. A standalone braced ${@:-word} or ${@-word} also preserves each positional parameter as a separate argument when that operator selects @; otherwise, word contributes one scalar argument. The :- form tests whether the ESH space-joined value is empty, while - tests whether any positional parameter exists. ${@:+word} and ${@+word} produce one scalar argument from word when their set/non-null condition matches and otherwise preserve the current positional list (which can be empty).

Assign scalars with NAME=value, then expand them with $NAME or ${NAME}. In a command word, each scalar expansion contributes text to that word and never creates extra arguments through whitespace splitting or wildcard matching. A standalone $@, "$@", or selected parameter-result form such as "${@:-word}" is an explicit multi-value expansion that contributes one unsplit argument per positional parameter. When $@ is embedded in a larger word, it contributes one space-joined scalar, so surrounding text remains in the same argument. "$*" also contributes one space-joined scalar. Indexed array expansion with "${ARRAY[@]}" likewise contributes one argument per item.

ESH exposes $0 through $9, ${10} and higher braced positional parameters, $#, $@, $*, $?, and $-. Unbraced positional references consume one digit, so $10 means $1 followed by the literal 0. $* joins positional values with a literal space, independent of IFS, and expands as one scalar; it does not undergo field splitting. This differs from POSIX's IFS-dependent "$*" join. $- lists the enabled short option flags in ESH's fixed order: a, e, u, f, x, C; pipefail has no short flag and is omitted. $$ and $! are not expanded; their spellings remain literal because ESH has no separate shell process ID or unstructured background jobs.

ESH also adds braced scalar helpers beyond the POSIX parameter operators. ${NAME:offset[:length]} slices by Unicode character position using non-negative decimal values; an offset past the end yields an empty string, and a length extending past the end stops at the end. Offsets and optional lengths must be non-empty decimal digits; malformed or extra fields are errors. Values beyond the machine integer range saturate and clamp to the end of the value. ${NAME/search/replacement} replaces the first literal substring, while ${NAME//search/replacement} replaces all non-overlapping literal matches. The search and replacement operands expand recursively, then act as literal strings; characters such as * do not become shell patterns, and an empty search string matches nothing. Write \/ in the search text to include a literal slash without ending the search portion.

Functions and sourced files can temporarily replace $1 and later positional parameters; $0 remains the script or command name from invocation. Function calls restore the caller's positional parameters when they return, and . restores the caller's parameters after a source file finishes.

shift [n] removes positional parameters from the front; n defaults to 1 and may be zero. ESH rejects negative, non-numeric, or extra arguments, and rejects a count greater than the number of positional parameters without changing them.

Parameter expansion supports defaults, assignment, alternatives, required values, length, prefix/suffix removal, slicing, and replacement.

${#@} and ${#*} return the number of positional parameters. ${##} returns the character length of the decimal value of $#. With set -u, directly expanding an unset variable or reading it through length, prefix/suffix removal, slicing, or replacement is an unbound-variable error. Default, alternative, assignment, and required-value operators retain their documented unset behavior.

The special count parameter also accepts default, alternate, and required-value operators. For example, ${#-fallback} and ${#:-fallback} expand to the current positional count; they do not mean the length of a variable named -fallback. $# is always set, including when its value is 0, so ${#+word} and ${#:+word} select word, while ${#?message} and ${#:?message} return the count without an error. For @ and *, non-colon operators treat the parameter as unset when there are no positional arguments; a single empty positional argument still counts as set. Colon operators test the ESH space-joined value, so an empty join selects the default or raises the required-value error.

case patterns and parameter prefix/suffix removal use *, ?, bracket lists, ranges, negated lists, and the POSIX named character classes ([:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]). Named classes use ASCII character definitions regardless of host locale; ranges compare Unicode scalar values in code point order. In case, quoted pattern pieces and quoted expansions make metacharacters literal; unquoted expansions can contribute pattern metacharacters. Backslash-escaped metacharacters are literal. A leading ^ also negates a bracket list as an ESH extension; POSIX leaves this form unspecified. POSIX locale collation and equivalence expressions such as [.ch.] and [=e=] are not supported.

FormMeaning
${NAME:-value}Use value when NAME is unset or empty.
${NAME-value}Use value only when NAME is unset; an empty value is retained.
${NAME:=value}Set NAME to value when it is unset or empty, then use it.
${NAME=value}Set NAME to value only when it is unset; an empty value is retained.
${NAME:+value}Use value only when NAME is set and non-empty.
${NAME+value}Use value when NAME is set, including when it is empty.
${NAME:?message}Report an error when NAME is unset or empty.
${NAME?message}Report an error only when NAME is unset.
${#NAME}Length of a scalar.
${NAME#pattern} / ${NAME##pattern}Remove a shortest / longest matching prefix.
${NAME%pattern} / ${NAME%%pattern}Remove a shortest / longest matching suffix.
${NAME:offset:length}Select a slice.

Slice offsets and lengths count Unicode characters. A length greater than the remaining value is clamped to the end of the value.

Parameter modifier operands recursively expand nested modifiers. Quotes inside an operand are removed after controlling expansion, and unquoted backslashes quote the next character.

POSIX leaves pattern removal on the special parameters @ and * unspecified. ESH applies the pattern to each positional parameter. A standalone ${@#pattern}, ${@##pattern}, ${@%pattern}, or ${@%%pattern} keeps one result per positional parameter; when embedded in a larger word, those results join with literal spaces. The corresponding * forms join the individually transformed values with literal spaces into one scalar.

Named variables in parameter modifiers must follow shell identifier syntax. Numeric braced positional parameters such as ${10} are accepted; assignment modifiers (= and :=) require an ordinary variable name.

Command substitution captures command output. Both $(command) and legacy `command` forms are supported in words, double quotes, and unquoted here-document bodies. Arithmetic expansion evaluates a signed 64-bit expression.

PORT="${PORT:-8080}"
VERSION="$(json -g version package.json)"
NEXT=$(( BUILD_NUMBER + 1 ))
echo "$VERSION on $PORT (build $NEXT)"

Arrays and maps

Indexed arrays use parentheses and zero-based indexes. Whitespace, including newlines, separates array items; semicolons are not array-item separators. Indexes may be sparse: assigning an element does not create entries for the missing indexes. ${ARRAY[@]} expands each set value as a separate item; ${#ARRAY[@]} returns the number of set values; ${!ARRAY[@]} expands the set indexes as separate items. Associative maps are declared with declare -A; ${!MAP[@]} expands each map key as a separate item. Keys can be quoted directly or supplied through a scalar expansion, and a key containing spaces remains one key. Map keys iterate in sorted order, and map values follow that same key order.

Prefix and suffix pattern removal on ${ARRAY[@]} or ${MAP[@]} applies to each value and preserves one result per set element, including empty values. A standalone ${ARRAY[*]...} or ${MAP[*]...} joins the individually transformed values with literal spaces into one scalar. Embedded ${...[@]...} expansions also join with literal spaces; ESH does not field-split unquoted expansion results.

Slicing ${ARRAY[@]:offset:length} selects set elements whose indexes are at or after the non-negative offset, then keeps up to length values; sparse holes do not count as elements. Map slices use the sorted value order. Standalone [@] slices preserve each selected value as an argument, while [*] slices join selected values with literal spaces.

unset 'ARRAY[index]' removes one indexed-array element without renumbering the remaining indexes. unset 'MAP[key]' removes one map entry; removing a missing element is a no-op. unset ARRAY removes the entire collection.

TARGETS=("linux" "macos" "windows")
declare -A TRIPLES
TRIPLES[linux]="x86_64-unknown-linux-musl"
TRIPLES[macos]="aarch64-apple-darwin"

for TARGET in "${TARGETS[@]}"; do
  echo "$TARGET: ${TRIPLES[$TARGET]}"
done

Array and map element expansions also accept parameter modifiers, such as ${TRIPLES[windows]:-not-configured}.

Arithmetic and tests

Arithmetic uses signed 64-bit integers. It supports decimal, POSIX leading-zero octal, hexadecimal (0x), and ESH binary (0b) and explicit octal (0o) literals; arithmetic, comparison, bitwise, logical, assignment, increment/decrement, and conditional operators. ESH adds ** exponentiation; it is right-associative, and unary operators bind before it (-2 ** 2 evaluates to 4). A negative exponent evaluates to 0 in the integer model. The signed minimum can be written as a negated magnitude, such as -9223372036854775808; that magnitude by itself is out of range. A variable value may itself contain an arithmetic expression and is evaluated recursively, using the same radix rules as literals in the expression; a circular variable reference is an error. Unset and empty variables evaluate to zero unless set -u is enabled, in which case reading an unset variable is an error while an empty value remains zero. An invalid leading-zero octal such as 08 is rejected. Arithmetic expressions reject malformed tokens and incomplete input; division or remainder by zero is an error. Shift counts must be in the range 0 through 63; negative and wider counts are errors. Right-shifting a negative value sign-extends it (for example, -7 >> 1 is -4), defining ESH's result where POSIX permits implementation-dependent behavior. &&, ||, and ?: evaluate only the selected operand or branch. Integer overflow wraps to the signed 64-bit range, including the INT64_MIN / -1 case.

COUNT=3
TOTAL=$(( COUNT * 10 + 5 ))

if test "$TOTAL" -gt 30; then
  echo "large build"
fi

Use test or its [ alias for filesystem, string, and numeric conditions. The Runtime Reference defines the exact command forms and statuses.

Control flow and functions

if, for, while, until, and case are language keywords. A for loop variable and function name must be shell identifiers: an ASCII letter or underscore followed by ASCII letters, digits, or underscores. A for NAME in ... loop leaves NAME unchanged when the expanded list is empty; otherwise it retains the final item after the loop. Each listed word expands to one item, except an unquoted standalone command substitution, whose output is split at newline boundaries into loop items. This line-list form preserves spaces within each line, treats embedded blank lines as empty items, and does not use IFS; command substitution's normal trailing-newline removal still applies. If the substitution produces no output, the loop has no items. Quote the substitution to keep its entire output as one item. break [n] and continue [n] accept one positive decimal loop level; a level greater than the number of active loops is limited to the active nesting depth. Missing levels default to 1; zero, non-numeric values, and extra arguments are errors, and using either command outside a loop is an error. ESH extends POSIX shell behavior by allowing a function called from inside a loop to break or continue that caller's active loop; in POSIX mode, Bash does not let loop-control commands inside a function affect the caller's loop. . executes a file in the current shell context. return [status] ends a function or the currently sourced file and is an error outside both. When status is omitted, return uses the last command's status. exit [status] ends the script or a subshell; without status, it exits with the last command's status. exit and return accept at most one integer status from 0 through 255; malformed, out-of-range, or extra arguments are errors.

An if/elif/while/until condition and every if branch or loop body must contain a command. Commands must be separated by a newline or ; before a compound command's closing keyword. Empty brace groups, including groups with only newlines between the braces, are allowed; an empty subshell is not. This also lets ESH define a no-op function as noop() {}. Bash POSIX mode accepts an adjacent empty brace group {} but rejects the multiline empty group and empty function body. A case with no arms and a case arm with no commands are allowed.

case matches shell patterns with the locale-independent rules described under parameter expansion. POSIX ;; ends the case; ESH ;& runs the next arm's body without testing its patterns, while ESH ;;& resumes pattern matching at the next arm. Prefix and suffix removal use the shortest or longest matching portion, as selected by #/## and %/%%.

classify() {
  case "$1" in
    *.zip)
      echo "zip"
      ;;
    *.tar.gz)
      echo "tarball"
      ;;
    *)
      return 1
      ;;
  esac
}

for FILE in "$@"; do
  classify "$FILE" || echo "unknown: $FILE" >&2
done

Functions may use local for function-scoped values; an unassigned local NAME starts as an empty string, and calling local outside a function is an error. Local lookup is dynamic: a called function can read and update the nearest matching local in its caller's active function frames. Popping the caller's function scope restores any shadowed outer value. POSIX-style name() compound-command definitions accept brace groups, subshells, conditionals, loops, and case commands as their body. ESH also accepts the extension function name { ... }. Parenthesized blocks run as subshells; brace blocks preserve the surrounding execution context.

Pipelines and redirection

| connects commands as a pipeline. Redirections attach to simple commands and compound commands, including brace groups, subshells, conditionals, loops, and case: > (or 1>) replaces standard output, >> (or 1>>) appends it, < (or 0<) reads standard input, and 2> redirects standard error. Expanded redirection targets remain one path, preserving spaces and wildcard characters; names such as 1, 2, &1, and &2 are ordinary filenames. Descriptor duplication uses the dedicated operators 1>&2 and 2>&1. 1>| explicitly forces an overwrite when noclobber is enabled. >&2 (or 1>&2) sends standard output to standard error, and 2>&1 duplicates the current standard output destination for standard error. With set -C, > refuses to overwrite an existing file; >| explicitly forces the overwrite. Redirections apply from left to right, so 2>&1 >out.txt sends standard error to the original standard output while standard output goes to the file. ESH routes only standard input, output, and error; <>, descriptor numbers beyond 0, 1, and 2, and descriptor closure are unsupported and rejected. &> and &>> are ESH extensions that send both streams to one target. <<< expands one word as a here string, keeps spaces and wildcard characters as data, and appends one newline to the expanded value. << reads a here-document through a line matching its delimiter; quoting any part of the delimiter disables body expansion. ESH accepts the closing delimiter at end-of-file even when the final delimiter line has no newline. Unquoted bodies expand parameters, command substitutions, and arithmetic expressions while preserving UTF-8 literal text; expanded values are not field-split or pathname-expanded. In unquoted bodies, backslash quotes $, backtick, and backslash, and backslash-newline is removed. <<- also removes leading tabs from body and delimiter lines. Multiple here-documents are read in source order. With CRLF source lines, ESH ignores the carriage return when recognizing a delimiter and preserves carriage returns in the body. ESH treats /dev/null as its null sink in script redirections.

echo "Line 1" > output.txt
echo "Line 2" >> output.txt
read -r FIRST SECOND <<< "alpha beta"
echo "$FIRST / $SECOND" 2> errors.log

Reaching end-of-file before a here-document delimiter is a syntax error in ESH, so an incomplete here-document does not execute.

Without pipefail, a pipeline reports the final command status. With set -o pipefail, it reports the status of the rightmost failed stage, or 0 when every stage succeeds, matching Bash's pipefail behavior.

Prefix a pipeline with ! to invert its status. ESH permits a newline between ! and the pipeline as an ESH continuation extension.

Each multi-command pipeline stage runs with isolated shell state. After the pipeline, ESH adopts the final stage's shell variable values and export attributes. This differs from the POSIX default, where pipeline-stage variable changes do not reach the parent shell. Changes from earlier ESH stages do not reach the caller, and stage-local function definitions, positional parameters, options, current-directory changes, and trap registrations remain isolated.

Parallel joins

&| starts independent pipelines concurrently and joins their result. Pipelines (including a leading !) form each branch; &| binds more tightly than && and ||, which associate left to right. This means a short-circuited && or || skips the entire parallel join on its right. Use &| only when the branches do not depend on each other’s output, files, or mutable state.

cargo fmt --check &| \
cargo clippy --all-targets -- -D warnings &| \
cargo test

The joined expression returns the first non-zero branch status in source order, or zero if every branch succeeds. ESH buffers branch output and emits it in source order after all branches finish. The result can be handled with ||. On failure, ESH records contextual telemetry including ESH_FAILED_CMD, ESH_FAILED_LINE, and, when available, ESH_FAILED_MSG.

&| is ESH syntax, not POSIX asynchronous-list syntax. It always joins its branches; it does not return a background process identifier.

Traps and diagnostics

trap registers a command or block for lifecycle and failure events. Use EXIT to clean up owned temporary state and ERR to add context around a failing path.

TEMP="$(mktemp -d)"
trap "rm -rf '$TEMP'" EXIT
trap 'echo "failed: $ESH_FAILED_CMD" >&2' ERR

ESH diagnostics preserve the failing command, line, and status. The variables are contextual values for error handling; do not use them as a substitute for handling expected non-zero statuses with if, &&, or ||.

CLI and language-server interface

CommandPurpose
esh file.esh [args...]Execute a script with positional arguments.
esh -c 'script' [name [args...]]Execute an inline script; name becomes $0 and following values become positional arguments.
esh --dry-run file.eshParse a file and print its execution plan without side effects.
esh help commandPrint the command or keyword documentation from the runtime catalog.
esh lspRun the embedded language server over JSON-RPC stdio.

The language server provides diagnostics, semantic tokens, completion, hover documentation, and symbols. Follow the IDE integration guide to connect an editor.

ESH starts scripts from a file or -c; it does not read shell source from standard input, start an interactive command loop, or provide job control. Standard input remains available to script commands such as read. With -c, omitting name leaves $0 as esh; with a name, the remaining operands become $1, $2, and so on.

Next: browse runtime commands and keywords or return to the ESH Reference.

For the precise accepted grammar and operator behavior, consult the source parser and language tests in this repository; changes to this page must preserve that implementation contract.

Page source: reference/esh/90.language-reference.3000.md