exec
The exec module runs external commands — either through a shell or directly with an argument list — captures their combined stdout/stderr, reads exit codes, and provides quick access to environment variables and the working directory. Import it with import exec.
Functions
| Function | Signature | Description |
|---|---|---|
run | exec.run(cmd: string) → string | run cmd via sh -c and return combined stdout/stderr |
runArgs | exec.runArgs(cmd: string, args: string[]) → string | run a program directly (no shell) with args, returning combined output |
exitCode | exec.exitCode(cmd: string) → int | run cmd via shell and return its exit code (-1 if it could not run) |
env | exec.env(key: string) → string | read an environment variable |
setEnv | exec.setEnv(key: string, val: string) → bool | set an environment variable |
cwd | exec.cwd() → string | current working directory |
exists | exec.exists(cmd: string) → bool | true if cmd is found on PATH |
Example
import exec
if exec.exists("git") {
let out = exec.run("git rev-parse --short HEAD")
print(out)
}
// run a program directly with arguments, no shell parsing
print(exec.runArgs("echo", ["hello", "world"]))
// check whether a command succeeded
if exec.exitCode("test -f config.toml") == 0 {
print("config present")
}