Help needed - os.exec

65 views
Skip to first unread message

R Srinivasan

unread,
Apr 5, 2020, 6:35:51 PM4/5/20
to golang-nuts
I cannot figure the error in the following.
package main

import (
"io"
"os"
"os/exec"
"strings"
)

func Run(args []string) {
lf, _ := os.Create("lf.log")
defer lf.Close()
cmd := exec.Command(args[0], strings.Join(args[1:], " "))
stderr, _ := cmd.StderrPipe()
cmd.Start()
io.Copy(lf, stderr)
cmd.Wait()
}

func main() {
args := []string{"go", "build", "./"}
Run(args)
}

I can execute go build ./ and get an executable. However when I run it I get the following in the logfile:

cat lf.log go build ./: unknown command Run 'go help build' for usage.

I exected that the "exec" will just execute go build ./

I did rename the exe to something else before running it.

Anyone can spot the error?

Thanks, srini

PS - I am not sure if it matters but I am on a Mac and use go version go1.13.6 darwin/amd64

burak serdar

unread,
Apr 5, 2020, 6:47:48 PM4/5/20
to R Srinivasan, golang-nuts
On Sun, Apr 5, 2020 at 4:36 PM R Srinivasan <s...@srin.me> wrote:
>
> I cannot figure the error in the following.
> cmd := exec.Command(args[0], strings.Join(args[1:], " "))

Do not join the args. You're passing one arg, "build ./", instead of
two args "build" "./" to exec. Instead:

cmd := exec.Command(args[0], args[1:]...)




> stderr, _ := cmd.StderrPipe()
> cmd.Start()
> io.Copy(lf, stderr)
> cmd.Wait()
> }
>
> func main() {
> args := []string{"go", "build", "./"}
> Run(args)
> }
>
> I can execute go build ./ and get an executable. However when I run it I get the following in the logfile:
>
> cat lf.log go build ./: unknown command Run 'go help build' for usage.
>
> I exected that the "exec" will just execute go build ./
>
> I did rename the exe to something else before running it.
>
> Anyone can spot the error?
>
> Thanks, srini
>
> PS - I am not sure if it matters but I am on a Mac and use go version go1.13.6 darwin/amd64
>
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a492a5a4-2fc1-4bd4-aadc-ed6ec5e45609%40googlegroups.com.

Ian Lance Taylor

unread,
Apr 5, 2020, 6:54:57 PM4/5/20
to R Srinivasan, golang-nuts
Besides other comments, always check your error returns. Do that
before you ask for help on any program. Thanks.

Ian
Reply all
Reply to author
Forward
0 new messages