[ACCEPTED]-getopt-like behavior in Go-go

Accepted answer
Score: 24

Google has created a getopt package (import "github.com/pborman/getopt") which provides 2 the more standard command line parsing (vs 1 the 'flag' package).

package main

import (

func main() {
    optName := getopt.StringLong("name", 'n', "", "Your name")
    optHelp := getopt.BoolLong("help", 0, "Help")

    if *optHelp {

    fmt.Println("Hello " + *optName + "!")


$ ./hello --help
Usage: hello [--help] [-n value] [parameters ...]
     --help        Help
 -n, --name=value  Your name

$ ./hello --name Bob
Hello Bob!
Score: 15

Use the 'flag' package: http://golang.org/pkg/flag/. It doesn't do 3 double-dash arguments, however. There isn't 2 anything that exactly mimics GNU getopt 1 behaviour (yet.)

Score: 11

From the section "Command Line UI", you 3 have several libraries able to parse getopt-long parameters.

I 2 tried, with a Go1.0.2:


package main

import (
    goopt "github.com/droundy/goopt"

func main() {
    goopt.NoArg([]string{"--abc"}, "abc param, no value", noabc)

    goopt.Description = func() string {
        return "Example program for using the goopt flag library."
    goopt.Version = "1.0"
    goopt.Summary = "goopt demonstration program"

func noabc() error {
    fmt.Println("You should have an --abc parameter")
    return nil

Other default 1 parameters provided with goopt:

 --help               Display the generated help message (calls Help())
 --create-manpage     Display a manpage generated by the goopt library (uses Author, Suite, etc)
 --list-options       List all known flags
Score: 7

go-flags is very complete, BSD licensed, and has 1 a clear example.

var opts struct {
      DSomething string `short:"d" description:"Whatever this is" required:"true"`
      ABC bool `long:"abc" description:"Something"`

fileArgs, err := flags.Parse(&opts)

if err != nil {
Score: 5

Another option is Kingping which provides support 6 for all the standard goodies you have come 5 to expect from a modern command line parsing 4 library. It has --help in multiple formats, sub-commands, requirements, types, defaults, etc. It's 3 also still under development. It seems like 2 the other suggestions here haven't been 1 updated in a while.

package main

import (

var (
  app      = kingpin.New("chat", "A command-line chat application.")
  debug    = app.Flag("debug", "Enable debug mode.").Bool()
  serverIP = app.Flag("server", "Server address.").Default("").IP()

  register     = app.Command("register", "Register a new user.")
  registerNick = register.Arg("nick", "Nickname for user.").Required().String()
  registerName = register.Arg("name", "Name of user.").Required().String()

  post        = app.Command("post", "Post a message to a channel.")
  postImage   = post.Flag("image", "Image to post.").File()
  postChannel = post.Arg("channel", "Channel to post to.").Required().String()
  postText    = post.Arg("text", "Text to post.").Strings()

func main() {
  switch kingpin.MustParse(app.Parse(os.Args[1:])) {
  // Register user
  case register.FullCommand():

  // Post message
  case post.FullCommand():
    if *postImage != nil {
    text := strings.Join(*postText, " ")
    println("Post:", text)

And the --help output:

$ chat --help
usage: chat [<flags>] <command> [<flags>] [<args> ...]

A command-line chat application.

  --help              Show help.
  --debug             Enable debug mode.
  --server=  Server address.

  help [<command>]
    Show help for a command.

  register <nick> <name>
    Register a new user.

  post [<flags>] <channel> [<text>]
    Post a message to a channel.
Score: 4

I made it just for you:

package main

import (

func main() {
  for i, arg := range os.Args {
    if arg == "-help" {
      fmt.Printf ("I need somebody\n")
    }else if arg == "-version" {
      fmt.Printf ("Version Zero\n")
    } else {
      fmt.Printf("arg %d: %s\n", i, os.Args[i])

see also https://play.golang.org/p/XtNXG-DhLI


$ ./8.out -help -version monkey business
I need somebody
Version Zero
arg 3: monkey
arg 4: business


Score: 3

I think what you want is docopt. I'll just 1 refer you to an earlier answer I posted for the details.

Score: 2

As a simple library, you have since August 12 2017 github.com/rsc/getopt

To use, define flags as usual with 11 package flag. Then introduce any aliases 10 by calling getopt.Alias:

getopt.Alias("v", "verbose")

Or call getopt.Aliases to define a list of 9 aliases:

    "v", "verbose",
    "x", "xylophone",


In general Go flag parsing is 8 preferred for new programs, because it is 7 not as pedantic about the number of dashes 6 used to invoke a flag (you can write -verbose or 5 --verbose, and the program does not care).

This package 4 is meant to be used in situations where, for 3 legacy reasons, it is important to use exactly 2 getopt(3) syntax, such as when rewriting in Go an 1 existing tool that already uses getopt(3).

Score: 0

One can simply use Golang own library "flag".

It 5 has pretty much code to create CLI like 4 application in GoLang. for Example :

srcDir := flag.String("srcDir", "", "Source directory of the input csv file.")

The 3 above String method of flag library will 2 expect one argument from command prompt.

Go 1 to https://golang.org/pkg/flag/ for more reading.

Happy Learning...

More Related questions