Cmd.Output
type Cmd.Output = { status: int, statuses: Array[int], stdout: string, stderr: string }Cmd.Output is what Cmd.capture collects from a command that ran to its end. status is its status, statuses each stage's own, and stdout and stderr the outputs as text, with bytes that are not valid UTF-8 as U+FFFD. The stages' standard error interleaves as it arrived.
Details
- A nonzero status is not an error: Cmd.capture returns
Okwith the status instatus. It isErronly when the command could not be started or run to its end. stdoutandstderrhold the whole output, final newline included, unlike Cmd.read.- Output that is not valid UTF-8 has U+FFFD in
stdoutorstderr. Cmd.captureBytes gives a Cmd.OutputBytes, which holds standard output as it was written. statuseshas one entry per stage, in pipeline order. For a pipeline,statusis that of the rightmost stage that failed, or 0, and a stage before the last that SIGPIPE ended does not count.- A child that a signal ended has status
128 + n, as a shell reports it: SIGKILL is 137. On Windows the status is the exit code.
Basic examples
Capture a command's status and both outputs with Cmd.capture:
let out = try Cmd.capture(Cmd.new("sh", ["-c", "echo hello; echo oops >&2; exit 3"]))
println(out.status)
println(out.stdout.trim())
println(out.stderr.trim())3
hello
oopsA Cmd.Output prints as a record:
println(try Cmd.capture(Cmd.new("echo", ["hi"])))Cmd.Output{ status: 0, statuses: [0], stdout: "hi\n", stderr: "" }Scope
A command that writes nothing has empty outputs:
let out = try Cmd.capture(Cmd.new("true"))
println(out.stdout.isEmpty())
println(out.stderr.isEmpty())true
trueWhat input sends the command shows up in its output:
let out = try Cmd.capture(Cmd.new("tr", ["a-z", "A-Z"]), input: "shout")
println(out.stdout)SHOUTA pipeline has one entry in statuses per stage. Its status is the rightmost failure:
let out = try Cmd.capture(Cmd.pipe([
Cmd.new("sh", ["-c", "echo a; exit 2"]),
Cmd.new("cat"),
Cmd.new("cat"),
]))
println(out.status)
println(out.statuses)2
[2, 0, 0]A command that a signal ended has status 128 + n. SIGKILL is signal 9:
let out = try Cmd.capture(Cmd.new("sh", ["-c", "kill -KILL $$"]))
println(out.status)
println(out.statuses)137
[137]A stage that stopped because a later stage stopped reading shows SIGPIPE's 141 in statuses, but does not set status:
let out = try Cmd.capture(Cmd.pipe([Cmd.new("yes"), Cmd.new("head", ["-n", "1"])]))
println(out.status)
println(out.statuses)
println(out.stdout)0
[141, 0]
yOutput that is not UTF-8 has the bad byte as U+FFFD in stdout; Cmd.captureBytes keeps it exact:
let c = Cmd.new("printf", ["\\377ok"])
println((try Cmd.capture(c)).stdout == "\u{FFFD}ok")
println((try Cmd.captureBytes(c)).stdout)true
Bytes(ff 6f 6b)Cmd.Output is a record type, so a literal builds one, for example to test a function that takes an output without running a command:
func summary(out: Cmd.Output): string {
if out.status == 0 { "ok" } else { "failed (${out.status}): ${out.stderr.trim()}" }
}
let failed = Cmd.Output{
status: 1,
statuses: [1],
stdout: "",
stderr: "disk full\n",
}
println(summary(failed))failed (1): disk fullApplications
Tell grep's three outcomes apart: 0 for a match, 1 for none, and 2 or more for trouble:
func search(pattern: string, text: string): Result[bool, Error] {
let out = try Cmd.capture(Cmd.new("grep", ["-q", pattern]), input: text)
if out.status > 1 {
return Result.fail("grep: ${out.stderr.trim()}")
}
Result.ok(out.status == 0)
}
println(search("fix", "fix typo\nadd tests\n"))
println(search("docs", "fix typo\nadd tests\n"))
println(search("[", "fix typo\n") is Err)Ok{ value: true }
Ok{ value: false }
trueReport a failed step with what it wrote to standard error:
func step(name: string, script: string): Result[string, Error] {
let out = try Cmd.capture(Cmd.new("sh", ["-c", script]))
if out.status != 0 {
return Result.fail("${name} failed with status ${out.status}: ${out.stderr.trim()}")
}
Result.ok(out.stdout.trim())
}
println(step("version", "echo 1.4.2"))
println(step("lint", "echo 'main.ant:3: unused variable' >&2; exit 1"))Ok{ value: "1.4.2" }
Err{ error: Error{ message: "lint failed with status 1: main.ant:3: unused variable" } }Find which stage of a pipeline failed:
let stages = [Cmd.new("echo", ["data"]), Cmd.new("grep", ["missing"]), Cmd.new("cat")]
let out = try Cmd.capture(Cmd.pipe(stages))
let failed = out.statuses.findIndex({ x != 0 })
if failed != null {
println("stage ${failed + 1} (${stages[failed].program}) exited ${out.statuses[failed]}")
}stage 2 (grep) exited 1Properties and relations
stdout is the output Cmd.captureBytes gives, decoded as text, and stderr is the same in both:
for script in ["echo plain", "printf 'caf\\303\\251'", "printf '\\377\\376'", "echo err >&2"] {
let c = Cmd.new("sh", ["-c", script])
let out = try Cmd.capture(c)
let raw = try Cmd.captureBytes(c)
assert(out.stdout == String.fromBytesLossy(raw.stdout))
assert(out.stderr == raw.stderr)
}For a single command, statuses holds only status:
for code in [0, 1, 7] {
let out = try Cmd.capture(Cmd.new("sh", ["-c", "exit ${code}"]))
assert(out.status == code)
assert(out.statuses == [code])
}Cmd.read returns stdout with one final newline removed:
let c = Cmd.new("printf", ["a\\nb\\n\\n"])
let out = try Cmd.capture(c)
assert(out.stdout == "a\nb\n\n")
assert(try Cmd.read(c) == "a\nb\n")Possible issues
try does not stop on a failing command, since a nonzero status is still Ok. Check status:
let out = try Cmd.capture(Cmd.new("false"))
println("still here, status ${out.status}")still here, status 1stdout ends with the command's newline, so comparing it to a bare word fails. Trim it, or use Cmd.read:
let out = try Cmd.capture(Cmd.new("echo", ["yes"]))
println(out.stdout == "yes")
println(out.stdout.trim() == "yes")false
trueA command that cannot be started gives no Cmd.Output at all, but an Err:
let result = Cmd.capture(Cmd.new("no-such-program"))
println(result is Err)trueSee also
Cmd.capture · Cmd.read · Cmd.readBytes · Cmd.run · Cmd.pipe · Cmd.Pipeline · String.fromBytesLossy
