os.Args / os.Getenv()
Command-line arguments are available through the os.Args slice, and environment variables can be read with os.Getenv(). These are essential features for building CLI tools and externalizing configuration.
Syntax
// Slice of command-line arguments (os.Args[0] is the program name)
os.Args
// Get an environment variable (returns an empty string if not set)
value := os.Getenv("VARIABLE_NAME")
// Set an environment variable
err := os.Setenv("VARIABLE_NAME", "value")
// Check whether an environment variable exists
value, ok := os.LookupEnv("VARIABLE_NAME")
Function / Variable Reference
| Function / Variable | Description |
|---|---|
| os.Args | A string slice of command-line arguments. os.Args[0] is the program name, and os.Args[1] onward are the arguments passed to it. |
| os.Getenv(key) | Returns the value of the named environment variable. Returns an empty string if the variable is not set. |
| os.Setenv(key, value) | Sets an environment variable. The change applies only to the current process. |
| os.LookupEnv(key) | Returns the value of the environment variable and a bool indicating whether it exists. This lets you distinguish between an unset variable and one set to an empty string. |
Sample Code
package main
import (
"fmt"
"os"
)
func main() {
// Print command-line argument info
fmt.Println("Program name:", os.Args[0])
fmt.Println("Number of arguments:", len(os.Args)-1)
// Print the first argument if one was provided
if len(os.Args) > 1 {
fmt.Println("First argument:", os.Args[1])
} else {
fmt.Println("No arguments provided")
}
// Set and then retrieve an environment variable
os.Setenv("APP_ENV", "development")
env := os.Getenv("APP_ENV")
fmt.Println("APP_ENV:", env)
// Use LookupEnv to check existence before reading
if port, ok := os.LookupEnv("PORT"); ok {
fmt.Println("Port:", port)
} else {
fmt.Println("PORT is not set. Default: 8080")
}
}
Notes
When building CLI tools, consider using the standard library's flag package for argument parsing — it handles flag-style input (such as --port=8080) with ease. os.Args gives you the raw string slice, which is well-suited for simple, positional arguments.
Environment variables are commonly used in place of configuration files, especially in container and cloud environments. Because os.Getenv() returns an empty string when a variable is not set, use os.LookupEnv() with the ok flag to safely verify that a required variable is actually present.
If you find any errors or copyright issues, please contact us.