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 raw command-line arguments. Index 0 is the program name as invoked; user-supplied positional arguments begin 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 for simple positional inputs. Use the flag package for named options and help text, or a FlagSet for subcommands. Avoid hand-parsing complex command lines because quoting and option handling have established conventions.
Enjoyed this? Get more software craft delivered to your inbox.