Cmd.run
func Cmd.run(c: Cmd | Cmd.Pipeline, ctx: Context | null = null): Result[int, Error]Cmd.run runs c in the foreground, with the program's own standard input, output and error, so a pager, an editor or ssh can use the terminal, and returns its status, nonzero included. While it runs the ant command holds back Ctrl-C, which every stage gets and decides on, and passes it on when the last stage dies of it. It is Err when a stage could not be started, and when ctx is done, which kills every stage.
Details
- A nonzero status is
Ok, notErr:Cmd.runfails only when a stage cannot be started orctxends. Check the status yourself. - The command writes straight to the program's standard output and error, and reads its standard input. Nothing is captured; use Cmd.read or Cmd.capture for the output.
- There is no shell:
argsarrive as they are, with no globbing, variables, or pipes. - A pipeline's status is that of the rightmost stage that failed, or 0. Only its first stage reads standard input.
- Where the host has signals, a child that a signal ended has status
128 + n, so SIGKILL is137and Ctrl-C is130.
Basic examples
Cmd.run(c) runs a command, lets its output through, and returns its status:
let status = try Cmd.run(Cmd.new("echo", ["hello"]))
println("status ${status}")hello
status 0A command that fails still gives Ok of its status:
let status = try Cmd.run(Cmd.new("sh", ["-c", "exit 3"]))
println("status ${status}")status 3Scope
A pipeline from Cmd.pipe runs its stages at once, and the last one writes to standard output:
let unique = Cmd.pipe([Cmd.new("printf", ["b\\na\\nb\\n"]), Cmd.new("sort", ["-u"])])
let status = try unique.run()
println("status ${status}")a
b
status 0The command reads the program's own standard input:
try Cmd.new("sort").run()apple
peardir runs the command in another directory:
try Cmd.new("ls", dir: "notes").run()todo.txtenv is the whole environment of the command. To add one variable, start from Os.environ:
let env = Os.environ()
env["GREETING"] = "hello"
try Cmd.new("sh", ["-c", "echo $GREETING"], env: env).run()helloA program that cannot be started is Err:
let result = Cmd.new("no-such-program").run()
println(result.isOk())falseNamed arguments
ctx
When ctx ends while the command runs, Cmd.run kills every stage and returns Err with the context's reason:
let ctx = Context.new(timeout: 100ms)
let result = Cmd.new("sleep", ["10"]).run(ctx: ctx)
println(result)Err{ error: Error{ message: "timeout" } }A context that is already done starts nothing:
let ctx = Context.new()
ctx.cancel()
println(Cmd.new("echo", ["never printed"]).run(ctx: ctx))Err{ error: Error{ message: "cancelled" } }Applications
Run build steps in order, log each, and stop at the first that fails:
let steps = [
Cmd.new("echo", ["compiling"]),
Cmd.new("sh", ["-c", "echo testing; exit 1"]),
Cmd.new("echo", ["deploying"]),
]
for step in steps {
println("+ ${step.string()}")
let status = try step.run()
if status != 0 {
println("failed with status ${status}")
break
}
}+ echo compiling
compiling
+ sh -c 'echo testing; exit 1'
testing
failed with status 1Exit with a failed command's status, and go on when it succeeds:
let status = try Cmd.new("sh", ["-c", "echo working; exit 3"]).run()
if status != 0 { Os.exit(status) }
println("done")workingTurn a nonzero status into an error, so try stops the script:
func check(c: Cmd): Result[void, Error] {
let status = try c.run()
if status != 0 {
return Result.fail("${c.string()}: exit status ${status}")
}
Result.ok(void)
}
try check(Cmd.new("true"))
try check(Cmd.new("false"))
println("not reached")Properties and relations
Cmd.run returns the status that Cmd.capture reports, without capturing the output:
let c = Cmd.new("sh", ["-c", "exit 4"])
let output = try c.capture()
let status = try c.run()
assert(status == output.status)A pipeline's status is that of its rightmost failed stage, so a later stage that succeeds does not hide a failure:
func exitWith(n: int): Cmd {
Cmd.new("sh", ["-c", "exit ${n}"])
}
let status = try Cmd.pipe([exitWith(2), exitWith(3), Cmd.new("true")]).run()
assert(status == 3)A stage before the last that SIGPIPE ends does not count:
let firstLine = Cmd.pipe([Cmd.new("yes"), Cmd.new("head", ["-n", "1"])])
let status = try firstLine.run()
assert(status == 0)yWhere the host has signals, a child that a signal ends has status 128 + n:
let status = try Cmd.new("sh", ["-c", "kill -9 $$"]).run()
assert(status == 128 + 9)Possible issues
try does not stop on a nonzero status, since that is Ok. Compare the status:
let status = try Cmd.new("false").run()
if status != 0 {
println("failed with status ${status}")
}failed with status 1No shell reads the arguments, so variables and globs stay as written:
try Cmd.new("echo", ["$HOME", "*.txt"]).run()$HOME *.txtFor the same reason a whole command line in program names a program that does not exist. Split it into program and args:
let result = Cmd.new("echo hello").run()
println(result.isOk())falseAn env that is not built from Os.environ() leaves the command only those variables:
try Cmd.new("env", env: Map{ "GREETING": "hi" }).run()GREETING=hiThe output is not returned. To use what a command prints, call Cmd.read:
let text = try Cmd.read(Cmd.new("echo", ["hello"]))
println(text.toUpper())HELLOWhat the program has already read ahead from standard input stays the program's, so a command run after the program read a line does not see the rest. To hand the rest on, read it and pass it as input to Cmd.read or Cmd.capture:
let header = try File.readLine(Os.stdin())
println("header: ${header}")
try Cmd.new("cat").run()
println("cat saw nothing")header: name
cat saw nothingWhile Cmd.run waits, the program holds back Ctrl-C for the whole process, so a server that waits for Os.interrupt runs its commands with Cmd.start instead.
A pipeline of no commands panics:
let empty = Cmd.Pipeline{ cmds: [] }
let result = empty.run() // panic: Cmd.run needs a pipeline of at least one commandSee also
Cmd.new, Cmd.pipe, Cmd.read, Cmd.capture, Cmd.start, Cmd.string, Os.exit, Os.environ
