2

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?

2
  • Note that when you call exec.Command, the first parameter is the command, subsequent parameters are the args. So your code changes the actual execution to (shell equivalent) echo "echo2" "oh wait I changed my mind". To change the command to execute, not just its args, you have to update cmd.Path. Commented Dec 6, 2017 at 15:07
  • Ah thank you @Adrian. It seems so :). Commented Dec 6, 2017 at 15:54

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer Cerise and @Tom

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.