Command-line arguments and flags

The os.Args variable holds the command-line arguments โ€“ starting with the program name โ€“ which are passed to a Go program.

func main() {
    if len(os.Args) != 3 {
        fmt.Println("Usage:", os.Args[0], "PATTERN", "FILE")
    pattern := os.Args[1]
    file := os.Args[2]
    // ...
$ go build grep.go
$ ./grep
Usage: ./grep PATTERN FILE

Flag parsing

The flag package implements basic command-line flag parsing.

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share this page: