0

I want to access command line arguments with hyphens for example:

go run user.go -version

or

go run user.go --version

When I executing like this, I received the below error:

flag provided but not defined: -version
Usage of /tmp/go-build354377460/command-line-arguments/_obj/exe/user:
  --version string
        prints current version and exits
exit status 2

Here is my code:

 package main

import (
    "flag"
    "fmt"
)

func main() {
    var version string
    flag.StringVar(&version, "-version", "", "prints current version and exits")

    // Parse the flags
    flag.Parse()

    fmt.Println(flag.Args())
}

Any help is greatly appreciated. Thanks in advance.

2
  • What does the code look like? Do you use the standard flag library? Please provide the code of user.go stripped down to have a working repro Commented Jan 11, 2017 at 13:31
  • I have added my code in the question, please review. Thanks for the response. Commented Jan 11, 2017 at 13:32

1 Answer 1

3

Use a bool. Do not include the "-" in the flag definition.

func main() {
    var version bool
    flag.BoolVar(&version, "version", false, "prints current version and exits")
    flag.Parse()
    if version {
        fmt.Println("hello")
        return
    }
    fmt.Println(flag.Args())
}
Sign up to request clarification or add additional context in comments.

2 Comments

Tried the code. But it is not working. I need to run with the hyphen go run user.go -version like --help.
Yes it's working. I cannot get the arguments. My flag.Args() is empty array.

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.