| 1 | # getopt [](https://godoc.org/git.sr.ht/~sircmpwn/getopt) [](https://builds.sr.ht/~sircmpwn/getopt) |
| 2 | |
| 3 | A POSIX-compatible getopt implementation for Go, because POSIX getopt is The |
| 4 | Correct Way to interpret arguments to command line utilities. |
| 5 | |
| 6 | Please send patches/bugs/feedback to |
| 7 | [~sircmpwn/[email protected]](https://lists.sr.ht/~sircmpwn/public-inbox). |
| 8 | |
| 9 | ## Example Usage |
| 10 | |
| 11 | ```go |
| 12 | import ( |
| 13 | "os" |
| 14 | "git.sr.ht/~sircmpwn/getopt" |
| 15 | ) |
| 16 | |
| 17 | func main() { |
| 18 | opts, optind, err := getopt.Getopts(os.Args, "abc:d:") |
| 19 | if err != nil { |
| 20 | panic(err) |
| 21 | } |
| 22 | for _, opt := range opts { |
| 23 | switch opt.Option { |
| 24 | case 'a': |
| 25 | println("Option -a specified") |
| 26 | case 'b': |
| 27 | println("Option -b specified") |
| 28 | case 'c': |
| 29 | println("Option -c specified: " + opt.Value) |
| 30 | case 'd': |
| 31 | println("Option -d specified: " + opt.Value) |
| 32 | } |
| 33 | } |
| 34 | println("Remaining arguments:") |
| 35 | for _, arg := range os.Args[optind:] { |
| 36 | println(arg) |
| 37 | } |
| 38 | } |
| 39 | ``` |
| 40 | |
| 41 | A [flag](https://golang.org/pkg/flag/)-like interface is also supported. |
| 42 | |
| 43 | ```go |
| 44 | import ( |
| 45 | "git.sr.ht/~sircmpwn/getopt" |
| 46 | ) |
| 47 | |
| 48 | func main() { |
| 49 | a := getopt.Bool("a", false, "turn on option a") |
| 50 | b := getopt.Int("b", 1, "set b to a numerical value") |
| 51 | var opt string |
| 52 | getopt.StringVar(&opt, "c", "", "let c be specified string") |
| 53 | |
| 54 | err := getopt.Parse() |
| 55 | if err != nil { |
| 56 | panic(err) |
| 57 | } |
| 58 | |
| 59 | print("Value of a: ") |
| 60 | println(*a) |
| 61 | print("Value of b: ") |
| 62 | println(*b) |
| 63 | println("Value of c: " + opt) |
| 64 | |
| 65 | println("Remaining arguments:") |
| 66 | for _, arg := range getopt.Args() { |
| 67 | println(arg) |
| 68 | } |
| 69 | } |
| 70 | ``` |