v0.3.2

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
DocsRuntime Reference

Runtime Reference

ESH bundles in-process commands and control-flow keywords directly into its runtime. ESH defines their syntax, behavior, and exit codes; filesystem and process interactions still depend on the host. Start with Learn ESH for guided examples and use the ESH Language Reference for syntax, execution, and error semantics.

Find a runtime capability

Use this page when you need an exact synopsis, option, example, handler, or exit status. Commands are grouped by filesystem paths, text, data, archives, cryptography, networking, time, system information, and flow control. The final section defines language keywords such as if, for, case, and function.

1. Filesystem & Path Utilities

command Run or locate a command without invoking an ESH function

Searches ESH builtins and the current shell value of PATH without calling an ESH function of the same name. PATH controls shell lookup even when it is not exported to child processes. Empty PATH components and an unset PATH resolve bare names from ESH's current directory. -v prints a command name or executable path; -V prints a short description. On Unix, -p searches /usr/bin:/bin; on Windows it uses the current PATH. Relative paths and relative PATH entries resolve from ESH's current directory. -- ends option parsing. Query forms recognize reserved words, functions, builtins, and external commands; -V uses ESH's descriptions. ESH has no aliases or hashed-command table.

Exit Status

  • Invoked command: Its exit status.

  • 0: Query succeeded, or no command operand was supplied.

  • 1: One or more queried names were not found.

  • 2: Conflicting -v and -V options.

  • 126: Command was found but is not executable.

  • 127: Command was not found.

type Describe how names resolve as commands

Reports each name as a reserved word, shell function, ESH builtin, or executable found through the shell's current PATH. PATH assignments need not be exported. Unknown names are diagnosed on standard error; ESH has no aliases to report. Output descriptions use ESH's format because POSIX leaves their exact wording unspecified. With no operands, type succeeds without output.

cd Change current working directory

Changes the current working directory of the ESH execution context. If no directory is provided, defaults to a nonempty shell $HOME value (or a nonempty %USERPROFILE% value on Windows). If neither variable has a nonempty value, it stays in the execution context's current directory. A successful change updates and exports $PWD and $OLDPWD. cd - changes to $OLDPWD, prints the resulting directory, and updates both variables so repeated uses toggle between the previous locations. -- ends option parsing so paths that begin with - can be used as operands; cd -- - treats - as a literal directory name instead of the OLDPWD shortcut. With no operand after it, cd -- changes to $HOME. An empty directory operand writes a diagnostic and returns nonzero. Relative names without a slash search the colon-separated $CDPATH entries in order, then resolve from ESH's current directory. A successful search through a non-empty $CDPATH entry prints the resulting directory. By default, -L keeps a logical path in $PWD, resolving . and .. before physical traversal. -P uses the canonical physical path. If both are specified, the last option wins.

Options

  • -: Change to the previous working directory ($OLDPWD).

  • -L: Resolve . and .. logically and preserve the resulting logical path in $PWD (default).

  • -P: Use the canonical physical path.

  • --: End option parsing; this is supported for predictable leading-hyphen paths.

Examples

cd ./src
cd -

Exit Status

  • 0: Directory changed successfully.

  • 1: Target directory does not exist or permission denied.

pwd Print current working directory

Prints the current directory. -L (the default) prints $PWD when it is an absolute path with no . or .. components that resolves to the current directory; otherwise it falls back to the canonical path. -P always prints the canonical path. The options may be clustered or repeated, with the last -L or -P taking effect. -- ends option parsing; operands after it are unsupported and return status 2.

Exit Status

  • 0: Success.

mkdir Create directories

Creates one or more directories, continuing after an operand fails and returning status 1 if any creation fails. -p may be grouped (-pp); -- ends option parsing so a directory name can begin with -. -m accepts octal modes and symbolic clauses with explicit u, g, o, or a selectors, r, w, x, X, s, or t permissions, and u/g/o permission copies. Permission copies use the current mode as each clause is processed. The symbolic mode starts from a=rwx; an omitted selector remains unsupported because ESH does not expose the caller process umask as shell state. Explicit octal and symbolic modes are applied to the newly created final directory, overriding the process umask; a CLI regression verifies this under umask 077. Since the target is a directory, X selects execute permission. s sets the selected user/group special bits, while a+t or o+t sets the sticky bit. ESH accepts u+t and g+t as no-ops; POSIX leaves the meaning of t with those selectors unspecified. With -p, new intermediate directories use the umask-adjusted default mode plus owner write/search (u+wx), and inherited set-ID or sticky bits are cleared; -m applies only to the final directory. An already-existing directory is left unchanged. Unsupported options and invalid modes return status 2.

Options

  • -p: Create intermediate parent directories as needed without erroring if target exists.

  • -m mode: Set the mode of newly-created final directories using octal digits from 0 through 7777, or symbolic clauses with explicit u, g, o, or a selectors. Symbolic permissions support r, w, x, X, s, t, and permission copies from u, g, or o. Omitted selectors are unsupported.

  • --: End option parsing.

Examples

mkdir -p ./dist/bin

Exit Status

  • 0: All directories created.

  • 1: Creation failed or permission denied.

  • 2: Unsupported option.

rm Remove files or directories

Removes files or directories from the filesystem. A symbolic link operand is removed as a directory entry without following its target. A trailing slash forces directory resolution; with -r, ESH removes the resolved directory's contents, then reports failure if the link entry itself cannot be removed. -f suppresses errors for missing operands but does not suppress other removal errors. Processing continues after an operand fails, and the final status is 1 if any operand could not be removed. Final . and .. components and paths resolving to the filesystem root are refused.

Interactive confirmation (-i) is not supported because rm is intended for unattended workflows; the option returns status 2 and leaves operands untouched.

Options

  • -r, -R, --recursive: Recursively remove directory trees.

  • -f, --force: Ignore missing operands and paths. Other errors still produce diagnostics and failure status.

  • --: End option parsing so paths beginning with - can be named. Short options may be grouped, for example -rf.

Unsupported options return status 2. Without recursive mode, a directory operand is an error, even with -f.

Examples

rm -rf ./target/tmp

Exit Status

  • 0: Success.

  • 1: One or more operands could not be removed, including a missing path without -f, a directory without recursive mode, or a refused unsafe path.

  • 2: Unsupported option.

cp Copy files and directories

Copies files or directories from each source to the destination. Multiple sources require an existing destination directory; when the destination is a directory, each source is copied under its basename. Recursive copies preserve symbolic links as links by default and reject copying a directory into itself. The -H, -L, and -P modes select which source links are followed, with the last selected mode taking effect; -L detects directory-link cycles. With -p, ESH preserves access and modification times and permission bits, including symlink timestamps when links are copied as links; owner and group preservation is best effort. ESH continues through source failures and returns status 1 if any copy fails. Unsupported options return status 2. Interactive -i is unsupported. -f retries a failed destination open after removing the existing destination entry.

Options

  • -r, -R, --recursive: Recursive copy for directory trees.

  • -H, --dereference-command-line: Follow command-line source links only.

  • -L, --dereference: Follow all source links during traversal.

  • -P, --no-dereference: Preserve source links as links.

  • -p, --preserve: Preserve access/modification times and permissions; owner and group preservation is best effort.

  • -f, --force: If opening a destination fails, remove that destination entry and retry the copy.

  • --: End option parsing so leading-hyphen paths can be used.

Exit Status

  • 0: Files copied successfully.

  • 1: Missing operands, a non-directory destination for multiple sources, or one or more copy failures.

  • 2: Unsupported option.

mv Move or rename files and directories

Moves or renames files and directories. Multiple sources require an existing destination directory. -- ends option parsing so leading-hyphen paths can be used. -f is accepted; ESH does not prompt before replacing destinations. Unsupported options return status 2. ESH uses filesystem rename when possible; for cross-filesystem moves it copies files, directory trees, and symbolic links, preserves permissions and timestamps, then removes the source. Owner and group preservation is best effort. Processing continues after a source fails, with final status 1 if any move fails. Interactive -i is unsupported because ESH scripts do not have an interactive prompt mode.

Exit Status

  • 0: Move completed successfully.

  • 1: Missing operand, invalid multiple-source destination, or one or more moves failed.

  • 2: Unsupported option.

touch Update timestamps or create empty files

Updates file access and modification timestamps without changing existing file contents. With no time-selection option, both timestamps are updated; -a selects access time and -m selects modification time. If a selected file does not exist, an empty file is created unless -c is given. -- ends option parsing. -r reference uses the reference file's access and modification times; combine it with -a or -m to select one timestamp. -t time accepts the POSIX [[CC]YY]MMDDhhmm[.SS] form, interpreted in the runtime's local timezone. -d date_time accepts the POSIX YYYY-MM-DDThh:mm:SS[.frac][Z] form, also allowing a space instead of T and a comma instead of a period before the fraction. Fractions are truncated to nanosecond precision. Nonexistent and ambiguous local times are rejected. ESH does not apply shell-local TZ assignments to local-time conversion. It continues through all operands and returns status 1 if any operation fails; unsupported options return status 2.

Exit Status

  • 0: Success.

  • 1: One or more files could not be touched, or no file operand was given.

  • 2: Unsupported option.

stat Display file status and metadata

Queries filesystem metadata for the specified path, including size, permissions, file type, and timestamps.

Exit Status

  • 0: Metadata retrieved successfully.

  • 1: Target does not exist.

mktemp Create a secure temporary file or directory

Creates a cryptographically randomized temporary file or directory.

Options

  • -d, --directory: Create a temporary directory instead of a file.

  • -p <dir>: Base directory for temporary creation.

Exit Status

  • 0: Temporary path created and emitted to standard output.

  • 1: Creation failed.

basename Extract filename component of a path

Extracts trailing filename components from paths. With no options, one path and an optional suffix are accepted. -a processes every path operand; -s suffix strips that suffix and also enables multiple operands. -- ends option parsing for names beginning with -. Trailing slashes are removed before extraction; an operand consisting only of slashes produces /. For the implementation-defined operand //, ESH also produces /. Missing -s values, unknown options, and excess operands without multiple mode return status 2.

Examples

NAME="$(basename ./src/main.rs)"      # "main.rs"
STEM="$(basename ./src/main.rs .rs)"  # "main"
basename -a src/one.rs src/two.rs     # "one.rs" and "two.rs"
basename -s .rs src/one.rs src/two.rs # "one" and "two"

Exit Status

  • 0: Success.

dirname Extract directory component of a path

Extracts the parent directory path from a file path. -- ends option parsing for names beginning with -. Trailing slashes are removed; a path with no remaining directory separator produces .. An operand consisting only of slashes produces /. For the implementation-defined operand //, ESH produces /.

Exit Status

  • 0: Success.

realpath Resolve absolute canonical path

Resolves symlinks and relative segments (. and ..) and prints canonical absolute paths. ESH defaults to -e, which requires the resolved path to exist. POSIX -e selects that behavior; -E permits a missing final component when its resolved parent directory exists. If the final component is a symlink to a missing target, -E resolves and prints the target path when its parent exists. When both -e and -E appear, the last option wins. Resolution errors return status 1 and do not suppress later operands; -q hides their diagnostics but preserves the failure status. --relative-to directory prints paths relative to an existing directory and is an ESH extension. Multiple path operands and -- are also supported.

Exit Status

  • 0: All paths resolved.

  • 1: A path or relative base could not be resolved.

  • 2: Unsupported option or missing --relative-to argument.

path Multi-functional path inspection & manipulation

Provides path inspection, resolution, and joining through the host path library. ESH presents paths with / separators in script output.

Options

  • -d, --dirname <path>: Extract parent directory.

  • -b, --basename <path>: Extract last path component.

  • -e, --ext <path>: Extract extension without dot.

  • -s, --stem <path>: Extract filename without extension.

  • -a, --abs <path>: Resolve absolute canonical path.

  • -r, --rel <target> [base]: Compute relative path from base (default: $PWD).

  • -j, --join <parts...>: Join components using host path rules; print the result with / separators.

  • --exists <path>: Test if path exists (exit 0/1).

  • --is-dir <path>: Test if path is a directory (exit 0/1).

  • --is-file <path>: Test if path is a regular file (exit 0/1).

Exit Status

  • 0: Operation succeeded / Condition True.

  • 1: Operation failed / Condition False.

glob Expand filesystem glob patterns

Explicitly expands wildcard patterns against the filesystem. Results from all patterns form a deduplicated union, sorted lexicographically. A pathname component beginning with . matches only when the corresponding pattern component begins with a literal .; wildcard and bracket expressions such as * and [.] do not match a leading period. Unmatched patterns produce no result and the command returns status 1; POSIX shell pathname expansion instead leaves an unmatched pattern literal by default.

Exit Status

  • 0: One or more matches found.

  • 1: No matches found.


2. Text Processing & Inspection

cat Concatenate and print files

Reads files sequentially and writes their contents to standard output. With no operands, or for an operand -, it reads standard input; repeated - operands consume the buffered input only once. A file read error is diagnosed and does not prevent later operands from being processed; the final status is nonzero if any read failed. -u requests unbuffered output and is accepted as a no-op because ESH writes each builtin result directly. -- ends option parsing so a leading-hyphen filename can be read; unsupported options return status 2.

Exit Status

  • 0: All files read successfully.

  • 1: Read error or file not found.

head Output first part of files

Outputs the first N lines (default: 10) or bytes of each input. -n uses the POSIX line-count option; ESH also accepts zero and emits no data, although POSIX requires applications to supply a positive count. -c byte counting is an ESH extension. Line mode preserves original bytes and newline termination. The two count modes cannot be combined. With no files or an operand -, input comes from standard input. -- ends option parsing so a leading-hyphen filename can be used. When multiple file operands are given, each readable input's output is preceded by a ==> name <== header, with a separating newline before every header after the first; read errors are diagnosed and do not prevent later operands from being processed. Counts must be non-negative decimal integers; missing or malformed counts, conflicting count modes, and unsupported options return status 2.

Exit Status

  • 0: Success.

  • 1: Read error.

  • 2: Usage error.

tail Output last part of files

Outputs the last N lines (default: 10) or bytes of each input. Line mode preserves original bytes and newline termination; -c emits the last N bytes, including for binary input. A signed count uses +N to start at the Nth line or byte and -N (or no sign) to count from the end; start positions are one-based, so +0 is invalid. -n and -c are mutually exclusive. With no files or an operand -, input comes from standard input. -- ends option parsing so a leading-hyphen filename can be used. When multiple file operands are given, each readable input's output is preceded by a ==> name <== header, with a separating newline before every header after the first; read errors are diagnosed and do not prevent later operands from being processed. POSIX follow mode (-f) is unsupported: ESH tail reads finite snapshots instead of waiting for files to grow. Missing or malformed counts and unsupported options return status 2.

Exit Status

  • 0: Success.

  • 1: Read error.

  • 2: Usage error.

grep Search text for patterns

Filters lines matching any supplied pattern. Repeated -e options accept multiple patterns and allow patterns beginning with -; -f reads newline-separated patterns from one or more files. Either option may supply patterns without a positional pattern operand. An empty pattern file supplies no patterns and selects no lines. Without -e or -f, the first operand is the pattern. With no input file operands, or for an operand -, grep reads standard input. When -f - is used, standard input is consumed as the pattern file. Input records split on LF; CR in CRLF data remains part of the line, and a final unterminated record is processed. Selected records are written with an LF terminator. -c prints the selected-line count for each input; filenames prefix counts when multiple files are supplied. -l prints each matching input name once, stops reading each file after its first selected line, and takes precedence over -c; standard input is named (standard input) using ESH's explicit display label. -q suppresses all output, stops reading at the first match, and returns success if any input line matched, even if an earlier input could not be read. -s suppresses file-read diagnostics but preserves the error status. -x selects only lines matched in their entirety. The default pattern dialect is POSIX basic regular expressions for grouping and interval operators; -E selects extended regular expressions and -F selects fixed strings. -E and -F are mutually exclusive, including when clustered. BRE backreferences and locale collating/equivalence classes ([[.element.]], [[=character=]]) are unsupported and return a usage error. Matching is Unicode-based rather than locale-controlled POSIX byte matching.

Options

  • -i: Case-insensitive search.

  • -v: Invert match.

  • -q: Quiet mode.

  • -s: Suppress file-read diagnostics.

  • -c: Print selected-line counts per input.

  • -l: Print each matching input name once; overrides -c.

  • -x: Require a pattern to match the entire input line.

  • -n: Line numbers.

  • -e <pattern>: Add a pattern; may be repeated.

  • -f <file>: Read newline-separated patterns; may be repeated. - consumes standard input as the pattern file.

Exit Status

  • 0: Match found.

  • 1: No matches found.

  • 2: Invalid invocation or read error.

cut Extract sections from lines

Extracts selected raw byte positions with -b, Unicode character positions with -c, or delimiter-separated fields with -f. Selection lists accept comma or ASCII-whitespace separators and inclusive ranges such as 1,3-5,8- or 1 3-5 8-; selected output stays in input order. With -b -n, valid UTF-8 characters are kept intact by adjusting each selected byte range to character boundaries. Invalid UTF-8 bytes are treated as independent bytes in this mode. Character selections follow ESH's locale-independent Unicode scalar model; ordinary byte selections can split a multibyte character. Short options may be grouped when the option with an argument is last, as in -sf1. Field mode accepts a one-character -d delimiter, preserves lines without that delimiter unless -s is supplied, and supports standard input with no files or the - operand. File read errors are diagnosed while later operands are still processed; the final status is 1 if any file failed. Output records end with a newline. Invalid or missing selections, conflicting modes, unsupported options, and invalid delimiters return status 2.

Exit Status

  • 0: Success.

  • 1: Read error.

  • 2: Invalid invocation.

tr Translate or delete characters

Translates characters from set1 to set2, deletes selected characters with -d, and squeezes repeated output characters selected by -s. -c/-C complement the first set for translation, deletion, or squeezing. The two complement options are mutually exclusive, though either selects the same ESH Unicode complement behavior. -d and -s can be combined, but require both set1 and set2; with -s alone, one operand squeezes repetitions from that set. The set2 form [x*n] repeats x n times; an omitted or zero count repeats enough to extend set2 to the length of set1, and a multi-digit count beginning with zero is parsed as octal. When set2 is shorter than set1, ESH repeats the last character of set2 to complete the mapping. Sets accept Unicode ranges, the ASCII forms of POSIX named character classes, backslash escapes, and one-to-three-digit octal escapes up to \377. ESH also expands supported named classes in set2 in ascending ASCII order; POSIX only defines the lower/upper case-conversion forms there, so other set2 classes are an ESH extension. Class expressions remain separate from adjacent range operators, and an escaped hyphen is literal. Octal values denote the corresponding Unicode scalar (so values above ASCII are emitted as UTF-8). ESH processes and orders Unicode scalar values independently of locale. If set1 repeats a character during translation, its first occurrence determines the replacement; this gives ESH a fixed result where POSIX leaves duplicate source characters unspecified. Unsupported options, malformed sets, or an invalid operand count return status 2.

Options

  • -d, --delete: Delete characters in the first set.

  • -s, --squeeze-repeats: Replace repeated selected output characters with one copy.

  • -c, -C: Complement the first character set.

Exit Status

  • 0: Success.

  • 2: Invalid invocation or character set.

sort Sort text lines

Sorts input records by ESH's locale-independent Unicode string order, or by an initial decimal number with -n. -m merges input files already ordered by the selected comparison keys. -c checks input order without writing sorted output; it returns status 1 and a diagnostic when records are out of order. -C performs the same check without a diagnostic. With -cu or -Cu, equal comparison keys also fail the check. -c and -C check one input file at most and cannot be combined with -m or -o. -k field[.character][,field[.character]] adds an ordered comparison key; fields and character positions are one-based. Without -t, fields are separated by runs of ASCII spaces and tabs. -t separator uses the specified single character and preserves empty fields. A key without an end position extends through the end of its record. Global -b ignores leading ASCII blanks when locating key character positions; a b modifier applies this rule only at the start or end position where it appears. Key definitions accept the b, d, f, i, n, and r modifiers. If any modifier appears on a key, that key uses its own comparison modes instead of global ordering modes. -d builds dictionary keys from Unicode alphanumeric characters plus ASCII spaces and tabs. -f compares Unicode uppercase keys; it does not depend on the host locale. -i ignores Unicode control characters in comparison keys. Numeric comparison uses optional leading ASCII spaces/tabs, an optional minus sign, digits, and an optional decimal fraction; missing digits mean zero. Decimal comparisons are exact and do not use floating-point conversion. ESH rejects -n combined with -d or -i. Ties use the full line as a lexical tie-breaker, reversed when global -r is active, unless -s or -u is selected. With -s, equal comparison keys retain input order. With -u, records equal on all selected keys collapse and the first input record is retained. Carriage returns are retained as record data, including in CRLF input, and an unterminated final record is processed. Output records end with a newline. Short -b, -c, -C, -d, -f, -i, -m, -n, -r, -s, -u, -k, and -t options can be combined where their modes do not conflict.

Options

  • -c, --check: Check that at most one input file is ordered; write no sorted output. Print a diagnostic for disorder.

  • -C, --check-silent: Check ordering without a diagnostic. Both check modes cannot be combined with each other, -m, or -o.

  • -m, --merge: Merge input files already sorted by the selected comparison keys.

  • -o output, --output output: Write sorted records to the output file. The input is read before the output is opened, so the same path may be used for input and output.

  • -r, --reverse: Reverse the sort order.

  • -d, --dictionary-order: Ignore punctuation for comparisons.

  • -i, --ignore-nonprinting: Ignore Unicode control characters for comparisons.

  • -f, --ignore-case: Compare Unicode uppercase keys.

  • -n, --numeric-sort: Compare initial decimal numbers.

  • -s, --stable: Preserve input order when all selected comparison keys are equal.

  • -u, --unique: Output one copy of each equal sort key.

  • -b, --ignore-leading-blanks: Ignore leading blanks when locating field character positions in keys.

Exit Status

  • 0: Success.

uniq Filter adjacent duplicate lines

Collapses adjacent records that are identical after optional comparison skips. Reads standard input when input is omitted or -; writes standard output when output is omitted or -. At most one input and one output operand are accepted. Carriage returns are retained as record data, including in CRLF input, and an unterminated final record is processed. Output records end with a newline. -f skips leading blank-separated fields; -s then skips Unicode characters. These options affect comparisons only; output preserves the original first record in each group. Comparison uses exact Unicode text equality, independent of locale. Short options may be grouped, but -c, -d, and -u are mutually exclusive. -c follows the POSIX number, one space, and record format without implementation-specific padding.

Options

  • -c, --count: Prefix each output line with its occurrence count and one space.

  • -d, --repeated: Output only repeated lines.

  • -u, --unique: Output only lines that occur once.

  • -f <fields>: Skip this many fields when comparing records.

  • -s <chars>: Skip this many Unicode characters after skipped fields.

Choose at most one of -c, -d, and -u; invalid combinations return status 2.

Exit Status

  • 0: Success.

  • 1: Read error.

  • 2: Invalid invocation.

wc Count lines, words, and bytes

Counts newline bytes, words separated by Unicode whitespace, bytes, and Unicode scalar values. Word and character counting are locale-independent. The default is lines, words, and bytes; -m selects character counts instead of bytes, and - reads standard input. ESH also permits -c and -m together as an extension, printing both counts in character-then-byte order regardless of option order. Multiple file operands each produce a count line followed by a total line. -- ends option parsing for filenames beginning with -. Short count options can be grouped (for example, -lwc). Unsupported options return status 2.

Exit Status

  • 0: Success.

diff Compare files line by line

Computes unified line-by-line differences between two files.

Exit Status

  • 0: Files are identical.

  • 1: Files differ.

str String inspection, manipulation, and predicates

Provides string transformation and inspection operations. Reads from standard input if trailing string argument is omitted.

Options

  • -t, --trim: Strip leading and trailing whitespace.

  • -u, --upper: Convert string to uppercase.

  • -l, --lower: Convert string to lowercase.

  • -r, --replace <from> <to>: Replace occurrences in string.

  • -s, --split <delim>: Split string into lines by delimiter.

  • -c, --contains <needle>: Exit code 0 if needle is found, 1 otherwise.

  • --starts-with <prefix>: Exit code 0 if string starts with prefix.

  • --ends-with <suffix>: Exit code 0 if string ends with suffix.

  • --len: Output character length of string.

Exit Status

  • 0: Success / Predicate True.

  • 1: Predicate False.

numfmt Convert numbers to/from human-readable strings

Formats numbers into human-readable units (e.g. 1024 -> 1.0K).

Exit Status

  • 0: Conversion successful.


3. Structured Data Formats

json In-process JSON query and validation

Query and extract values from JSON structures without external dependencies like jq. The source may be a file path, an inline JSON string, or standard input when omitted or -. A path is treated as a file only when it names an existing regular file; otherwise the operand is parsed as JSON text.

Options

  • -g, --get <key_path>: Extract value by dot path (e.g. json -g pkg.version package.json).

  • -v, --valid: Validate JSON syntax (exit 0 if valid, 1 if malformed).

  • -k, --keys: List top-level object keys.

  • -p, --pretty: Format and pretty-print JSON payload.

Examples

PACKAGE='{"name":"everyinit","version":"1.2.3","downloads":{"bytes":2048}}'
NAME="$(json -g name "$PACKAGE")"
VERSION="$(json -g version "$PACKAGE")"
BYTES="$(json -g downloads.bytes "$PACKAGE")"
echo "$NAME $VERSION ships $BYTES bytes"

Exit Status

  • 0: Match found / Valid syntax.

  • 1: Key not found or invalid JSON.

yaml In-process YAML parser and query engine

Query and convert YAML documents directly in-process without external tools. Reads from standard input when file is omitted or -.

Options

  • -g, --get <key_path>: Extract value by dot path (e.g. yaml -g app.name config.yaml).

  • -j, --to-json: Convert YAML document into JSON format.

  • -v, --valid: Validate YAML syntax.

  • -k, --keys: List top-level mapping keys.

Exit Status

  • 0: Success.

  • 1: Key not found or invalid YAML.

csv Parse and format CSV data

Parses and formats CSV input data.

Exit Status

  • 0: Success.

table Render aligned terminal tables from columnar data

Formats columnar input into aligned, readable terminal tables with borders.

Exit Status

  • 0: Success.


4. Archive & Compression

archive Format-agnostic archive creator

Automatically detects format (.tar.gz, .zip) from file extension and packages assets.

Examples

archive output.tar.gz ./files...
archive output.zip ./files...

Exit Status

  • 0: Success.

unarchive Format-agnostic archive extractor

Automatically unpacks .tar, .tar.gz, and .zip files into target directory.

Exit Status

  • 0: Extraction successful.

tar Read and write tarball archives

Creates or extracts standard tarball archives.

Exit Status

  • 0: Success.

zip Create ZIP archives

Compresses files and directories into a standard ZIP container.

Exit Status

  • 0: Archive created.

unzip Extract ZIP archives

Extracts entries from a ZIP archive to disk.

Exit Status

  • 0: Success.


5. Cryptography & Hashing

hash Multi-algorithm cryptographic hash generator

Without arguments, hash reports the (empty) command-location cache; hash -r clears it, and hash utility... checks names against the shell's command lookup. ESH resolves commands dynamically and does not retain a location cache, so these POSIX forms do not change later lookup. For cryptographic digests, use an explicit algorithm option: -a/--algo with sha256, sha512, md5, or crc32, or one of the --sha256, --sha512, --md5, and --crc32 flags. The digest form reads one file, string operand, or standard-input operand. Conflicting algorithm selections and more than one input operand return status 2.

Options

  • -a, --algo <algo>: Compute hash using sha256, sha512, md5, or crc32.

  • --sha256: Shorthand for -a sha256.

  • --sha512: Shorthand for -a sha512.

  • --md5: Shorthand for -a md5.

  • --crc32: Shorthand for -a crc32.

Exit Status

  • 0: Success.

  • 1: Failure reading file or computing hash.

  • 2: Conflicting algorithms or extra input operands.

base64 Encode or decode Base64 data

Encodes or decodes standard Base64 streams.

Options

  • -d, --decode: Decode Base64 input into raw data.

Exit Status

  • 0: Success.

crypto Manage Ed25519 signatures and keys

Verifies and creates raw Ed25519 signatures with PKCS#8 private keys and SubjectPublicKeyInfo public keys. It can also generate a PEM key pair or export the public key corresponding to a private key.

Options

  • --verify --pubkey <key.pem> --sig <signature> <file>: Verify a raw signature.

  • --sign --key <key.pem> <file>: Write a raw signature to standard output.

  • --public-key --key <key.pem>: Write the corresponding public PEM key to standard output.

  • --generate --private <key.pem> --public <key.pem>: Generate and save a key pair.

Exit Status

  • 0: The requested operation succeeded.

  • 1: Signature is invalid or an input cannot be read.

  • 2: Invalid invocation.

sha256sum Compute and check SHA-256 digests

Computes and verifies SHA-256 checksums compatible with coreutils.

Options

  • -c, --check <checksums.txt>: Verify files listed in a checksum manifest.

Exit Status

  • 0: Success / Match.

  • 1: Checksum mismatch.

  • 2: Invalid invocation.

md5sum Compute and check MD5 digests

Computes and verifies MD5 checksums.

Exit Status

  • 0: Success.


6. Networking & Polling

http In-process HTTP client

Performs HTTP requests directly in-process without requiring external curl.

Options

  • -X, --request <method>: HTTP method, defaulting to GET.

  • -H <key:value>: Request header.

  • -d <data>: Request body payload.

  • -o <file>: Destination file.

Exit Status

  • 0: HTTP 2xx response.

  • 1: Network error or HTTP error status.

wait_port Poll TCP port until socket is open

Blocks execution until the specified TCP port is accepting connections or timeout reached.

Examples

wait_port 127.0.0.1:8080 15s

Exit Status

  • 0: Port is open.

  • 1: Timeout reached.


7. Date, Time & Duration

date Format and inspect system date and time

Displays the current date and time in the standard form, or formats it with a POSIX-style +format operand. -u formats in UTC; otherwise ESH uses the host process local timezone. Shell-only changes to TZ do not change that host timezone. ESH also accepts GNU-style -d/--date to format epoch seconds (@seconds or bare integer seconds) or an RFC-3339 timestamp; invalid dates return status 2. Setting the system clock is unsupported, and non-format timestamp operands return status 2. ESH supports the POSIX date conversions, including %n (newline), %t (tab), and the %E/%O modifiers; the modifier forms fall back to their unmodified conversion because ESH uses fixed English/C-style names and formats and does not apply LC_TIME. %s emits epoch seconds as an extension. An unsupported format directive returns status 2 with a diagnostic.

Exit Status

  • 0: Success.

  • 2: Invalid option, date, format directive, or unsupported clock-setting operand.

duration Parse, convert, and format durations

Converts durations between human strings (2h30m, 45s) and milliseconds.

Exit Status

  • 0: Success.

time Measure execution time of a command

Executes a command and prints real, user, and system time elapsed.

Exit Status

  • Evaluates to the exit code of the executed command.

sleep Delay execution for specified duration

Pauses execution for one specified non-negative finite duration (e.g. 500ms, 2s, 1m, or fractional seconds). POSIX sleep uses one non-negative integral seconds operand; ESH also accepts unit suffixes and fractional seconds. Extra operands produce a diagnostic and status 2. Milliseconds require an integer value; seconds, minutes, and hours may be fractional. Negative, non-finite, and out-of-range values produce a diagnostic and status 1.

Exit Status

  • 0: Duration elapsed.

timeout Enforce execution deadline on command

Executes a command, forcibly terminating it if it exceeds a non-negative finite duration. Duration values use the same syntax as sleep; invalid values produce a diagnostic and status 1.

Exit Status

  • Command exit status if within deadline.

  • 124: Terminated due to timeout.


8. System & Environment

env Print or modify execution environment

Prints the current environment when no command is given, or executes a command with a modified environment. -i starts with an empty environment; -u name removes a variable (an ESH extension to the POSIX env form). Assignments apply to the child environment. Command words and arguments retain their individual boundaries and are treated as literal arguments. The utility operand bypasses shell function lookup. ESH also permits in-process builtins as utility operands; this is an ESH extension.

Exit Status

  • 0: Success.

os Query host operating system attributes

Returns host architecture, target family, or operating system name.

Options

  • -n, -s, --name, --os: Print OS name (linux, macos, windows).

  • -m, --arch, --machine: Print host CPU architecture (x86_64, aarch64).

  • -f, --family: Print target family (unix, windows).

  • -a, --all, --info: Print combined OS-ARCH string (default).

Exit Status

  • 0: Success.

uname Print system information

With no options, prints the system name. The POSIX options -s, -n, -r, -v, and -m select the system name, node name, release, version, and machine fields. Options may be combined; selected fields are written in that fixed order. -a selects all available fields. Unix hosts use the platform's native system identity; other platforms may have only system name and machine information available.

Exit Status

  • 0: Success.

  • 1: Host system information could not be queried.

  • 2: Unsupported option or unexpected operand.

which Locate executable in PATH

Resolves the full filesystem path of external executable binaries.

Exit Status

  • 0: All commands located.

  • 1: One or more commands not found in PATH.

semver Semantic versioning manipulation and comparison

Validates, compares, and bumps semantic version strings (e.g. 1.2.3-beta.1).

Options

  • -v, --validate <version>: Validate semantic version format.

  • -c, --compare <v1> <op> <v2>: Compare two versions with operator (<, <=, >, >=, =, !=).

  • -b, --bump <major|minor|patch> <version>: Bump semantic version component.

  • -g, --get <major|minor|patch|pre|build> <version>: Extract version component.

Exit Status

  • 0: Valid version / Comparison True.

  • 1: Invalid version / Comparison False.


9. Control Flow, Output & Interaction

echo Unified standard output & formatting engine

The canonical ESH output tool. Unifies standard string printing, backslash escapes, and C-style printf format strings into a single high-performance built-in.

Options

  • -n: Do not output trailing newline.

  • -e: Enable escape sequence interpretation (\n, \t, \x1b).

  • -E: Disable escape interpretation (default).

  • -f <format>: C-style printf format string.

  • --: End option parsing so option-looking operands are printed literally.

The combined forms -ne and -en disable the trailing newline and enable escape interpretation. The format may also be attached to -f, as in -f%s.

Unless -n is present, echo appends one record newline after the joined operands, even when an operand or an interpreted escape already ends in a newline.

These flags define ESH's output behavior. POSIX echo leaves important -n and backslash cases implementation-defined; use printf when writing scripts intended to behave consistently across shells.

Examples

echo "Hello world"
echo -f "User: %s (ID: %d)\n" "$USER" "$UID"

Exit Status

  • 0: Success.

printf Format and print data

Formats arguments according to a required format string. If the format operand is missing, printf writes a diagnostic and returns status 2. Unsupported conversion characters and incomplete trailing conversions write diagnostics, return status 1, and allow later format text or shell commands to continue. A %b operand's precision limits the decoded output before \c stops the current invocation.

Octal escapes in the format operand emit one byte using the low eight bits of the octal value; for example, \\400 emits NUL and \\777 emits byte 0xff.

For a backslash followed by an unrecognized character in the format operand or a %b value, ESH removes the backslash and writes that character. POSIX leaves these escape sequences unspecified.

Supported conversions are %s, %b, %c, %d, %i, %o, %u, %a, %A, %f, %F, %e, %E, %g, %G, %x, and %X; %% prints a percent sign. Integer operands accept C-style base prefixes, and unsigned conversions print negative values using 64-bit unsigned representation. A leading single or double quote converts the next Unicode scalar value to its numeric value. Floating operands accept decimal and hexadecimal forms such as 0x1.8p+2. %a/%A format hexadecimal floating values with a binary exponent; default precision emits enough hexadecimal digits to represent the f64 value exactly and trims trailing zero digits, while explicit precision rounds to nearest with ties to even. The format operand and %b accept POSIX \\a, \\b, \\f, \\n, \\r, \\t, \\v, and \\\\ escapes. The format operand also accepts \\ddd for one to three octal digits; %b accepts \\0ddd for a zero byte or up to three following octal digits. ESH additionally accepts \\e and \\x followed by one or two hexadecimal digits. An escaped percent in the format is written literally and does not start a conversion. The format repeats while arguments remain. Numeric field widths, numeric precision, and the -, +, space, #, and 0 flags are supported for the implemented conversions. Positive NaN values honor the + and space sign flags, and negative NaNs retain their minus sign. The 0 flag is ignored when formatting infinity or NaN. Width and precision can also be supplied by * operands; a negative width left-aligns, and a negative precision is treated as omitted. %s and %b precision count Unicode scalar values, and %c emits the first Unicode scalar from its argument (NUL for an empty argument). This uses ESH's Unicode string model instead of POSIX's byte-oriented character and precision behavior. %f/%F default to six fractional digits; %e/%E use scientific notation and retain a decimal point for # with zero precision, and %g/%G choose fixed or scientific notation from the rounded exponent and significant-digit precision. %g/%G remove trailing fractional zeros unless # is present; with #, the decimal point is retained even when the rounded mantissa has no fractional digits. Numeric formatting is locale-independent: LC_NUMERIC does not change the decimal point or conversion output, keeping builtin output stable across hosts. The hh, h, l, ll, j, z, t, and L length modifiers are accepted; they do not narrow ESH's integer operand values. %b interprets ESH backslash escapes, including POSIX \\0ddd octal escapes that emit the corresponding raw byte; \\c in a %b operand stops the current printf output, including later conversions and format repetitions. Numeric conversion errors emit a diagnostic, print the valid numeric prefix when available, clamp integer overflow to the signed or unsigned 64-bit boundary and flag floating overflow/underflow, return status 1, and do not prevent later conversions or format repetitions.

Exit Status

  • 0: Formatting completed without errors.

  • 1: Invalid or incomplete conversion, or invalid numeric operand.

  • 2: Missing format operand.

read Interactive input, passwords, confirmations, and menus

Unified input tool for terminal interaction and script wizards. For ordinary line input, the default delimiter is newline. With no variable operands, read assigns the full line to REPLY without IFS splitting, matching the conventional shell behavior; omitting variable operands is an ESH convenience extension. With named variables, ESH splits using IFS: IFS whitespace is collapsed, non-whitespace delimiters can produce empty fields, and the final variable receives the remaining text with intervening delimiters preserved. A single trailing non-whitespace IFS delimiter is discarded when the final variable's remainder begins with field data; repeated trailing delimiters, and delimiters at the start of that remainder, stay in the final variable. Leading and trailing IFS whitespace is removed from named-variable assignments. If IFS is unset, read uses space, tab, and newline as its delimiters; ESH leaves IFS unset when it was absent from the startup environment, so expanding $IFS then produces an empty value. An EOF after partial input assigns the data and returns status 1; EOF before any data leaves variables unchanged. If non-newline-terminated input ends immediately after a backslash, the partial value preserves that backslash. On a terminal, Ctrl-D at the start of a line produces immediate EOF, while Ctrl-D after text returns the partial text with status 1.

Options

  • -p <prompt>: Display prompt on standard error before reading.

  • -s: Silent password entry.

  • -c: Confirmation mode (exits 0 on y/yes, exits 1 on n/no).

  • -m <character> / --mask <character>: Show a mask character during secret input.

  • --menu: Interactive menu selection. Pass a source and optional target as operands.

  • -r: Keep backslashes literal instead of treating them as escape characters.

  • -d <delimiter>: Use the first byte of the argument as the input delimiter. An empty argument selects the NUL byte, as in POSIX.1-2024; for a multi-byte argument ESH uses its first byte, where POSIX leaves behavior unspecified. A byte delimiter can split a UTF-8 character; any invalid UTF-8 left in the input is replaced with � when assigned to shell variables.

  • -t <duration>: ESH extension; return status 1 when the timeout expires. If input has already supplied part of a line to ESH, it assigns that partial data before returning 1; with no input, variables remain unchanged. Canonical terminals deliver typed input on Enter or EOF, so unsubmitted keystrokes remain in the terminal until then. A timed-out terminal read does not consume input intended for the next read command.

  • -a <name>: ESH extension; assign multi-select menu results to an array (requires --menu).

  • --defaults <name>: ESH extension; use an array variable of selected menu keys as defaults.

  • --default <value>: ESH extension; use a default when input is empty or reaches EOF.

  • --: End option parsing so following operands are variable names.

Unknown options, missing option arguments, and invalid target variable names produce a diagnostic and status 2, including in secret, confirmation, and menu modes. Ordinary input validates every target before consuming data; menu mode restores buffered input if its target is invalid. Bare read options that POSIX defines but ESH does not support are not silently ignored.

Examples

read -p "Enter username: " USERNAME
read -s -p "Enter password: " PASSWORD
read -c -p "Deploy to production? " && ./deploy.sh

Exit Status

  • 0: Input read / Confirmation accepted.

  • 1: EOF / Confirmation declined / Interactive timeout.

  • 2: Invalid option or interactive-input configuration.

  • 130: Interactive input cancelled with Ctrl-C or Escape.

getopts Parse positional command-line options

Parses short options in the familiar POSIX loop pattern. It supports grouped short options, required option arguments, OPTIND/OPTARG, a leading : in the option string for silent error reporting, and an optional explicit operand list. With silent reporting, an unknown option sets the result variable to ? and OPTARG to the option character; a missing required argument sets the result variable to : and OPTARG to that option character. Without silent reporting, unknown options and missing arguments leave OPTARG unset and write a diagnostic. When option parsing ends, the result variable is set to ?, OPTARG is unset, and OPTIND points to the first operand. ESH requires option characters in the specification to be unique ASCII alphanumerics, with : only as the leading silent-mode marker or after an argument-taking option. When no explicit operands are supplied, it reads the script's positional parameters. Inside a function, it reads that function's positional parameters; OPTIND, OPTARG, and the result variable follow ESH's scoped assignment rules and can persist after the function returns. ESH also accepts a declarative option form for workflow commands; that form is an ESH extension and is not the POSIX getopts interface.

The traditional form requires both an option string and a valid shell identifier for the result variable. A missing operand or invalid result-variable name prints a usage diagnostic and returns status 2.

while getopts ":f:o:" option; do
  case "$option" in
    f) INPUT=$OPTARG ;;
    o) OUTPUT=$OPTARG ;;
    :) echo "missing argument for -$OPTARG" >&2 ;;
    \?) echo "unknown option -$OPTARG" >&2 ;;
  esac
done

Exit Status

  • 0: Option parsed successfully.

  • 1: End of options reached; the result variable is ?, OPTARG is unset, and OPTIND points to the first remaining operand.

assert Assert condition or abort with diagnostic

Evaluates a condition and immediately aborts execution with diagnostic telemetry if false.

Examples

assert [ -d ./dist ] "Dist directory must exist before packaging"

Exit Status

  • 0: Condition is True.

  • 1: Assertion failed.

retry Retry command until success or attempt limit

Repeatedly executes a command until it returns exit code 0 or reaches the attempt limit. -n requires a positive integer, -d accepts a non-negative finite duration, and -b accepts a finite non-negative backoff factor. -- ends option parsing; use it when the command name begins with -. A missing command, unsupported option, invalid or missing option value, or backoff that grows beyond the supported duration range returns status 2.

Exit Status

  • 0: Command succeeded within attempt limit.

  • The status of the final failed attempt when all attempts fail.

  • 2: Usage error or backoff duration overflow.

exit Terminate execution with exit status

Terminates the script or subshell context with the specified integer status from 0 through 255. Without an operand, it uses the last command's status. Malformed, out-of-range, or extra operands write a diagnostic and return status 2 without exiting.

return Return from a function or sourced file

Returns from the currently executing function or sourced file. An explicit status from 0 through 255 is returned as given; when omitted, return uses the last command's status. Outside a function or sourced file, or with malformed or out-of-range operands, it writes a diagnostic and returns status 2 without returning.

break Break from innermost loop(s)

Terminates the enclosing for, while, or until loop. An optional positive decimal level selects an outer loop; levels beyond the current nesting depth clamp to the outermost loop. Invalid operands or use outside a loop write a diagnostic and return status 2.

continue Continue to next iteration of loop(s)

Resumes execution at the next iteration of the enclosing loop. An optional positive decimal level selects an outer loop; levels beyond the current nesting depth clamp to the outermost loop. Invalid operands or use outside a loop write a diagnostic and return status 2.

export Export variables to child processes

Marks valid shell identifiers to be passed to child processes. Operands may use name=value to assign and export in one step. -- ends option parsing. export -p prints exported names in sorted order using shell-quoted scalar values; an exported name without a scalar value is printed without an assignment. With no operands, export succeeds without output. Other options and malformed identifiers write a diagnostic and return status 2.

local Declare local variables in function

Declares shell-identifier variables scoped strictly to the enclosing function body. Calling local outside a function writes a diagnostic and returns status 2 without creating variables. Invalid identifiers also write a diagnostic and return status 2.

declare Declare scalar variables, arrays, maps, or exports

Declares indexed arrays with -a, associative maps with -A, or exported scalar variables with -x. Without an option, operands declare scalar variables. -- ends option parsing. Readonly (-r) and integer (-i) attributes are not implemented and return an unsupported-option diagnostic.

typeset Declare variables or arrays (alias of declare)

Alias of declare; uses the same supported options and diagnostics.

set Set or inspect shell option flags

Enables runtime options with - and disables them with +. ESH supports a/allexport, e/errexit, u/nounset, x/xtrace, f/noglob, C/noclobber, and pipefail through -o/+o. set -a exports later scalar assignments; disabling it does not remove export attributes already set. Structured arrays remain internal values and are not converted to environment strings. -f is accepted and tracked for familiar option handling, but scalar pathname expansion is always disabled; explicit calls to glob continue to work. With noclobber enabled, > fails when its target already exists; use >| to force an overwrite. set -o lists each supported option and whether it is on; set +o prints commands that restore the current option state. $- contains the enabled short options in the order aeufxC.

After the first non-option argument, remaining words become positional parameters. -- ends option parsing, so set -- -x sets $1 to -x; use the same form for dash-prefixed numbers such as set -- -1. The sole argument - disables xtrace without changing positional parameters, matching the POSIX special form. With no arguments, set leaves options and positional parameters unchanged. Unknown options produce a diagnostic and status 2; invalid option groups leave the current option and positional-parameter state unchanged. ESH does not implement POSIX's variable listing behavior for bare set.

set -e stops execution after an unhandled nonzero result under ESH's failure-boundary rules. Builtin usage and context errors return ordinary status 2 and follow these same rules; they do not have POSIX special-builtin fatal-error behavior. if and loop-test failures are exempt, including failures inside a function called as one of those tests. The left operand of &&/|| is evaluated without an immediate exit so the operator can choose whether to run its right operand, but the final status of the complete logical expression is still subject to errexit. Thus false && action and true && false both stop execution; false || true succeeds. This is simpler than POSIX's contextual exceptions for non-final commands in AND/OR lists. set -u rejects expansion of an unset variable, including a read in arithmetic; short-circuited arithmetic operands are not read. set -o pipefail reports the rightmost nonzero pipeline-stage status, or 0 when all stages succeed; otherwise a pipeline's status is the last stage's status.

shift Shift positional parameters

Shifts positional parameters ($1, $2, ...) to the left by N positions (default: 1). Zero is allowed; negative, non-numeric, extra, or excessive counts write a diagnostic and return status 2 without changing the parameters.

trap Register signal and lifecycle handlers

Registers a shell command as a handler for the ESH conditions EXIT (also spelled 0), ERR, and cancellation-driven INT. Trap registrations belong to the shell execution context and persist when set or reset inside a function or a command with prefix assignments. ERR runs once for each failed command or pipeline stage, including failures inside command substitutions. A failing command that contains a failing substitution can therefore run the handler once for each failure. A failed command inside a function can trigger ERR for that command and again for the nonzero function call. In &| branches, each branch's trap output is buffered with its other output and emitted in source order. While an ERR handler runs, further ERR dispatch is suppressed; its result does not replace the triggering command's status. INT runs once when execution is cancelled. At root script completion, EXIT runs after INT, including after explicit exit, an unhandled set -e failure, cancellation that was already pending before execution began, or a returned runtime error. ESH temporarily clears a pending exit request while the handler runs; the handler sees the status that triggered cleanup, and its ordinary status does not replace the script's status or returned runtime error. An explicit exit inside an EXIT handler replaces the pending status without recursively invoking the handler. Isolated subshells and command substitutions do not run the parent EXIT handler. Both cleanup handlers can finish despite the cancelled execution token. Panics are not caught, so no trap cleanup guarantee applies during unwinding. INT does not install an operating-system signal handler. An empty action installs a no-op handler (ignore); - removes the handler and restores ESH's default behavior. With no operands, trap lists installed handlers in stable EXIT, ERR, INT order. With conditions and no action, it lists only those installed handlers. Listings use single-quoted shell text and can be sourced to restore registrations. Missing registration operands, unknown conditions, and malformed handler scripts write a diagnostic and return status 2; failed registration leaves existing handlers unchanged. Other POSIX signal names are unsupported.

trap 'echo "failed: $ESH_FAILED_CMD"' ERR
trap 'cleanup' EXIT
trap - ERR
wait Report completion status for shell process IDs

ESH does not launch fire-and-forget process jobs, and &| branches join before the next command runs. With no operands, wait therefore succeeds immediately. A decimal PID operand is not known to the ESH shell environment and returns status 127; empty or non-decimal operands, including job IDs such as %1, are unsupported and return status 2. If any operand is malformed, the whole invocation returns 2 before unknown-PID handling.

: No-op command

Returns success without producing output. Shell expansions and redirections are still evaluated before the builtin runs.

false Return an unsuccessful status

Returns status 1 without producing output. Operands are ignored. ESH implements this as a builtin so scripts do not depend on an operating-system executable.

true Return a successful status

Returns status 0 without producing output. Operands are ignored. ESH implements this as a builtin so scripts do not depend on an operating-system executable.

unset Remove variables or functions

Removes shell variables by default. Use -v to select variables explicitly or -f to remove function definitions; -- ends option parsing. Unsetting a function-local variable hides outer values until the owning function returns. Unsupported options and invalid identifiers write diagnostics and return status 2. ESH applies its regular variable scope and export restoration rules; it does not emulate POSIX special-builtin assignment persistence.

. Execute a file in the current shell context

Reads and executes the named ESH file in the current shell context, so variable, function, option, and trap changes remain visible to the caller. Optional operands temporarily replace the positional parameters while the file runs; the caller's positional parameters are restored afterward. A return command ends the sourced file and returns its status to the caller. Relative paths with a slash resolve from the ESH working directory; bare names are searched through the current shell value of PATH, even when it is not exported, then fall back to the working directory if no entry matches. This fallback is an ESH convenience extension.

test Evaluate conditional expressions

Evaluates condition expressions in-process without spawning subshells.

The [ builtin uses the same evaluator and requires a closing ]. Quote ( and ) when grouping an expression so the shell parser passes them as arguments. Boolean precedence is !, then -a (AND), then -o (OR).

File Predicates

  • -f <file>: True if regular file exists.

  • -d <dir>: True if directory exists.

  • -e <path>: True if path exists.

  • -a <path>: Alias for -e when used as a unary predicate.

  • -L, -h <path>: True if path is a symbolic link.

  • -b, -c, -p <path>: True for a block device, character device, or FIFO.

  • -g, -u <path>: True when the set-group-ID or set-user-ID mode bit is set.

  • -s <file>: True if file exists and has size > 0.

  • -r, -w, -x: Check read, write, and execute permission bits. -x is true for searchable directories as well as executable files. On Unix, these inspect mode bits and do not account for ACLs or effective-user access checks.

  • -nt, -ot, -ef: Compare file modification times or identity.

For -nt and -ot, a missing second operand makes -nt true when the first exists; a missing first operand makes -ot true when the second exists. If both are missing, either comparison is false.

On non-Unix platforms, -b, -c, -g, -p, and -u return false. The POSIX terminal predicate -t is not implemented because ESH does not expose shell file descriptors to this builtin; a two-operand use such as test -t 1 returns status 2 with an explicit unsupported-predicate diagnostic. A one-operand test -t still treats -t as a nonempty string.

String Predicates

  • -z <str>: True if string length is 0.

  • -n <str>: True if string length is non-zero.

  • <s1> = <s2>: True if strings are equal. ESH also accepts <s1> == <s2> as a Bash-compatible extension; = is the POSIX form.

  • <s1> != <s2>: True if strings differ.

  • <s1> < <s2> and <s1> > <s2>: Compare strings by Unicode scalar value, independent of locale. Quote the comparison operator so the shell passes it as an argument.

Integer Predicates

  • -eq, -ne, -lt, -le, -gt, -ge.

Malformed expressions and non-numeric operands to integer comparisons produce a diagnostic and status 2.

Exit Status

  • 0: Expression is True.

  • 1: Expression is False.

  • 2: Expression is malformed or an integer comparison has a non-numeric operand.


10. Control-Flow Keywords

if Conditional execution

Evaluates a condition command or expression. If the exit status is 0, executes the then branch.

Examples

if test -f ./config.yaml; then
    echo "Config found"
fi

then Consequent branch of an if/elif conditional

Marks the beginning of the consequent statements in an if or elif block.

elif Alternative condition branch

Evaluates an alternative condition if the preceding if or elif condition failed.

else Default fallback branch

Executes statements when all preceding if and elif conditions fail.

fi Close an if conditional block

Closes an if/then/elif/else block.

for Iterate over a list of items

Iterates over a sequence of words, binding each word to the variable.

Examples

for item in alpha beta gamma; do
    echo "Processing $item"
done

while Loop while condition is true

Executes the body statements repeatedly as long as the condition evaluates to exit status 0.

Examples

while test -f ./lock.pid; do
    sleep 500ms
done

until Loop until condition is true

Executes the body statements repeatedly until the condition returns exit status 0.

case Multi-way pattern matching branch

Matches word against glob patterns, executing the branch of the first matching pattern.

esac Close a case pattern matching block

Closes a case statement block.

select Generate interactive terminal menu loop

Expands the item list once, then prints a numbered menu to standard error and reads a selection from standard input on each iteration. An empty item list ends immediately without prompting or running the body. PS3 supplies the prompt, defaulting to #? , and is read again for each prompt. A valid one-based decimal number, with optional surrounding whitespace and a leading +, assigns the selected item to the loop variable; an invalid number assigns an empty value. REPLY retains the original input line unless it is also the loop variable. Without an in list, the positional parameters supply the items. End-of-file writes a newline to standard output and ends the loop with status 1; break and continue control it like other loops.

do Start body of for, while, until, or select loop

Begins the loop body statements.

done Close a for, while, until, or select loop

Closes a loop block.

in Specify item list in for, case, and select blocks

Separates loop variable or case target from candidates.

function Define named shell function

Declares a named function with isolated parameter scoping.

Page source: reference/esh/100.runtime-reference.3010.md