Home > other >  Golang - flag.Arg(0) returns index 1 instead of index 0 of arguments passed by exec.cmd
Golang - flag.Arg(0) returns index 1 instead of index 0 of arguments passed by exec.cmd

Time:12-15

I currently have something in my bar app that looks like this

flag.Parse()
str := flag.Arg(0)
fmt.println(str)

Now in my foo app I have something like this

var stdout, stderr bytes.Buffer
    cmd := exec.Cmd{
        Path:   c.Path,
        Args:   c.Args,
        Env:    c.Env,
        Stdin:  bytes.NewReader(b),
        Stdout: &stdout,
        Stderr: &stderr,
    }

    if err := cmd.Start(); err != nil {
        return err
    }

Now in the above c.Args = [1,2,3]

foo program attempts to call into bar program and bar displays 2 How do I make bar display 1 instead.

I know flag.parse ignores the first parameter. How do I tell read the first parameter (index 0) using flag.Arg()

CodePudding user response:

Cmd.Args includes the command name. flag.Arg(0) is the first argument after the command name and flags.

Fix by adding the command name to Cmd.Args.

cmd := exec.Cmd{
    Path:   c.Path,
    Args:   append([]string{c.Path}, c.Args...),
    Env:    c.Env,
    Stdin:  bytes.NewReader(b),
    Stdout: &stdout,
    Stderr: &stderr,
}
  •  Tags:  
  • go
  • Related