Search⌘ K
AI Features

Accessing Non-Flag Arguments

Explore how to retrieve non-flag arguments in Go command-line tools using flag.Args() and os.Args. Understand processing input from standard input and files to create flexible DevOps utilities. This lesson equips you to build tools that accept flags, arguments, and streamed data, enhancing command-line automation capabilities.

We'll cover the following...

Arguments in Go are read in a few ways. We can read the raw arguments using os.Args, which will also include all the flags. This is great when no flags are used.

When using flags, flag.Args() can be used to retrieve only the non-flag arguments. If we want to send a list of authors to a development server and retrieve QOTDs for each author, the command might look like this:

C++
qotd --dev "abraham lincoln" "martin king" "mark twain"

In this list, we use a --dev flag to indicate that we want to use the development server. Following our flag, we have a list of arguments:

Go (1.18.2)
func main() {
flag.Parse()
authors := flag.Args
if len(authors) == 0 {
log.Println("did not pass any authors")
os.Exit(1)
}
...

In this code, we do the following:

  • Line 4: Retrieve the non-flag arguments using ...