Go os.Args command-line argument access¶
In Go, the os.Args variable from the os package provides access to command-line arguments.^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md] It is a string slice ([]string) that holds useful information passed to the application, including the program's name.^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]
Usage¶
To use os.Args, the os package must be imported.^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]
import (
"os"
)
Structure¶
The os.Args slice contains the command-line arguments.
- Index 0: The name of the executing command or script.
- Index 1: The first actual argument passed by the user (often used for subcommands).
- Subsequent Indices: The remaining arguments or flags.
Argument Validation¶
A common use case is to check if sufficient arguments are provided before proceeding. This is often done by checking the length of the os.Args slice^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
For example, to ensure a user provides a subcommand (e.g., get or add), one might verify that the length is at least 2^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]:
if len(os.Args) < 2 {
fmt.Println("expected 'get' or 'add' subcommands")
os.Exit(1)
}
Parsing Subcommands¶
Because os.Args[0] is the program name, os.Args[1] typically represents the first user-defined argument (such as a subcommand)^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. Developers often use a switch statement to handle different values found at this index^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
For example, differentiating between a get and add command can be achieved by inspecting os.Args[1]^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]:
switch os.Args[1] {
case "get":
// Handle 'get' logic
case "add":
// Handle 'add' logic
default:
// Handle unknown input
}
Integration with Flag Parsing¶
When building complex CLI tools that require flags (e.g., --id or --title), os.Args is used to segment the input stream^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. While the built-in flag package handles the actual parsing of options, the arguments passed to it usually come from a slice of os.Args.
For instance, when handling a specific subcommand, a program typically passes the arguments after the subcommand (starting from index 2) to the flag parser^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]:
// Parse arguments starting from index 2 (skipping binary name and subcommand)
getCmd.Parse(os.Args[2:])