Skip to content

os.Args command-line argument access

os.Args is a variable provided by Go's built-in os package that allows programs to access command-line arguments passed during execution^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. It is a string slice ([]string) that holds the command-line arguments, starting with the program name itself^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

Structure

The os.Args slice contains the full list of arguments. By convention:

  • os.Args[0]: The name of the executable or the path used to invoke the command^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
  • os.Args[1]: The first actual user-provided argument (often used for subcommands).
  • os.Args[n]: Subsequent arguments or flags.

Basic Validation

A common use case for os.Args is basic input validation, such as checking if the user provided enough arguments. This is typically done by checking the length of the slice^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

For example, to ensure a user provides at least one argument (a subcommand), a program might verify that len(os.Args) is at least 2^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. If the length is insufficient, the program can print usage instructions and exit.

Parsing Subcommands

When building command-line interfaces (CLIs), os.Args is often used in conjunction with a switch statement to route execution logic based on the first argument provided by the user^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

For instance, os.Args[1] can be evaluated to determine if the user is running a subcommand like get or add^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

Integration with the flag Package

While os.Args provides raw access to arguments, Go's standard flag package is often used for sophisticated parsing^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

When implementing subcommands, os.Args is used to identify the command, while flag.NewFlagSet can be initialized to handle the specific flags for that subcommand^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

In this pattern, os.Args[2:] is passed to the flag parser (e.g., getCmd.Parse(os.Args[2:])) to process arguments specific to that subcommand, excluding the program name and the subcommand itself^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

  • [[flag package]]: The standard Go package for command-line flag parsing.
  • [[Go CLI development]]

Sources

^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]