Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Comments¶
exec.Command
takes a shell command and optional arguments passed to the shell command, e.g.,exec.Command("ls", "-lha")
. It does not work if you pass a shell command with arguments as a single string toexec.Command
, e.g.,exec.Command("ls -lha")
does not work. There are a few situations where it is appealing to pass a shell command with arguments as a single string toexec.Command
.- You want to run a compound shell command
which leverages pipe (
|
),&&
,||
, etc. Even though you can break such a compound shell command into multiple smaller ones and then run each of them usingexec.Command
, it can be much more convenient to be able to run a compound shell command directly. Use provides a shell command as a single string for your Golang application to run.
It might not be trivia to parse a string shell command to its array representation.Fortunately, there is one way around this problem. You can explicitly call a shell and pass a command (with arguments) to it, e.g.,
exec.Command("bash", "-c", "ls -lha")
.
- You want to run a compound shell command
which leverages pipe (
import "fmt"
import "reflect"
import "os"
import "os/exec"
cmd := exec.Command("ls")
cmd
reflect.TypeOf(cmd)
err := cmd.Run()
err
err == nil
out, err := exec.Command("ls").Output()
err == nil
out
string(out[:])
Compound Command¶
exec.Command("ls", "|", "wc", "-l").Output()
exec.Command("bash", "-c", "ls -lha")
Environment Variables¶
cmd = exec.Command("bash", "-c", "ls -lha")
os.Environ()
cmd.Env = append(os.Environ(),
"FOO=duplicate_value", // ignored
"FOO=actual_value", // this value is used
)
Get Detailed Error Message¶
Please refer to How to debug "exit status 1" error when running exec.Command in Golang for detailed discussions.
References¶
os.Getenv("PATH")
os.LookupEnv("PATH")