在Go中调用exec.Cmd()后修改参数

I am trying to run command with exec.Cmd(command, flags...) and want to have the flexibility to modify the arguments before calling the cmd.Run() function.

for example:

cmd := exec.Command("echo", "hello world")
cmd.Env = []string{"env1=1"}
cmd.Args = []string{"echo2", "oh wait I changed my mind"}
cmd.Run()

The above code seems to be always running echo hello world but not echo2 oh wait I changed my mind

Am I correct to expect echo2 to be run instead of echo?

When changing the command to execute, you must also set cmd.Path as in exec.Command.

cmd := exec.Command("echo", "hello world")
cmd.Env = []string{"env1=1"}
cmd.Args = []string{"echo2", "oh wait I changed my mind"}

lp, err := exec.LookPath("echo2")
if err != nil {
    // handle error
}

cmd.Path = lp
if err := cmd.Run(); err != nil {
    // handle error
}