Go by Example

Command-Line Arguments

os.Args provides raw access to command-line arguments as a string slice, with os.Args[0] holding the program name as invoked and os.Args[1:] holding the user-supplied arguments.

os.Args contains the values typed after a command in a terminal. Its first item is the program name. Positional arguments, values supplied without a name such as a filename, start at index 1.

Check the argument count before indexing. Use the slice os.Args[1:] when iterating over user-supplied values.

package main
 
import (
    "fmt"
    "os"
)
 
func main() {
    args := os.Args[1:]
    if len(args) == 0 {
        fmt.Fprintln(os.Stderr, "usage: greet <name>")
        os.Exit(1)
    }
    fmt.Printf("Hello, %s!\n", args[0])
}

In production

os.Args is enough when a program accepts a few values such as filenames. Use the flag package for named options such as -output report.txt and generated help text. A FlagSet is a separate group of options for a subcommand. Use these tools instead of writing a parser for a large command line.

Enjoyed this? Get more software craft delivered to your inbox.