Cmd.new
func Cmd.new(program: string, args: Array[string] = [], dir: string | null = null, env: Map[string, string] | null = null): CmdCmd.new returns the Cmd of program with args, run in dir and with env when they are given.
Details
Cmd.newruns nothing. It returns aCmdrecord, the same as the literalCmd{ program, args }with the defaults filled in. Cmd.run, Cmd.read, Cmd.capture and Cmd.start run it.- No shell runs the command. Each element of
argsreaches the program as it is: no globbing, no$VARexpansion, no splitting on spaces. - A
programwithout a path separator is looked up in the program's ownPATH, never in thePATHofenv. Aprogramwith a separator is taken relative todir. envis the child's whole environment. To add one variable, start fromOs.environ().- The
Cmdholds theargsarray it was given, not a copy, as any record does.
Basic examples
Make a command from a program and its arguments:
Cmd.new("git", ["rev-parse", "--short", "HEAD"]) // Cmd{ program: "git", args: ["rev-parse", "--short", "HEAD"], dir: null, env: null }
Cmd.new("ls") // Cmd{ program: "ls", args: [], dir: null, env: null }Run it with a function of Cmd:
let out = try Cmd.read(Cmd.new("echo", ["hello", "world"]))
println(out)hello worldScope
Each argument arrives as one argument, exactly as written. A shell would expand * and $HOME, and split a b in two:
let c = Cmd.new("sh", ["-c", `printf '[%s]\n' "$@"`, "sh", "*", "$HOME", "a b"])
println(try Cmd.read(c))[*]
[$HOME]
[a b]The result is a record, so its fields read and change like any record's:
let build = Cmd.new("go", ["build"])
build.args.push("./...")
println(build.program)
println(build.string())go
go build ./...Named arguments
args
args can be named, which keeps the call readable when dir or env follows it. The two calls make the same command:
Cmd.new("ls", args: ["-a"], dir: "/") == Cmd.new("ls", ["-a"], "/") // truedir
dir sets the working directory of the child. Without it the child runs in the program's working directory:
println(try Cmd.read(Cmd.new("pwd", dir: "/")))/env
env replaces the child's environment. Copy Os.environ() and add to it to keep PATH, HOME and the rest:
let env = Os.environ()
env.set("GREETING", "hi")
println(try Cmd.read(Cmd.new("sh", ["-c", `echo "$GREETING"`], env: env)))hiApplications
A helper that returns a Cmd keeps how a tool is called in one place and leaves how to run it to the caller:
func git(repo: string, args: Array[string]): Cmd {
Cmd.new("git", ["-C", repo, ...args])
}
println(git("/srv/app", ["log", "-n", "1"]).string())git -C /srv/app log -n 1Build the arguments from data before running. Options come before the file names:
let files = ["notes.txt", "todo list.txt"]
let verbose = true
let flags: Array[string] = if verbose { ["-v"] } else { [] }
let c = Cmd.new("rm", [...flags, "--", ...files])
println(c.string())rm -v -- notes.txt 'todo list.txt'Run one command per input:
let words = ["one", "two", "three"]
for c in words.map({ Cmd.new("echo", [x.toUpper()]) }) {
println(try Cmd.read(c))
}ONE
TWO
THREEProperties and relations
Cmd.new is the record literal with its defaults:
let c = Cmd.new("ls", ["-l"])
assert(c == Cmd{ program: "ls", args: ["-l"] })
assert(c.dir == null && c.env == null)Making a command checks neither the program nor dir; running it does:
let c = Cmd.new("no-such-program")
assert(c.program == "no-such-program")
assert(!Cmd.read(c).isOk())
let d = Cmd.new("pwd", dir: "no-such-dir")
assert(!Cmd.read(d).isOk())Possible issues
A command line in one string is a program name, not a command. No shell splits it, so the lookup fails:
println(Cmd.read(Cmd.new("echo hi")).isOk())
println(try Cmd.read(Cmd.new("echo", ["hi"])))false
hiPass the line to sh -c only when you want a shell, with its quoting and expansion.
dir does not change where a program without a path separator is found. hello is looked up in PATH, not in tools; write ./hello:
println(Cmd.read(Cmd.new("hello", dir: "tools")).isOk())
println(try Cmd.read(Cmd.new("./hello", dir: "tools")))false
helloThe command shares the array passed as args. Changing the array afterwards changes the command:
let args = ["a"]
let c = Cmd.new("echo", args)
args.push("b")
println(try Cmd.read(c))a bPass a copy, such as [...args], to keep the command as it was.
A map with only the new variable leaves the child without the rest of the environment, such as HOME:
let c = Cmd.new("sh", ["-c", `echo "[$GREETING] [$HOME]"`], env: Map{ GREETING: "hi" })
println(try Cmd.read(c))[hi] []See also
Cmd · Cmd.pipe · Cmd.string · Cmd.run · Cmd.read · Cmd.capture · Cmd.start · Os.which · Os.environ
