Run a command and capture its output
Run another program and use what it prints.
- Build the command with Cmd.new: the program, then its arguments as an array. No shell runs it, so each argument reaches the program as it is.
- Call Cmd.read to get what the command prints, without its final line break. Any nonzero status is an
Err. - Call Cmd.capture instead when a nonzero status is an answer, or when you need standard error too.
- Use
tryto return theErr, and Result.wrapErr to say what the program was doing.
Read what a command prints
This script prints the TODO lines of notes.txt that grep finds:
let todos = try Cmd.read(Cmd.new("grep", ["TODO", "notes.txt"]))
for line in todos.lines() {
println(line.trimPrefix("TODO: "))
}call Ann
pay rentCall Cmd.readBytes for output that is not text.
Handle a command that fails
When the command exits with a nonzero status, Cmd.read returns an Err whose message names the program and its status, followed by what it wrote to standard error. Add context with Result.wrapErr:
let c = Cmd.new("sh", ["-c", "echo 'disk full' >&2; exit 3"])
let saved = Cmd.read(c) | Result.wrapErr("save report")
println(saved)Err{ error: Error{ message: "save report: sh: exit status 3: disk full" } }With try, a script stops there, writes the message to standard error, and exits with status 1:
let c = Cmd.new("sh", ["-c", "echo 'disk full' >&2; exit 3"])
let saved = try (Cmd.read(c) | Result.wrapErr("save report"))
println(saved)A program that cannot be found is an Err too. Call Os.which first to report it your own way; it returns null when the PATH has no such program:
if Os.which("convert") == null {
return Result.fail("install ImageMagick to resize images")
}Keep the status and both outputs
grep exits with 1 when nothing matches and with 2 on an error, so Cmd.read fails on both. Cmd.capture returns Ok for every status, with the status, standard output, and standard error in one Cmd.Output record:
func countTodos(path: string): Result[int, Error] {
let out = try Cmd.capture(Cmd.new("grep", ["-c", "TODO", path]))
if out.status > 1 {
return Result.fail("grep ${path}: ${out.stderr.trim()}")
}
Result.ok(out.stdout.trim().toInt() ?? 0)
}
for path in ["notes.txt", "clean.txt"] {
println("${path}: ${try countTodos(path)}")
}notes.txt: 2
clean.txt: 0The outputs keep their final line breaks, so trim them with String.trim before you compare or convert them.
Give the command input
Pass the text the command reads from standard input as input:. Without it, the command reads nothing:
let sorted = try Cmd.read(Cmd.new("sort", ["-u"]), input: "pear\napple\npear\n")
println(sorted.lines())["apple", "pear"]Choose the directory and environment
Give dir: to run the command in another directory. env: is the command's whole environment, so start from Os.environ and add to the copy with Map.set:
let env = Os.environ()
env.set("GREETING", "hello")
let c = Cmd.new("sh", ["-c", "echo \"$GREETING\" $(ls)"], dir: "reports", env: env)
println(try Cmd.read(c))hello today.txtLimit how long it runs
Pass a context with a deadline as ctx:. When it ends first, the command is killed and the result is an Err with the context's reason:
let ctx = Context.new(100ms)
println(Cmd.read(Cmd.new("sleep", ["5"]), ctx: ctx))Err{ error: Error{ message: "timeout" } }Stop or time out a process shows more.
Log the command
Cmd.string writes the command as a shell would need it quoted, and leaves out dir and env:
let c = Cmd.new("grep", ["-c", "to do", "notes.txt"])
println("running ${Cmd.string(c)}")running grep -c 'to do' notes.txtSee also
Cmd.new · Cmd.read · Cmd.readBytes · Cmd.capture · Cmd.Output · Cmd.string · Os.which · Os.environ · Result.wrapErr · Result.fail · Context.new · Map.set · String.lines · String.trim · String.trimPrefix · String.toInt · Cmd.run · Stream a command's output · Build a pipeline · Stop or time out a process
