Passing CLI arguments to excutables with 'go run'

Viewed 25301

I have a program readfile.go and I want to give the command line argument os.Args[1] also as readfile.go.

However 'go run' thinks that it is an additional argument to itself rather than to the output executable. Is there a flag which can tell 'go run' that this is an argument to executable?

mvaidya@mvaidya-VirtualBox:~/junkeork$ go run readfile.go readfile.go
package main: case-insensitive file name collision: "readfile.go" and "readfile.go"
mvaidya@mvaidya-VirtualBox:~/junkeork$

Error:

package main: case-insensitive file name collision: "readfile.go" and "readfile.go"

3 Answers

To avoid the ambiguity of getting twice readfile.go, I advise you to use named flags. This will solve the problem too.

Example:

package main

import (
    "flag"
    "fmt"
)

func main() {
    cmd := flag.String("cmd", "", "")
    flag.Parse()
    fmt.Printf("my cmd: \"%v\"\n", string(*cmd))
}

Don't forget using flag.Parse() to retrieve the command line arguments

You can pass args to the go run command this way: go run .\main.go -cmd main.go and you'll get as output:

my cmd: "main.go"

I hope this can help other.

The answer by janos can work well with unnamed args., for named args.:

go run [file].go -arg1Name arg1Value -arg2Name arg2Value.....
Eg, go run main.go -x 2 -y 5 ; x and y are arg. names
Related