After Dark Systems / Service Automation HubCompletely Programmable Infrastructure

OpenSAH / Shell guides

The sash language.

Every form sash accepts: values and quoting, byte and row pipelines, expressions and their functions, control flow, functions, errors and jumps, transactions, concurrency and deadlines, service files, the closed command catalog with its entitlement keys, every exit status and every error string.

Available unversioned No packaged releases Linux and macOS

This guide: sash guide · Language reference

This reference describes the language implemented in this checkout: values, expressions, pipelines, statements, options, the closed agent command catalog, and explicit local Unix execution. For building, connecting, grants, planning changes, and recording runs, see DOCUMENTATION.md.

sash is not a POSIX shell and never evaluates a value as source. Default and --session modes run built-in filters and explicitly granted agent verbs; they do not search PATH. --local additionally runs Unix programs under the invoking user's OS permissions. Unless labeled local, host examples and command catalog entries describe agent forms and require the corresponding grant. See Explicit local execution mode for the differences.

Values

A value is a string, bytes, rows, one row, or data. Data comes from [ ] expressions and the from formats:

kind literal (inside [ ] only)
number 42, -3, 2.5 (int64 or float64)
bool true, false
list [1, "a", $x]
map {"port": 8080}; keys are strings, insertion order is kept
null null
path path("/etc/nginx"), or let p = path /etc/nginx (see Paths below)

Outside [ ] a bare 42 is a string. Rows are a list of maps that keeps its column order.

Access: $cfg.server.port, $list[0], $m["a key"], $row.field. A missing map key is null. An unbound name is exit 2 unset <name>; a field on a value that has no fields is exit 2 type value.

A value is never parsed again as source. let c = "unit restart nginx" then echo $c prints text; it cannot run. A command name must be a literal word on the line (see command_from_value below).

Words and quoting

  • 'single' is literal. "double" expands $name; write a regex in single quotes, because $ in double quotes starts a name.
  • Shell double quotes and expression double-quoted strings share escapes: \n, \r, \t, \b, \f, \v, \a, \e, \\, \", \$, \xHH, \uHHHH, and \UHHHHHHHH. Hex byte escapes may produce arbitrary bytes; Unicode escapes must be valid scalar values. Unknown escapes preserve their backslash; malformed numeric escapes are errors. Single quotes remain literal. Bare words still require quoting for spaces and separators.
  • $a$b and "$a$b" are one word. There is no word-splitting.
  • # starts a comment.
  • ; or a newline separates statements. && and || chain pipelines.
  • {a,b}c is brace expansion, !! and !$ are history; both rewrite the line before it runs, so the grant check sees the result.
let x = 1
echo "dq $x" $x$x 'single $x'

Pipes

| carries bytes: the left side is rendered to text. |> carries rows and accepts rows only. A row command with no row consumer prints its text table.

ps -ef | egrep sshd | head -n 5
unit status nginx |> where state == "failed"
ps |> group by user |> count |> sort by count desc

A byte stage before |> is a type error, exit 2, and that statement does not run. rows, lines, parse, and the from formats lift text into rows; a byte pipeline never calls rows for you.

echo "alice 1
bob 2" | rows name n |> where n > 1

json prints bytes as one JSON string and rows as one JSON array. to json prints a value or rows as JSON.

ps |> select user pid |> json
echo '[{"name": "web1", "cpu": 90}]' | from json |> where cpu >= 50 |> select name

In the built-in/agent pipeline engine, a pipeline fails when any stage fails. Local external pipelines run concurrently and report the rightmost nonzero stage status (or zero when every stage succeeds). if on a row pipeline is true when it yields a row; on a byte pipeline, when its exit is 0. A where that keeps nothing succeeds and is false in if.

Redirection

form meaning
< path stdin from a file, through file.read; first stage only
> path write the rendered text through file.write; last stage only; stdout stays empty
<<< word here-string: the word and a newline as stdin, not a file read

Background & requires --local; it is refused in agent/default mode. There is no >> or file descriptor redirection: 2>, 2>&1, 1>, &>, >&, <& and N< are exit 2 parse: <form> is not sash redirection: use capture { } for errors, and >> says use template_file or atomic for appends. A word and > need a space between them to be a word and a redirect: echo 2 > x writes 2. > of rows writes the text table; > after json writes the JSON. Every explicit stage and redirect path of a pipeline is checked against the grant before that pipeline starts. A function body is checked as its statements are reached; earlier pipeline stages may already have run when its body is denied. For explicit stages and redirects: a path outside the roots is exit 126 denied file.read or denied file.write.

unit status nginx |> json > /var/tmp/ops/nginx.json
egrep error <<< "one error line"

> writes whatever the pipeline produced, whatever its stages' statuses, also under set -e: a stage that fails or matches nothing still truncates the file to what came out, even nothing.

So write with | fs write-atomic <path> (operational features), which sends nothing when a stage failed, or write to a new path and check it, or put the writes in atomic { } (which rolls back on a non-zero statement), and read the byte count in the plan output before the real run.

Expressions

Expressions live only inside [ ]. Outside, a line is words and pipelines, so < and > stay redirects (except right after where <col>, where they compare).

Operators: + - * / %, == != < <= > >=, && || !, in, string + and *. Arithmetic reads a string that is exactly a decimal number. Comparison does not: two strings compare as strings, so [ "00" == "0" ] is false. Expressions are one line, assign nothing, and cannot call a verb. Division by zero is exit 2 type expr div zero.

Ranges: [ 1..10 ].

Functions, pure and in process (builtin lists them; a name not here is exit 2 type expr unknown function <name>):

group functions
text len upper lower trim split(s) split(s, sep) split_re(s, re) slice(s, start, end) join(list, sep) replace(s, old, new) starts(s, p) ends(s, p) pad(s, n) repeat(s, n) contains(s, sub)
regex (RE2, pattern up to 1 KiB) match(s, re) find(s, re) groups(s, re) sub(s, re, repl)
convert int int(s, base) float str bool type
list len sum min max avg sort uniq reverse first(l, n) last(l, n) range(a, b) contains(list, x) slice(list, start, end) get(list, index, default)
map keys values has(m, k) get(m, k, default) merge(a, b)
encode sha256(s) base64(s) unbase64(s) base64url(s) unbase64url(s) base91(s) unbase91(s) base122(s) unbase122(s) hex(s) unhex(s) uuid()
number radix(n, base) band(a, b) bor(a, b) bxor(a, b) bnot(a) shl(a, n) shr(a, n) popcount(a)
math abs(x) sign(x) floor(x) ceil(x) trunc(x) round(x) round(x, d) clamp(x, lo, hi) pow(a, b) sqrt(x) cbrt(x) exp(x) log(x) log(x, base) log2(x) log10(x) hypot(a, b) sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) atan2(y, x) pi() e() deg(x) rad(x) gcd(a, b) lcm(a, b) isqrt(n) divmod(a, b)
net is_ip(s) ip(s) ip_version(s) ip_in(addr, prefix) cidr(s) ip_class(s) ip_next(s) ip_prev(s)
path path(s) starts(p, root) (two paths compare whole components)
terminal is_tty()

Number bases: int(x) with one argument reads only a decimal number, so int("0x10") is an error. int(s, base) reads s in base 2, 8, 10 or 16 (any other base is exit 2 type int base): an optional sign, then an optional prefix that must match the base (0x for 16, 0b for 2, 0o for 8, either case), then digits. Only the base's own prefix is a prefix: in base 16, 0b101 is hex digits, so int("0b101", 16) is 45313. _ is refused, and so is a string that does not parse (type int(text)); past int64 is type expr overflow. radix(n, base) writes an int in base 2 to 36, lowercase, no prefix, - for a negative: radix(255, 16) is "ff". hex(s) stays a string's bytes, so hex(255) is a type error; unhex(s) is its inverse, an even number of hex digits in either case (anything else is type unhex).

Bitwise functions work on int64; a float is exit 2 type <name>(float), never truncated. shl and shr take a count from 0 to 63 (anything else is type shift); shr is arithmetic, and shl has no overflow check: a bit shifted out is gone. popcount counts the set bits of the 64-bit two's complement, so popcount(-1) is 64.

Addresses are text, read by Go's net/netip: dotted v4 with no leading zeros (010.1.1.1 is refused, never read as octal), v6 in any RFC 4291 form, and v4-mapped v6 (::ffff:1.2.3.4). A zone (fe80::1%eth0, or any %) is refused everywhere (type ip zone). An address that does not parse is type ip, a prefix type cidr, and an input over 1 KiB type <name>(text).

  • is_ip(s) is true or false for any value and never fails, so where over host data can filter with it.
  • ip(s) is the canonical text (v6 compressed lowercase; a mapped address stays mapped). ip_version(s) is 4 or 6 (a mapped address is 6).
  • ip_in(addr, prefix) is true when the address is in the prefix as written; or, for a v4 address and a v6 prefix, when its mapped form ::ffff:a.b.c.d is; or when the unmapped address is in the unmapped prefix (a v4-mapped prefix of /96 or longer unmaps to the v4 prefix it stands for). So containment never shrinks as a prefix widens: 127.0.0.1 and ::ffff:127.0.0.1 are each in 127.0.0.0/8, ::ffff:0:0/96 and ::/0, and neither is in ::1/128 or 2001:db8::/32. A v6 address that is not mapped is in no v4 prefix. A mismatch is false, not an error.
  • cidr(s) is a map: network (masked, so 10.1.2.3/8 gives 10.0.0.0/8), prefix, bits (32 or 128), first, last, and size (the address count, or null past int64, as for ::/0).
  • ip_class(s) is the first of unspecified, loopback, private (RFC 1918 and fc00::/7), link_local (unicast), multicast, reserved that holds for the unmapped address, else global. reserved is a fixed table of special-purpose ranges: v4 0.0.0.0/8 (but 0.0.0.0), 100.64.0.0/10, 192.0.0.0/24, 192.0.2.0/24, 198.18.0.0/15, 198.51.100.0/24, 203.0.113.0/24, 240.0.0.0/4 (with 255.255.255.255); v6 ::/96 (but :: and ::1), 64:ff9b::/96, 64:ff9b:1::/48, 100::/64, 2001::/23, 2001:db8::/32, 2002::/16, fec0::/10, 3fff::/20. global means only none of the above, so it may be publicly routable; it is not a guarantee that the address is reachable or assigned.
  • ip_next(s) and ip_prev(s) step one address; past the end of the family is type ip range, and so is a mapped address stepping out of ::ffff:0:0/96 (ip_next("::ffff:255.255.255.255")).

A result computed from a secret is a secret, and one computed from a term prompt answer still selects no subcommand. Known limit, as for hex and base64: an encoding of a secret made with radix or hex is not the secret's text for the file-mode and recording checks.

Math never yields NaN or infinity: an operation whose float result would be one is exit 2 type expr <name> domain (sqrt(-1), log(0), pow(0, -1), asin(2), exp(1000)). Integers stay exact: where both inputs are int64 and the result is integral, the result is an int64, and past int64 is type expr overflow, never a float (pow(3, 39) is exact, pow(3, 40) and abs(-9223372036854775807 - 1) are overflow).

  • abs keeps an int an int and a float a float. sign is -1, 0 or 1.
  • floor, ceil, trunc and round(x) give an int64 from a float (out of range is overflow) and return an int unchanged. round takes halves away from zero: round(2.5) is 3, round(-2.5) is -3. round(x, d) rounds a float to d decimal places, 0 to 15 (else type round places), for display, not money: binary floats make round(2.675, 2) 2.68.
  • clamp(x, lo, hi) is lo below, hi above, else x; lo > hi is type clamp range.
  • pow(a, b) with an int a and an int b >= 0 is exact by repeated squaring; any other is a float (pow(2, -1) is 0.5). There is no **.
  • sqrt cbrt exp log log2 log10 hypot and the trig functions (radians) are floats. log(x, base) needs base > 0 and base != 1. deg and rad convert radians to degrees and back.
  • gcd, lcm, isqrt and divmod take int64 only (a float is type <name>(float)). gcd(0, 0) is 0, isqrt(n) is the exact floor square root of n >= 0, and divmod(a, b) is {"q": ..., "r": ...} with floored division, so r has the sign of b; b == 0 is type expr div zero.

is_tty() takes no argument and is true only when a person can be asked: sash's stdin and stderr are both terminals and the script is not on stdin (sash -c, sash file, or the prompt). sash < script, a pipe, a job, and a replay are false. It is not pure like the others: it reads the terminal, and a recording pins it.

let n = [ 1 + 2 ]
let ok = [ $n >= 3 && "web" + "1" == "web1" ]
echo [ split("a,b", ",") ] [ upper("x") ] [ 2 in [1, 2] ]

Text fields and slices

split(s) splits on runs of Unicode whitespace and drops leading/trailing whitespace; an empty or whitespace-only string gives []. split(s, sep) keeps its existing literal-delimiter behavior, including empty fields. split_re(s, re) uses an RE2 delimiter (captured delimiters are not returned). Regex splitting accounts for temporary match storage against the expression budget before allocating it; dense delimiters can reach that budget sooner.

slice(value, start, end) takes a string or list, with a zero-based inclusive start and exclusive end. Omit end to take the remainder. Negative offsets count from the end; bounds clamp; a reversed range is empty. String offsets count Unicode code points, like len, not bytes or displayed grapheme clusters. get(list, index, default) returns the default for an absent element, including an empty list; negative indices count from the end. Wrong types still fail. Existing map get and strict $list[index] access keep their behavior.

Multiple names in let destructure a list expression, evaluated once. The list must have exactly as many elements as names; duplicate names are refused. Commas separate names for readability (as with for, whitespace also works). All target names and declared types are checked before any binding changes. Each result preserves the expression's secret and source provenance.

let user, uid = [ split("  alice   1001  ") ]
echo $user $uid [ slice("héllo", 0, 2) ]

Binding

let a = word
let b = [ {"port": 8080, "hosts": ["web1", "web2"]} ]
let c = (ps |> where user == root)
declare -r port = 8080
declare -i count = 0
echo $b.port $b.hosts[1]

declare flags: -r read-only (rebinding is exit 2 readonly <name>), -i number, -a list, -A map, -P path (a wrong type is exit 2 type <name> <type>), -s secret (see operational features). declare alone lists names, types, and flags, never values; declare -p name shows one. There is no declare -x. export NAME... declares public library names; export NAME = VALUE sets an environment value only in --local mode.

At the prompt, names, functions, and options carry from line to line. A script and sash -c start fresh.

Paths

A path is its own kind of value, not a string. Make one with let p = path /etc/nginx, declare -P p = /etc/nginx, or [ path("/etc/nginx") ]. It is checked once, when it is made: absolute, clean (no ., .., // or trailing /), valid UTF-8 with no control, format or line-separator character, at most 4096 bytes. A violation is exit 2 path: <reason>. A relative path (path conf.d or path ./conf.d) joins the current prefix; with none it is exit 2 prefix_unset. A glob in a path literal is exit 2 parse: a glob is not a path.

  • Join with / inside [ ]: [ $p / "conf.d" / $name ]. Each right-hand part is one component: not empty, not . or .., no /. Otherwise it is exit 2 path: join component, so a join cannot climb out of $p.
  • Accessors: $p.name, $p.dir (a path), $p.ext, $p.parts (a list).
  • starts($p, $root) compares whole components: /etc/nginx2 does not start with /etc/nginx. A path never equals a string; str($p) is its text.
  • A path prints as its text, and to json writes it as a string.
  • In a script (a file or sash -c), a file path given to cat, ls, cd, pushd, config, template, template_file, use, < or > must be literal text or a path. A word that expands text read from a host response, such as cat $r.name after ls or a field of from json over cat output, is exit 2 type path: build it with path(...) or a join, which checks it. Text the script wrote itself (a literal, an argument) is not from the host. At the interactive prompt, and when a session recording replays, words keep working.
let conf = path /etc/nginx
for r in ls /etc/nginx/conf.d {
  cat [ $conf / "conf.d" / $r.name ]
}

Control flow

let n = 0
if [ $n < 10 ] { echo small } else if [ $n < 100 ] { echo medium } else { echo large }
for x in [ 1..3 ] { echo $x }
for i, x in [ ["a", "b"] ] { echo $i $x }
for k, v in [ {"x": 1} ] { echo $k $v }
for p in ps |> where user == root { echo $p.pid }
while [ $n < 3 ] { let n = [ $n + 1 ] }
do { let n = [ $n - 1 ] } while [ $n > 0 ]

for walks a list, a map's keys (or key and value), rows, a pipeline, or a range. There is no C-style for and no foreach. break and continue act on the innermost loop.

A pipeline condition (if, while, await) is decided by what it produced: rows by whether there is at least one; bytes by exit 0; a function's returned bool by its value (fn up() { return [ false ] }; if up { ... } takes the else branch); returned rows by whether there is one. A secret never decides a branch.

Caps: one loop runs at most loopmax iterations (default 100000); the same cap bounds the rows of filter and each, the lines of parse, and the items of par for. One run (one prompt line, or a whole script) calls at most verbmax agent verbs (default 10000). Past either the run ends with exit 2 loop max or verb max, and try does not catch it.

Functions

fn restart_if_failed(u) {
  if unit status $u |> where state == "failed" { unit restart $u }
}
fn add(a, b) { return [ $a + $b ] }
let r = (add 2 3)
restart_if_failed nginx

A function is a command: call it with words, one per parameter (a wrong count is exit 2 usage <name>). return [value] gives the call's value. Each call checks the grant again. A function cannot be named after a closed-table form (exit 2 usage fn). Functions accept pipes and redirects; there are no default function parameters. A call deeper than eight is exit 2 fn depth.

When a function participates in a pipeline or has a redirect, $input is its input value, scoped to that call. | supplies text; |> supplies rows. A function's stdout becomes its output, or an explicit return supplies a typed value. Mixing stdout with an explicit returned value is exit 2 type fn: cannot mix stdout and return in a pipeline; use log for diagnostics. $input is restored after the call, including nested calls. A parameter named input, or a read-only outer input, cannot be used for a piped call.

fn loud() { return [ upper($input) ] }
echo hello | loud | egrep HELLO
fn services() { return [ [{"state": "active"}] ] }
fn identity() { return $input }
services |> identity |> where state == active |> select state

A function's output type is checked at runtime before the next row stage. |> refuses non-row output. Secrets cannot cross a piped function boundary or its output redirect. A plain standalone function retains its previous stdout and return behavior. Pipes remain buffered, not streaming.

Script arguments

An optional args { } declaration must be the first top-level statement. Each entry is name type required or name type default literal, optionally followed by choices "a,b,c" and help "description". Types are string, int (signed 64-bit), bool (true or false), and duration (positive, at most 24h; bound as its duration string). Names are letters, digits, and _, not starting with a digit, at most 64 characters (parse: argument name ... is not an identifier). Defaults, choices, and help must be literal, not expressions or variable references, and hold no *, { or } (a declaration reads nothing, so it never globs). help is reserved.

args {
  service string required help "Service to inspect"
  wait duration default 30s
  environment string default dev choices "dev,prod"
}
unit status $service

Invoke with an explicit separator:

sash inspect.sash -- --service nginx --environment prod
sash inspect.sash -- --help
sash -c 'args { name string required }; echo $name' -- --name nginx

Every option takes a separate value, including booleans. Unknown, duplicate, missing, or invalid arguments are exit 2 before source expansion or host calls. Values are data and are never reparsed as source. Generated --help lists the schema and runs no script commands. These arguments apply to normal script execution, including --plan and --session; the analysis and offline tape command-line modes still take only their documented arguments. Do not put secrets in command-line arguments.

args {
  service string default nginx
  attempts int default 3
}
echo $service $attempts

Errors and jumps

try { echo "{bad" | from json } catch e { echo $e.status $e.message }
try { unit status nginx } catch e { echo $e.key }

e is a map: status, message, key, code, source, line. code is a stable category: timeout, denied, declined, unknown_command, invalid_argument, type_error, parent_error, refused, limit_exceeded, secret_refused, hangup, await_mutation, runtime_error, or command_failed. This does not expose new host-specific error details. source is the script filename (or script), or the file loaded with use; line is one-based in expanded source. Function errors identify the failing body statement. A denial can be caught: the denied statement ran nothing. Catching does not retry. try without catch is a parse error; catch { } is the explicit way to ignore a failure, and lint reports it as silent-catch.

What try cannot catch: a mutation or session-option change attempted inside await, loop max, verb max, a secret ended the line, and a jump. return outside a fn is exit 2 usage return; break outside a loop is usage break; exit n takes 0 to 255 (otherwise usage exit).

How a script continues: a statement whose status is 1 (an egrep that keeps nothing, a FAIL check) or any other status a verb returns (3 stays 3) does not stop it. Status 2, 126, or 127 stops the rest of the script, and the program status is that stopping status; a failed par stops it at any status. With set -e, any failed stage ends the script.

The grant is checked statement by statement, when each is reached, not for the whole script first. Statements before a denial have already run, mutations included.

Run sash --needs on a script to see every grant it needs before running it, and group file writes that must land together in atomic { } (operational features).

A status that does not stop the script is still that statement's status; the script ends with the last statement's status.

defer and finally

There is no trap. defer { block } runs when the enclosing function, or the script, ends: on success, return, exit, an error, a set -e stop or a cap, last deferred first. A hangup stops the session at once, defers included. A defer that fails is reported, the others still run, and the first failure keeps its status. A defer body is checked, planned and denied like any statement, and cannot break, continue or return (exit 2). At most 64 pending defers per function (exit 2 defer max).

try { } catch e { } finally { } runs finally after the body and any catch, on every way out, a return or break included. A finally that fails replaces the status.

defer { echo first }
defer { echo second }
echo body

$last and capture

sash has no file descriptors: a verb answers with output, an exit status, and an error message. After every statement $last is a read-only map: status, stages (each stage's status, like bash ${PIPESTATUS[@]}), keys (each stage's verb), failed_stage (index of the first failing stage, or null), code and message (as $e). let last = ... is exit 2 readonly last.

let r = capture { pipeline } binds a map of out (the output: text, rows or data), err (the error text, which is not printed), status, stages, keys, failed_stage, code and message, and an ordinary failure (a failed command, bad data, a timeout) does not fail the statement. A refusal is not captured: a denial, an unknown name, a secret refusal, a cap, or a hangup fails exactly as it would without capture. A secret stays *** in the map.

echo hi | egrep zz | head -n 1
echo $last.status $last.stages $last.failed_stage
let r = capture { echo x | from json }
echo $r.status $r.err

Options

set and shopt write one option table; set alone lists it as rows. No option touches the grant, the roots, or the agent re-check.

option set it default meaning
errexit set -e, set -o errexit off a failed stage ends the script
nounset set -u, set -o nounset off a missing map key is an error (unset key <k>), not null; an unbound name is always exit 2 unset <name>, with or without it
xtrace set -x, set -o xtrace off print trace <stage> on stderr before each stage
noglob set -f, set -o noglob off * stays a literal word on later lines
plan set -o plan off mutating verbs print plan: would ... and do not run
confirm set -o confirm off ask before each mutating verb; terminal only
pipefail always on on set +o pipefail is exit 2
loopmax set loopmax N 100000 iterations one loop may run
verbmax set verbmax N 10000 agent verbs one run (prompt line or script) may call

+ turns a flag off (set +e, set +o plan). shopt -s name and shopt -u name are the long names. The long name needs -o: set errexit is exit 2 usage set.

set loopmax N and set verbmax N take 1 up to the default. set may lower a cap and raise it back to its default, never past it; the same holds inside with.

set -e
set loopmax 1000
set loopmax 100000

Locks: under sash --plan, set +o plan is exit 2 usage set: plan is locked on for this run. Once confirm is on, set +o confirm, shopt -u confirm, and with set +o confirm are exit 2 confirm is locked. Without a terminal, set -o confirm is exit 2 confirm needs a terminal. set -o record <path> is in operational features.

Globs and expansion

* and ** list through file.read (argv ls) under a read root; sash never opens the directory. ** descends into child directories under the same root. *(/) and **(/) keep directories only; any other qualifier is exit 2 type glob, and so is a glob that matches nothing. A quoted * is literal.

cat /var/log/nginx/*.log | egrep error
echo /srv/app/**

A run accepts echo /srv/app/*(/), but --lint and --needs read a script before expansion and refuse the qualifier as a parse error (exit 2), so a script that uses one cannot be linted.

Globs, braces, and history expand once, before the line or script runs, against the prefix it starts with. In a script the prefix starts unset, so write globs as absolute paths: a relative glob is exit 2 prefix_unset even after a cd. A short name is never rewritten.

Output to a terminal

Byte output (echo, cat, a value printed) that goes to a terminal is escaped at the last write: a line feed and a tab pass, and every other control character, format character (bidi, zero-width), rune that draws nothing (a default-ignorable code point such as a variation selector or a Hangul filler, and the blank braille pattern U+2800), stacking combining mark past the fourth on one base, and unprintable rune prints as <U+XXXX>, a byte that is not UTF-8 as <0xHH>, and a literal <U+ or <0x as <U+003C>U+ or <U+003C>0x. Row cells and messages keep their own form (\x1b). A pipe, a file, a value, a > body, and a recording get the bytes unchanged, so what a script computes never depends on this. It keeps host data from driving the screen; it does not make that data trustworthy.

Exit statuses

status meaning
0 success
1 an ordinary failure: no match, a FAIL check; the script goes on. A verb's own status passes through unchanged (3 stays 3)
2 parse, type, or usage error, a cap, a refusal (secret, atomic, wasm, command_from_value), a grant that does not verify; the script stops
126 denied by the grant, or declined at a confirm prompt; that statement ran nothing, earlier ones did
127 unknown name; no host binary is run
129 hangup (SIGHUP)
130 a par interrupted (Ctrl-C), or Ctrl-C at a term question

Error strings

Each is one line on stderr.

stderr cause
unknown <name> not in the closed table and not a fn (127)
denied <key> the grant lacks the key, or a path is outside the roots; earlier statements already ran (126)
declined <key> answered no at a confirm prompt (126)
command_from_value a command word that comes from a value, $x status nginx (2); command_from_value: a term prompt answer selects no subcommand, a term prompt answer as the word that selects what unit, package, or sysctl does (2)
type |> bytes piped into |> (2)
unset <name> a name that was never bound (2)
type value a field on a value with none, or a whole row as a word (2)
type fn invalid function pipeline input/output, such as mixing printed output with a returned value (2)
fn depth a call deeper than eight (2)
loop max, verb max a cap; the line ends, try cannot catch it (2)
timeout past a timeout deadline; try and retry can catch it (2)
readonly <name> rebinding a declare -r name (2)
prefix_unset a relative path or glob with no session prefix (2)
path: <reason>, type path a path that is not absolute and clean, a bad join, or host text used as a script's file path (2)
type glob a glob qualifier other than (/), or a glob that matches nothing (2)
parse: ... parse: try needs catch, parse: too deep (65 nested blocks), parse: env not in this series (2)
usage <form>... wrong arguments to a form (2)
usage fs write-atomic the sink given the wrong words, or not last, or with no input, or with a > after it (2)
fs write-atomic: not written an earlier stage failed, so the sink sent nothing; the status is that stage's
term needs a terminal term with no terminal to ask; the script stops (2)
term prompt: end of input Ctrl-D on an empty line, or the input ended (1)
term prompt: empty answer Enter on an empty line: no answer, as at the end of input (1)
term prompt: answer over 4096 bytes, term prompt: answer is not text an answer that is too long or not UTF-8; there is no value (2)
term: interrupted Ctrl-C at a question; the script stops, try cannot catch it (130)
term inside par, atomic_irreversible: term a question inside par or atomic { } (2)
term prompt -s: only as declare -s name = (term prompt -s "question") -s anywhere but the whole value of a declare -s (2)
replay_secret <seq> a replay reached a term prompt -s; a recording never holds that answer (2)
a secret cannot decide a branch, a secret cannot leave sash, a secret ended the line secret rules, operational features (2)
atomic_irreversible: <what>, atomic: rolled back operational features (2)
wasm_unsupported the release build has no wasm (2)
plan: would <command> plan mode stopped a mutating verb (the run goes on)
grant_missing, grant_bad_shape, grant_bad_sig, grant_star, grant_expired, grant_root_slash sash --session refused the grant before anything ran (2)
grant_exp_zero, grant_service_mismatch, grant_identity_mismatch exp 0 on a grant that is not a boot grant (purpose service or boot); a service file under a grant for another service, or with another user or group (2)
service_top_level, service_run_and_start, service_glob, entry_missing a service file's rules, operational features "Service files" (2)
secret_refused, spawn_shell, env_refused: NAME, denied exec, denied cap, denied user, denied group, denied fs.mount, denied mount source, mount_overlap, mount_opt_refused, denied cwd, denied probe: ... a service verb's refusals, command catalog (2 or 126)
refused <key>: <code> (<why>) the init refused a service verb: unknown_name, name_in_use, denied, ceiling (2)
boot_entry, boot_in_await, boot_in_par, boot_call_limit a boot verb outside fn start, inside await, check or par, or past 64 in a run (2)
denied boot.<key>, denied module, denied device, denied host mount, denied network profile, denied service start, denied service stop a boot verb without a sash/3 purpose boot grant holding its key, or a name its list does not hold (126)
refused boot.<key>: <code> (<why>) the init refused a boot verb: boot_over, boot_once, boot_self, boot_chain, boot_cycle, boot_unit_auto, boot_essential, module_*, device_*, mount_target, mount_conflict, net_*, sash_grant_host, host_decl_*, busy, not_found, timeout and the others in command catalog (2)

Advanced statements

The following blocks control transactions, concurrency, deadlines, scope, and service lifecycle execution.

atomic

atomic deadline 120s {
  template_file /srv/app/app.yaml /srv/app/app.tpl /srv/app/app.conf
  echo on > /srv/app/flag
  check "conf" [ true ]
}

The block asks the agent to journal each file before it writes it, and on any failure to restore every journaled file. D is 1s to 600s (default the agent's 600 s). What that does and does not promise:

  • Writes land as they happen. Services and other readers see each file change before the block ends; there is no isolation.
  • A restore puts back only what the agent journaled, and leaves as found any file another writer changed meanwhile: refused atomic: atomic_inconsistent. The host is then half changed, and the agent keeps the journal for an operator.
  • If the session is lost mid-block (killed, the socket closed) and not by a hangup, sash sends no abort. The restore is the agent's, and the writes can stay until the transaction's deadline (up to 600 s); refused atomic: atomic_restored reports a restore the agent made at the deadline.
  • The agent refuses a write, which aborts the block, past 64 files (atomic_files), when the snapshots would pass 32 MiB (atomic_size), when a file's mode is not 0600, 0640, or 0644 (atomic_mode), or when another user owns the file (owner_changed). These limits are the agent's; sash prints its messages for them as refused file.write: <code> (...).

Refused statically, before the agent is asked anything, exit 2 atomic_irreversible: <what>: any unit.restart, package.install, or sysctl.set stage (a subcommand from a value counts), use, a nested atomic, and par, anywhere in the body or in a fn it calls by literal name. A break, continue, return, or exit that would leave the block is a parse error; atomic inside a par branch is too. A grant without file.write is denied file.write before begin.

Rollback: a failed check (with or without set -e), a non-zero statement, an uncaught error, a timeout or the block's deadline, or a cap stops the block, prints atomic: rolled back, and aborts; the block fails with that status (2 when it was 0), which try catches. A rolled-back run never ends 0, even after try or exit 0, so rolled-back writes cannot pass for landed ones. If the agent cannot open a transaction the block does not run: atomic unavailable: agent too old, or no file write targets in the grant. Plan mode prints plan: would begin atomic, the writes, then plan: would commit atomic.

par

par 4 { unit status nginx; unit status sshd }
par 4 as r for u in [ ["nginx", "sshd"] ] { unit status $u }

Each top-level statement (or each iteration) is a branch; N is 1 to 16 (usage par: N is 1 to 16), and the agent's in-flight limit caps it further (1 against an agent without the multiplexed pipe). Output is buffered and printed in branch order after all finish. Branch bindings are discarded at the join; checks merge. as r binds rows branch, item, status, message, key. A branch fails when its last status is not 0, so an egrep that matches nothing fails the par. The first failure cancels the rest at their next statement or verb; a verb already started finishes, and a mutating one that finished after the cancel is reported (branch 1: unit.restart nginx finished after cancel (exit 0)). par fails with par: branch N failed (exit S), which try catches; uncaught, a failed par stops the script whatever its status, 1 included. A first Ctrl-C cancels the branches and waits (par: interrupted, exit 130); a second stops waiting and prints outcome unknown: <key> <target> for each mutating verb still out, whose result only the agent audit then holds. verbmax is shared. Under confirm, N is 1. Parse errors: par inside par, atomic inside par, and a jump that would leave a branch.

branch { a; b } makes several statements one branch of a par N { } body; anywhere else it is parse: branch outside par. branch is a reserved word, as par is.

Channels. par N chan jobs(16) { ... } declares channels for that par only (1 to 4, buffer 1 to 64). send jobs <value> queues one value and waits while the buffer is full; for x in recv jobs { } takes them in order and ends when every branch that sends on jobs has ended. A channel is a name in the par text, never a value: it cannot be bound, returned, passed to a fn, or used in a nested par, and send/recv cannot be in a fn or a retry (parse: send inside fn, parse: recv inside retry); a whole channel par inside a fn or a retry is fine, each attempt a fresh par. Every channel needs a sending branch and a receiving branch, and no branch both sends on and receives from one. chan, send, recv, and branch are reserved words. All branches start; the agent's in-flight limit gates door calls, not branch starts, and with one slot (confirm, replay, an agent without the multiplexed pipe) one branch runs at a time, the lowest-numbered runnable one, switching only when it waits on a channel or ends. Values left unread fail the par (par: chan jobs: N unread, exit 1); a send with no receiver left is status 1 (send jobs: no receiver left); all branches waiting is par: deadlock: ..., exit 2, which try does not catch. Bytes do not cross: send jobs $b, [ $b ], or a list or map holding $b is exit 2; lift them with lines or rows. Text made from bytes ("x$b", [ len($b) ]) is text, as echo makes it, and crosses. A value is copied at send, at most 8 MiB counting 24 bytes for each string, number, list, map, row, and cell beside its text, and 32 MiB across a par's buffers (send jobs: value over 8 MiB, send jobs: buffers over 32 MiB, exit 2). A secret stays a secret and a term prompt answer still selects no subcommand after it crosses; origin on a received value shows where the sender got it. Use one receiving branch to write a shared file, not several. --needs adds nothing for a channel, and a verb on a received value is dynamic. Lint carries a sent value into the names recv binds, so secret-to-sink and the prompt rules see through a channel, and adds chan-to-mutation, chan-order, chan-secret, and chan-unread-risk. A recording holds each send, recv, and close in order, with the value's hash, never the value, and replay follows that order or is replay_diverged. A value with a secret in it, or a bound secret's text in any of its strings, is recorded redacted with no hash, and so is any value after the first 16 MiB of channel values a recording keeps to check for secrets bound later; each send event carries that 16 MiB budget's running total (keep), which replay checks; on replay a redacted event must be such a value, or one made from a response the recording holds redacted, or the run is replay_diverged. A redacted event checks the order, not the value. A recording is not tamper-proof: its hash chain is unkeyed, so anyone who can edit the file can rebuild the chain, and a forged redacted response is accepted as one; replay checks that a run matches its recording, not who made it.

retry and timeout

retry N [delay D] { } runs the block again on failure, up to N times (N 1 to 100, D up to 1h). A failure is what try catches; a cap or jump passes through; a confirm no is not retried. timeout D { } (D up to 24h) checks the deadline before every statement and agent call; past it is exit 2 timeout, which try and retry catch. A verb already in flight finishes. Durations are Go durations: 500ms, 2s, 5m, 1h. Lint warns retry-on-mutation when a retry body can repeat a mutation.

retry 3 delay 2s { package query nginx }
timeout 30s { package query nginx }

with

with items, then a block: set flags (set -e, set -o plan), loopmax N, verbmax N (same ceiling as set), prefix <dir> (checked like cd), and name = value. Each is restored on every way out. with set -f { } and with set -o noglob { } are refused (usage with: noglob is per line; use set -f), with noglob { } is not an item (parse: with item noglob), a read-only name cannot be overridden, and with env is parse: env not in this series.

with set -e, loopmax 1000, prefix /var/log { ls }

use

use PATH retains the flat definition-only import. use PATH as NAME [sha256 HASH] loads an isolated library namespace: call exported functions as NAME::function and read exported constants as $NAME.constant. A library may contain functions, non-secret readonly constants, explicit namespaced imports, and export declarations. With no exports declared, its own functions/constants are public; with exports, only the listed names are public. Dependency namespaces remain private. Dependencies resolve relative to their importing file. Import cycles, namespace collisions, more than 16 active imports, and more than 8 MiB of source across one dependency load are refused. SHA-256 pins use 64 lowercase hex digits and check the original file bytes before parsing.

Namespaced libraries cannot capture caller variables. Each call gets fresh bindings for its module constants and helpers; grant, budgets, plan, confirmation and cancellation still belong to the caller. Failed loads publish no namespace. A namespace is readonly and user function definitions cannot contain ::. --needs still does not open library files and reports use: not followed; it must not be treated as a complete dependency manifest.

functions lists names, parameters, source and scope as rows. functions show NAME prints the stored definition; functions refs NAME lists syntactic variable/function references (including locals and parameters), never values. funcsave NAME PATH writes one session function definition through file.write at mode 0600. It saves parsed source after normal source expansion, not captured bindings; dependencies are not bundled and nothing autoloads. Module functions must be distributed with their library source. Showing or saving source containing a secret declaration is refused. Saving obeys plan, confirmation, typed-path checks and file-write roots, and must be a standalone stage.

wasm

wasm m = <literal path> sha256 <64 lowercase hex> loads a WebAssembly module through file.read and checks its hash; [ m::fn(args) ] calls an export as pure computation (JSON in, JSON out, no imports, no clock, no filesystem, a 1 s deadline, counted against verbmax). A secret argument is refused (wasm_secret). It needs a build with the sashwasm tag.

The shipped release binary is built without the sashwasm tag. There, a wasm statement or a module call exits 2 wasm_unsupported and reads nothing. Do not write wasm for a release host.

await

await timeout D every I { pipeline } polls one condition immediately and then at interval I, until true or its deadline. D is positive and at most 24h; I is positive and at most 1h. The condition passes only on an explicit answer:

  • A verb's rows, at least one, usually filtered: unit status nginx |> where state == active. Rows turned into text on the way (| cat, | head) still decide by whether there was a row, and a value between two stages that held nothing (no rows, no text) makes the condition not ready whatever later stages produce, so ... |> where state == active | ps cannot pass on an empty where. A bare unit status nginx always has a row, so it passes at once: filter it.
  • Bytes straight from a verb or a byte filter, by exit 0: journal nginx | egrep started waits for a match.
  • A function's returned bool, and only a bool: fn up() { let r = (unit status app |> where state == active); return [ len($r) > 0 ] } then await ... { up }. A function that returns rows, a map, a string, a number or null is exit 2 type await: a function in the condition must return a bool, because a value's shape is not an answer: one row of {count: 0} would look ready. A function that prints instead of returning is exit 2 (printed text), and a function's value may not be piped into a later stage.

Stages that always exit 0 while turning data into text are refused as the condition's own stages (count, sum, avg, min, max, json, to ..., echo, wc, log). Ordinary nonzero statuses poll again; type errors, denials, unknown commands, caps, and control-flow jumps stop immediately. Output from observations is suppressed. The timeout is exit 2, catchable with $e.code == "timeout". A recording keeps one sleep per interval.

The condition must be a single pipeline. Functions may be called, but mutations, atomic blocks, and session-option changes inside them are refused, even under plan mode and inside parallel branches. These refusals cannot be hidden with catch. Grant checks and verb/loop caps still apply. --needs, --lint, and preview inspect the condition through the ordinary static walkers. Reads still reach the host under plan mode.

An outer, shorter timeout wins. Polling checks hangups and parallel cancellation between bounded sleeps. An already running parent call is not forcibly interrupted; if it returns after the deadline, even a successful observation times out. Clock and sleep operations participate in record/replay.

Service files

A service file is one sash script the init runs: a static service { } block the init reads without running anything, and optional lifecycle functions fn start(), fn stop(), fn reload() and fn check(). A file with no functions is purely declarative. The init does all process work; sash never forks, execs or signals anything. The verbs (spawn, signal, wait, proc, service status, probe, output, the file verbs, mount) are in command catalog.

The block is first in the file (before args), one key per line, literal values only, each key once:

key value
name [a-z0-9][a-z0-9_.-]{0,63}; must equal the grant's service
description one word or a quoted string
requires, after, wants service names; the init orders and fails on them, sash only records them
user, group the default identity of spawn
run an absolute program and its arguments, for a declarative service; not with fn start (service_run_and_start)
ready tcp HOST:PORT, unix PATH, file PATH or notify, then timeout D; or none
stop signal SIG timeout D: the signal, and the wait before the init sends KILL
restart never, or on-failure or always with optional delay D and burst N within D

An unknown key, a duplicate, a value from a name or [ ], and a bad value are parse errors (exit 2). A service file has no globs and no brace patterns anywhere: a run expands them before the top level, so they would read the host at load. Any is exit 2 service_glob, before anything runs. The top level of a service file may hold only service, args, fn, let and declare of a literal, and use: anything else is exit 2 service_top_level at parse time, so --describe and --entry never run a stray statement. A lifecycle function takes no parameters, fn run is refused (run is the implicit entry), and fn check is the entry while check "name" [ ] stays the builtin.

sash --describe [--grant-request] file
sash --session --entry start|stop|reload|check|run file
sash --plan --entry start file

--describe reads the file, runs nothing, takes no grant and calls no parent. It prints one JSON document ("v": "sash-describe/1"): the block (durations in milliseconds, empty lists as [], absent ready, stop or restart as null), the entries the file has, and per entry the --needs rows of that function and every function it calls by literal name. Exit 0 complete, 1 incomplete (a row with a note), 2 a parse error or no service block. --grant-request prints instead the unsigned sash/2 body the literal needs ask for (or sash/3, purpose boot, actor boot:<name>, when any boot verb is among them, with modules, devices, host_mounts, net_profiles, units_start and units_stop filled from the literal names): entitlements, file_read and file_write (the exact paths), exec, caps, mounts, mount_sources, user and group (the block's), env_names (the literal env keys), allow_private (a probe of a private address), exp 0, and host, lease_id and serial left for the fleet signer. A row with a note is never in the request.

--entry runs the top level (definitions only) and then calls the function; an entry the file does not define is exit 2 entry_missing. run is implicit for a file with run and no fn start: spawn main <run...> as the block's user and group, so the start is checked and audited like a scripted one. A sash/2 or sash/3 grant whose service is not the block's name (or a sash/1 grant) is exit 2 grant_service_mismatch before anything runs, a block user or group that is not the grant's is exit 2 grant_identity_mismatch, and a boot grant without --entry is exit 2 entry_missing. The init reads the exit:

exit start stop check
0 started (the init then waits on ready) stopped healthy
1 failed (the restart policy applies) failed (KILL after the stop timeout) unhealthy
2 a configuration or grant error: a denial, usage, type, secret_refused, unknown name; the init marks it failed and does not restart same same
3 not ready in time (an await ran out inside start) - -

check runs under the await rules: every mutation is refused, plan mode or not (await: mutation refused). Under --plan, a mutation prints plan: would spawn main /opt/app/bin/server --port 8080 as app:app and runs nothing; reads (proc, probe, service status, wait, output) still reach the init.

A secret bound with declare -s may leave sash only as an env value inside a literal env map in spawn opts: the frame carries it marked {"secret": ...} so the init writes it into the child's environment and never logs it, and the plan line, a trace and a recording never show it. Anywhere else (an argument, another option, an env map built in a name, a path, any other verb) it is exit 2 secret_refused.

check is read-only: a mutation there is refused before the init sees it, and --lint flags it as check-mutates.

Boot-ops units

A boot-ops unit prepares the host and ends: its fn start loads drivers, waits for disks, mounts them, brings up the network and starts the units that use them, with the boot verbs (command catalog, "Boot verbs"). It runs under a sash/3 grant with purpose boot (actor boot:<name>), which lists each name it may use; the init's host.json, module tree and catalog say what each name means. A boot verb runs only in fn start (boot_entry anywhere else), never in await, check or par, and the five that change the host are atomic_irreversible. Plan mode prints each one and calls nothing, device wait included, since what it would see depends on the module loads plan skipped.

A boot verb in fn stop is refused before the init sees it, and --lint flags it as boot-outside-start. mount ensure takes one name, never a path.

A declarative service with run needs no function; --entry run spawns it.

service {
  name app
  user app
  group app
  run /opt/app/bin/server "--port" 8080
}

Command catalog

Read this to check that a name exists, which entitlement key it needs, and whether it mutates. Every command and keyword form is in one Go table (internal/lang/builtin.go); the builtin command prints it, and a test checks that the embedded verbs reference and that table agree. The one statement outside it is wasm (operational features), which the release build refuses. A command name that is not here, and is not a fn you defined, is exit 127 unknown <name>. There is no host binary behind it.

Columns:

  • kind: verb (the agent fulfills it), filter (in process), builtin (in process, or a prefix move), keyword (syntax), session (the interactive editor only).
  • key: the entitlement the grant must hold, - for none. The agent checks the key again, and the target against the host's channel or file policy.
  • mutates: yes when the key is one plan mode stops and confirm asks about (unit.restart, package.install, sysctl.set, file.write, compute.job.cancel, svc.spawn, svc.signal, fs.mount, boot.module, boot.mount, boot.net, boot.start, boot.stop). Plan mode also stops boot.device (see the boot verbs).

The policy flag in the descriptions is what sash --needs --policy prints for that key: the systemapi channel-policy grant that adds it.

Host verbs

Run by the local agent, one call each, behind the grant check and the agent re-check.

form kind key mutates what
ps verb ps no Process table as rows. No policy flag.
unit status verb unit.status no unit status <unit> as rows. Grant: --service-status <unit> (status only) or --service <unit>. A bare unit is status too; unit <unit> is exit 2 usage unit. The agent refuses status without exactly one unit (--needs note not_grantable).
unit restart verb unit.restart yes unit restart <unit>, exactly one unit. Grant: --service <unit>.
journal verb journal no Journal read. The agent has no reader yet, so no grant can carry it: it is always denied (--needs note not_grantable).
package query verb package.query no package query <name> as rows. Grant: --package <name>.
package install verb package.install yes package install <name>, exactly one name. Grant: --package <name>.
sysctl get verb sysctl.get no sysctl get <key>. Grant: --tweak-sysctl <key>.
sysctl set verb sysctl.set yes sysctl set <key> <value>. Grant: --tweak-sysctl <key>.
config read verb config.read no config read <path>, a clean absolute path. sash checks the config.read key and that the path is under a file_read root (outside is denied file.read), not the file.read key; the agent re-checks with its own policy. Grant: --config <path>. There is no config write.

Compute

computeapi.io through the control plane (operational features, Compute). The host's agent forwards each call to the systemapi control plane, which checks the run's grant again and alone holds the tenant's computeapi key; nothing runs on the host. Every form answers rows. The subcommand and the lookup kind or job action are literal words (exit 2 command_from_value otherwise). No policy flag: the keys come with the run's grant.

form kind key mutates what
compute lookup verb compute.lookup no compute lookup dns <domain> [mx|txt|ns], tls <host>, ip <ip>, host <host>, reputation <domain or ip>, domain <domain> (availability). A target is at most 253 bytes with no control, format or space character: an address for ip, an ASCII host name for dns and domain, either for the others (operational features); else exit 2 compute_bad_input: target, nothing sent.
compute job list verb compute.job.read no The tenant's jobs: job, state, capability per row.
compute job show verb compute.job.read no compute job show <id>, an id of 1 to 128 letters, digits, _ and -, not starting with - (else compute_bad_input: id).
compute job logs verb compute.job.read no compute job logs <id>, the job's log lines as rows.
compute job wait verb compute.job.read no compute job wait <id> [timeout]: 90, 90s or 2m, 1 to 3600 seconds, default 300 (else compute_bad_input: timeout); inside a timeout block, no longer than the block has left. Returns the job's row when it ends or the time is up.
compute job cancel verb compute.job.cancel yes compute job cancel <id>. Carries an idempotency key from the run, the statement, and the loop iteration, so a retry around it sends the same key every attempt.

Files and text

Paths go through the agent's file helper under the grant's file_read and file_write roots; sash never opens a host path. Grant: --file-read <dir> or --file-write <dir>. Reads disclose host data: cat, template, use, config read, and the command lines in ps print whatever the host holds, credentials included, and a recording keeps it.

form kind key mutates what
cat verb file.read no cat <path>... reads files. With no path it copies the bytes already in the pipeline and needs no key.
ls verb file.read no ls [<dir>] lists a directory as rows.
cd builtin file.read no cd <dir> moves the session prefix (sash state, not the process cwd). The target must be inside a read root.
pushd builtin file.read no pushd <dir> pushes the prefix.
dirs builtin - no Shows the prefix stack.
popd builtin - no Pops the prefix; popping the last entry is exit 2 usage popd.
echo filter - no Prints its words and a newline. A list or map prints as JSON.
egrep filter - no egrep <re>: keeps matching lines (Go RE2). Exactly one pattern, no flags.
head filter - no head, head <n>, or head -n <n>: first lines (10 by default). head -1 and head -<n> print nothing and exit 0: use head -n 1 or head 1.
cut filter - no cut [-d <sep>] -f <n>: one field per line, whitespace-split without -d.
wc filter - no Counts lines of text, or rows. Flags are ignored: wc -c and wc -w print the line count too.
template_file verb file.write yes template_file <spec> <tpl> <out> [--check]: validate and render to <out>. --check writes nothing and prints a diff (only file.read). Local mode also accepts --engine jinja2 and --template-root DIR.
template verb file.read no ... | template <tpl>: render a template with the piped value; local --engine jinja2 optionally accepts --template-root DIR.
fs write-atomic verb file.write yes ... | fs write-atomic <path> [--mode 0600|0640|0644]: the last stage of a pipeline; writes what was piped to <path>, a > target under a write root. Unlike >, it sends nothing when an earlier stage failed (fs write-atomic: not written, the failing stage's status). --mode never loosens an existing file.
cat /etc/nginx/nginx.conf | head -n 1
cat /etc/nginx/nginx.conf | wc -c

Row tools

In process, no key. They take rows on |>; rows, lines, and parse lift text into rows.

form kind key mutates what
where filter - no where <col> <op> <value>, op == != < <= > >=.
select filter - no select <col>...: keep columns.
rows filter - no rows [<name>...]: text to rows. No names is one column line; named columns split on whitespace, the last keeps the rest.
sort filter - no sort by <col> [desc] [, <col>...].
uniq filter - no uniq [<col>...]: drop repeated rows.
group filter - no group by <col>, then count, sum, avg, min, or max.
count filter - no Count rows, or per group.
sum filter - no sum <col>, or per group.
avg filter - no avg <col>, or per group.
min filter - no min <col>, or per group.
max filter - no max <col>, or per group.
first filter - no first <n>.
last filter - no last <n>.
skip filter - no skip <n>.
filter filter - no filter [ <expr> ]: keep rows where it holds; $it is the row.
each filter - no each [ <expr> ]: a map adds or replaces columns, a scalar gives column value.
lines filter - no Text to rows with a line column.
parse filter - no parse "{a} {_} {b}", or parse re '<re with (?P<name>...)>': text to rows.
sub filter - no sub <col> <re> with <repl>: rewrite one column.

Data formats

In process, no key. Input is capped and nested data stops at depth 64.

form kind key mutates what
encode filter - no encode base64|base64url|hex|base91|base122: bytes to text; Base122 experimental.
decode filter - no decode base64|base64url|hex|base91|base122: strict text to bytes; no partial output on malformed input.
json filter - no Bytes print as one JSON string, rows as one JSON array.
from json filter - no Parse JSON text into a value.
to json filter - no Print a value or rows as JSON.
from yaml filter - no Parse one YAML document; a multi-document stream is a list.
to yaml filter - no Print a value as YAML.
from toml filter - no Parse TOML into a map; dates become RFC 3339 strings.
to toml filter - no Print a map as TOML.
from csv filter - no CSV to rows, header first; --noheader names columns c1, c2, ...
to csv filter - no Rows as CSV; a cell starting = + - @ gets a leading '.
from tsv filter - no TSV to rows; --noheader as for CSV.
to tsv filter - no Rows as TSV.

Control, settings, and modules

form kind key mutates what
let keyword - no let x = <word>, let x = [ <expr> ], let x = (<pipeline>).
if keyword - no if <pipeline or [ expr ]> { } else if ... { } else { }.
else keyword - no The other branch of if.
for keyword - no for x in <src> { }, for k, v in <src> { }: rows, a list, a map, a pipeline, a range.
in keyword - no The source of for.
fn keyword - no fn name(a, b) { } defines a command. Depth 8.
while keyword - no while <cond> { }.
do keyword - no do { } while <cond>: body first.
try keyword - no try { } catch [e] { }. A try without catch is a parse error.
catch keyword - no The handler of try; e is a map status, message, key.
return keyword - no return [value] from a fn.
break keyword - no Leave the innermost loop.
continue keyword - no Next iteration of the innermost loop.
exit keyword - no exit [n], n 0 to 255: end the script.
declare keyword - no declare -r -i -a -A -s name = value; declare lists names, declare -p name shows one.
functions builtin - no List function names, parameters, source and scope as rows.
functions show builtin - no NAME: print its source definition; secret declarations are refused.
functions refs builtin - no NAME: list syntactic variable and function references, never values.
funcsave verb file.write yes NAME PATH: save a session function definition at mode 0600; no captured bindings or autoload.
export keyword - no export NAME...: public library names. Local export NAME = VALUE is a separate environment form.
use keyword file.read no use PATH [as NAME] [sha256 HASH]: load definitions; namespaced imports support private helpers, exports and dependencies.
set builtin - no Session options: -e -u -x -f, -o name, +o name, loopmax N, verbmax N. set -o record <path> also writes a file (a file.write at mode 0600 at the end; refused in plan mode, asked under confirm).
shopt builtin - no shopt -s name, shopt -u name: the same option table by long name.
builtin builtin - no Lists this table and the expression functions as rows; builtin <name> filters it.
capture keyword - no let x = capture { pipeline }: the output, error text and statuses as a map; refusals are not captured.
defer keyword - no defer { block }: runs when the enclosing function or script ends, last first, on every way out but a hangup.
finally keyword - no try { } catch e { } finally { }: runs after the body and any catch, on every way out; a failing finally replaces the status.
retry keyword - no retry N [delay D] { }: run again on failure. N 1 to 100, D up to 1h.
args keyword - no Static script argument schema: required values, typed defaults, choices, and help.
await keyword - no await timeout D every D { pipeline }: poll a read-only condition, bounded by deadline and caps.
timeout keyword - no timeout D { }: D up to 24h, checked before each statement and verb.
atomic keyword file.write yes atomic [deadline D] { }: on a failure the agent restores the file writes inside, except files another writer changed meanwhile; writes are visible as they land. The key is the writes it holds.
par keyword - no par N [as r] { } or par N [as r] for x in <src> { }: branches at once, N 1 to 16.
chan keyword - no par N chan c(B)[, d(B)] { }: channels of that par only, 1 to 4, buffer 1 to 64.
send keyword - no send c <value>: one value on a channel of the enclosing par; waits while the buffer is full.
recv keyword - no for x in recv c { }: each value of c in send order, until every sending branch has ended.
branch keyword - no branch { a; b }: several statements as one branch, only at the top of a par N { } body.
with keyword - no with set -e, loopmax N, prefix P, x = v { }: scoped, restored on every way out.
check builtin - no check "name" [ <expr> ]: prints ok name or FAIL name (status 1).
checks builtin - no The check rows so far (check, result).
origin builtin - no origin name: where a name's value came from, as rows.
log builtin - no log debug|info|warn|error <msg> [ {fields} ]: one line on stderr.
term prompt builtin - no term prompt [-s] "<question>": asks the person at the terminal (script asks: <question>) and gives the line they type, without its Enter; an empty line is status 1 term prompt: empty answer. No terminal is exit 2 term needs a terminal. The answer is untrusted text (operational features). -s reads without echo and is legal only as declare -s name = (term prompt -s "<question>").
term confirm builtin - no term confirm "<question>": asks script asks: <question> [y + Enter / N]; status 0 for y or Y then Enter, 1 for anything else, Ctrl-D included. It is not the answer to confirm mode or to any approval.

Service verbs (the init)

A service file (operational features, "Service files") runs under the init, which performs these: sash never forks, execs, signals or mounts. sash checks each against the grant first and the init checks it again. The svc.* and fs.mount keys, and the exec, caps and mounts lists, come only in a boot grant, sash/2 purpose service or sash/3 purpose boot (sash --describe --grant-request); --needs --policy prints a comment for them, not a flag. A process is a name given to spawn ([a-z][a-z0-9_.-]{0,63}), never a pid: the init keeps a name-to-process table per service. A path is literal text or a path value, made absolute and clean before the check. No form takes a flag (a word starting with - is usage), and a secret anywhere but a spawn env value is exit 2 secret_refused.

form kind key mutates what
service keyword - no service { }: the static block of a service file, first in the file, literal values only.
spawn verb svc.spawn yes spawn NAME PROGRAM args... [opts [ {map} ]]: the init starts PROGRAM, one absolute path listed in the grant's exec (else exit 126 denied exec); a shell string or a relative name is exit 2 spawn_shell. opts keys: user, group (only the grant's, which the service block must match; omitted means those; else exit 126 denied user), cwd (under a file_read or file_write root, else denied cwd), umask, env (each name listed in the grant's env_names and not a loader, libc, interpreter or tool hook such as LD_PRELOAD, GIT_SSH_COMMAND or OPENSSL_CONF, which no grant opens: else exit 2 env_refused: NAME), limits, caps (each in the grant's caps, else denied cap), stdout and stderr (journal, null, file:<path> in file_write; stderr also stdout). Row name, pid, started_at. Plan mode prints plan: would spawn NAME PROGRAM args as U:G.
signal verb svc.signal yes signal NAME SIG: SIG one of HUP INT QUIT KILL USR1 USR2 TERM CONT STOP WINCH, to a process this service spawned (the init refuses any other name: exit 2 refused svc.signal: unknown_name).
wait verb svc.wait no wait NAME timeout D: row name, exit, signal, ended_at when it ends; exit 2 timeout when it does not.
proc verb svc.proc no proc NAME: row name, pid, state, started_at.
service status verb svc.status no service status NAME: any service's row name, state, since, pid.
probe verb svc.probe no probe tcp HOST:PORT, probe unix PATH, probe file PATH, probe notify NAME: exit 0 when ready, 1 when not; usable inside await. HOST is an IP literal or localhost, loopback only unless the grant has allow_private (then private addresses too; never a public one). A unix or file PATH must be in file_read.
output verb svc.output no output NAME [stderr] [tail N]: what the init captured of a spawned process's stdout (or stderr), as rows; N 1 to 10000.
mkdir verb file.write yes mkdir PATH [mode M] [owner U:G]: idempotent; M is three octal digits, or four with a leading 0 or 1.
chown verb file.write yes chown PATH U:G.
chmod verb file.write yes chmod PATH M.
touch verb file.write yes touch PATH.
ln verb file.write yes ln PATH TARGET: a symlink at PATH; both in file_write.
rm verb file.write yes rm PATH: a file or an empty directory, never recursive (rm -rf is exit 2 usage).
mount verb fs.mount yes mount SRC DIR [type T] [opts O]: T is tmpfs, proc, sysfs or devpts and SRC is that same name, or there is no type and O holds bind or rbind; remount changes only a mount the init made for this service (refused fs.mount: not_mounted); O is a quoted comma list of ro rw nosuid nodev noexec bind rbind remount size=N nr_inodes=N mode=OCTAL uid=N gid=N (else mount_opt_refused), and sash always adds nosuid,nodev. DIR exactly one of the grant's mounts (else denied fs.mount); SRC one of the grant's mount_sources (a name such as tmpfs) or a path beneath one listed (else denied mount source); bind, rbind and remount need a path SRC. DIR may not be at, under or over a file_write root: exit 126 mount_overlap.
umount verb fs.mount yes umount DIR: DIR in the grant's mounts.

Boot verbs (the init, boot grant only)

A boot-ops unit's fn start prepares the host: it loads drivers, waits for disks, mounts them, brings up the network and starts the units that use them, then ends. The script passes only a name; the grant lists the names, and the init decides what each one means (the kernel's module tree, root's host.json, the unit catalog). A raw path, mount target, address or interface never comes from the script. Each key needs a sash/3 grant with purpose boot (actor boot:<service>); with a sash/1 or sash/2 grant, even one that lists the key, it is exit 126 denied boot.KEY. The names come from the grant's modules, devices, host_mounts, net_profiles, units_start and units_stop, which sash --describe --grant-request fills; no systemapi flag grants them, and --needs --policy prints a comment for each.

Where they run: only under --entry start (anywhere else exit 2 boot_entry); never inside await or check (exit 2 boot_in_await), nor par (exit 2 boot_in_par): boot order is the order written. Inside atomic the five that change the host are exit 2 atomic_irreversible: boot.KEY before anything runs: none has a restore. At most 64 boot verbs per run (boot_call_limit, exit 2); set cannot raise it, and they count against verbmax too. No form takes a flag, each takes exactly one name, and a secret anywhere is exit 2 secret_refused. Every verb is idempotent: state is done when this call changed the host, already when it already matched. The init re-checks everything and answers a refusal as exit 2 refused boot.KEY: CODE (why); any other init error is exit 1 parent boot.KEY. Plan mode prints plan: would load module NAME, would wait for device NAME (up to Ds), would ensure mount NAME, would apply network NAME, would start service NAME or would stop service NAME, and calls nothing.

form kind key mutates what
module load verb boot.module yes module load NAME: NAME the kernel's canonical spelling, [a-z0-9][a-z0-9_]{0,54} (_, never -: virtio-net is exit 2 usage), listed in modules (else exit 126 denied module). No alias (pci:v..., fs-ext4) and no module parameter: a /etc/modprobe.d option is ignored. The init loads its dependencies first from the root-owned modules.dep and needs kernel signature enforcement. Row name, state, deps.
device wait verb boot.device no device wait NAME timeout D: NAME [a-z][a-z0-9_-]{0,31} in devices (else denied device); D whole seconds, 1s to 60s (else exit 2 usage device wait: timeout 1s to 60s). Waits until the device declared in host.json is present with the declared sysfs identity; prefer wwid or dm/uuid there, which a hostile device copies less easily than a serial. Row name, path, major, minor; refused boot.device: timeout when D runs out, device_mismatch at once for the wrong disk. Read-only, but plan mode does not call it.
mount ensure verb boot.mount yes mount ensure NAME: NAME in host_mounts (else denied host mount). A mount stage whose second word is ensure is always this verb and takes exactly one name, so mount ensure /mnt/x is exit 2 usage mount ensure NAME; no grant may list ensure as a mount source. The init mounts the declared target, nosuid,nodev unless the declaration says otherwise, through the device device wait checked (device_changed otherwise). Row name, target, fstype, state.
network apply verb boot.net yes network apply NAME: NAME in net_profiles (else denied network profile). The init applies the declared profile: it only adds addresses and routes to the link the profile selects by MAC, or starts the profile's DHCP unit. Row name, link, state, changes.
service start verb boot.start yes service start NAME: NAME [a-z][a-z0-9-]{0,62} in units_start (else denied service start), a unit with "boot": false, at most once per boot, never itself or another boot-ops unit. Row name, state, since, pid, as service status.
service stop verb boot.stop yes service stop NAME: NAME in units_stop (else denied service stop); never an essential unit; the unit is not restarted. Row as service start.

Session words

The interactive editor handles these; they never reach a script. In a script, under -c, or on piped stdin they are unknown names (exit 127). Do not put them in a script.

form kind key mutates what
why session - no why <line> explains the grant check for that line and runs nothing; bare why explains the last line.
logout session - no Ends the session, like Ctrl-D. A bare exit at the prompt does the same.
theme session - no Session colors: list, show, default/dark/light/mono, set ROLE COLOR, reset.
bind actions session - no List named editor actions.
bind keys session - no List configurable key names.
bind list session - no List bindings, optionally for MAP.
bind set session - no MAP KEY ACTION: bind a named editor action.
bind unset session - no MAP KEY: ignore a key.
bind reset session - no MAP: restore default bindings.
bind session - no bind vi or bind emacs.
abbr session - no abbr name 'text', abbr -e name, abbr: visible rewrites of a command word.
z session - no z part... goes to the most used and most recent visited directory containing each part in order, inside the file_read roots; z -l part... lists candidates. Exit 1 z: no match. In a script, exit 2 z: prompt only.
jump session - no jump name, jump save name, jump list, jump rm name: bookmarks ([a-z0-9_-]{1,32}, at most 64), checked against the roots on every use. In a script, exit 2 jump: prompt only.
syntax session - no syntax on or syntax off. The denial color stays either way.
trace session - no trace on or trace off: print each stage key before it runs. In a script use set -x.
prompt session - no prompt line (default) or prompt menu.

The editor also takes the whole line confirm off, which asks confirm off? [y + Enter / N] before it clears confirm mode.

Maintaining this reference

The implementation is authoritative. The command table lives in internal/lang/builtin.go. The embedded language, features, and verbs references include fixture-based examples checked by TestSkillExamplesAreSash; their command and expression inventories also have coverage checks. This root reference adapts that material for readers and omits fixture-specific test demonstrations. Keep both sets of documents in sync when changing syntax, command forms, limits, or error behavior.

Editor themes, keymaps, kill-ring behavior, and JSON completion tooling are described in DOCUMENTATION.md.

Explicit local execution mode

--local adds Unix process execution to the existing language. Unknown program names resolve through PATH; command PROGRAM ... forces external execution. External pipelines use |, with < and > file redirection. A trailing & backgrounds one pipeline. jobs, fg [%job], bg [%job] and wait [%job] operate on session-local job IDs. Compound background chains, typed external pipes and functions inside external process pipelines are not supported.

Local cd/pwd, source libraries and funcsave use OS-user file access. A local child inherits the environment, but environment names do not automatically become sash variables. This mode neither constructs a signed grant nor uses an agent socket. Default and --session execution retain their existing behavior.

For private terminal automation, local mode provides:

expect open NAME PROGRAM [args...]
expect match NAME literal|regex PATTERN timeout D
expect send NAME TEXT
expect resize NAME ROWS COLS
expect close NAME

Match returns matched text, status 124 on timeout, or status 1 for EOF before a match. Send adds no newline automatically. Match deadlines are positive and at most five minutes; send has a ten-second maximum deadline. There are at most 16 conversations, each with a 64 KiB unmatched-output limit and 4096-byte pattern limit. Resize dimensions are 1–1000. Close kills and reaps the conversation group. See Expect and Job control for full limits.

Local execution is refused in readiness checks, atomic transactions, recordings and parallel-language branches. Secret-valued arguments are refused. Plan mode suppresses launches; confirm mode prompts. Agent-managed jobs and expect are planned, not implemented, and are not enabled by local mode.

Local environment

Form Result or effect
export NAME = VALUE Set an environment string for later local children and PTY conversations.
getenv NAME [DEFAULT] Exact bytes, no appended newline; status 1 if absent without a default, otherwise 0. Empty means set.
unset NAME ... Remove environment names, not sash bindings; validate all names before changing any.
export APP_MODE = production
let mode = (getenv APP_MODE development)
echo $mode
unset APP_MODE

These forms are local-only and must stand alone, without redirects, backgrounding or external pipeline stages. getenv supports command capture; export/unset do not. Normal expansion applies but values are never parsed as source. Secret-valued arguments are refused. Plan skips reads as well as writes. Environment strings are not automatically secret-marked. Names use ASCII letters, digits and _, with no leading digit. Values cannot contain NUL and are limited to 128 KiB each.

Environment names do not automatically become sash bindings: read (getenv HOME) unless you have defined $HOME yourself. let does not export. export name in a library remains a declaration of public library names, not environment mutation.

Each local session snapshots its environment. Changes affect subsequent children, including PATH lookup and expect open, but do not alter other sessions or already-running programs. Unset/empty PATH has no fallback. HOME controls bare cd. Sash initializes SHELL to its executable, increments SHLVL, and maintains PWD and OLDPWD after successful cd. PWD, OLDPWD and SHLVL cannot be exported or unset. Invalid, negative or >=1000 inherited SHLVL becomes 1.

The interactive startup settings are SASH_THEME (default, dark, light, mono) and SASH_COLOR (auto, always, never). Auto respects nonempty NO_COLOR and TERM=dumb, then COLORTERM=truecolor/24bit, then TERM containing 256color, falling back to 16 colors. Always forces truecolor; never disables foreground colors. Palette changes preserve this policy. Invalid settings refuse interactive startup. These settings do not change child programs' output.

See Environment settings for complete examples and limits.

Optional Jinja2 templates

Local mode supports genuine Jinja2 as an optional backend for the existing schema-aware template workflow:

template_file settings.yaml nginx.conf.j2 nginx.conf --engine jinja2 --check
template_file settings.yaml nginx.conf.j2 nginx.conf --engine jinja2

Native templates remain the default (--engine native). Piped maps can use template FILE --engine jinja2. Add --template-root DIR to supply a bounded bundle of .j2/.jinja/.jinja2 includes, macros and base templates. Missing variables are errors; rendering errors leave the destination untouched. Plan mode renders a diff without writing. This backend is local-only and refuses tracked secrets, recordings, readiness checks, atomic blocks and parallel branches.

Install the pinned optional Python dependencies and select the interpreter with SASH_JINJA_PYTHON. See Jinja2 templates for setup, complete syntax, include rules, resource limits and a render/validate/install workflow.

Native local installer filesystem operations

In --local mode, fs provides native read, write, copy, mkdir, symlink, chmod, chown, exists, and remove operations. See INSTALLER.md for syntax, atomic-write behavior, and boundaries. Fleet fs write-atomic retains its separate granted behavior.

Binary encoding and decoding

encode FORMAT and decode FORMAT are byte filters, with formats base64, base64url, hex, base91, and experimental base122. They work in-process in agent/default mode and as native workers in local OS pipelines; no external codec program is required. Input/output are bounded to 8 MiB, with no automatic line wrapping or appended newline. Decoding errors return status 2 with no decoded output.

In local mode:

encode base91 < payload.bin > payload.b91
decode base91 < payload.b91 > restored.bin
encode base122 < payload.bin > payload.b122
decode base122 < payload.b122 > restored122.bin

In agent mode, file access still requires the corresponding grant. Local > can truncate a destination before decoding fails; use a staging file when necessary.

Expression functions include base64, unbase64, hex, unhex, plus base64url, unbase64url, base91, unbase91, base122, and unbase122:

echo [ unbase91(base91("hello")) ]
echo [ unbase122(base122("hello")) ]
echo [ hex(base122("hello")) ]

Base64 uses standard padding; Base64URL is unpadded. Pipeline decoders and the new expression decoders are strict and validate canonical tails. Hex accepts either letter case. Existing unbase64 retains its previous permissive behavior; the decode base64 filter rejects CR/LF and noncanonical unused bits. Base122's valid whitespace/control bytes are data, never stripped. Expressions preserve secret taint and consume the existing evaluation budget.

Base122 is experimental UTF-8, can contain control characters, and should be saved to files rather than copied from a terminal. These are not encryption or integrity checks. See Encoding guide for exact behavior, limits, reference compatibility, and binary-safe workflows.

Built from the sash repository's language reference (LANGUAGE_REFERENCE.md) at commit e5bf852 on branch main. The implementation is authoritative: where this page and the code disagree, the code and its tests win. The repository has no license file yet.