Command-line flags
are a common way to specify options for command-line
programs. For example, in |
|
package main
|
|
Go provides a |
import "flag"
import "fmt"
|
func main() {
|
|
Basic flag declarations are available for string,
integer, and boolean options. Here we declare a
string flag |
wordPtr := flag.String("word", "foo", "a string")
|
This declares |
numbPtr := flag.Int("numb", 42, "an int")
boolPtr := flag.Bool("fork", false, "a bool")
|
It’s also possible to declare an option that uses an existing var declared elsewhere in the program. Note that we need to pass in a pointer to the flag declaration function. |
var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")
|
Once all flags are declared, call |
flag.Parse()
|
Here we’ll just dump out the parsed options and
any trailing positional arguments. Note that we
need to dereference the points with e.g. |
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numbPtr)
fmt.Println("fork:", *boolPtr)
fmt.Println("svar:", svar)
fmt.Println("tail:", flag.Args())
}
|
To experiment with the command-line flags program it’s best to first compile it and then run the resulting binary directly. |
$ go build command-line-flags.go
|
Try out the built program by first giving it values for all flags. |
$ ./command-line-flags -word=opt -numb=7 -fork -svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: []
|
Note that if you omit flags they automatically take their default values. |
$ ./command-line-flags -word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []
|
Trailing positional arguments can be provided after any flags. |
$ ./command-line-flags -word=opt a1 a2 a3
word: opt
...
tail: [a1 a2 a3]
|
Note that the |
$ ./command-line-flags -word=opt a1 a2 a3 -numb=7
word: opt
numb: 42
fork: false
svar: bar
trailing: [a1 a2 a3 -numb=7]
|
Use |
$ ./command-line-flags -h
Usage of ./command-line-flags:
-fork=false: a bool
-numb=42: an int
-svar="bar": a string var
-word="foo": a string
|
If you provide a flag that wasn’t specified to the
|
$ ./command-line-flags -wat
flag provided but not defined: -wat
Usage of ./command-line-flags:
...
|
Next we’ll look at environment variables, another common way to parameterize programs. |
Previous example: Command-Line Arguments.
Next example: Environment Variables.