Command-line arguments and environment variables
- Version
- 1.27
- Review
- Draft
Summary#
os.Args holds the program name followed by its arguments. os.Getenv returns an environment value or an empty string. os.LookupEnv also reports whether the variable is set.
Syntax#
args := os.Args[1:]
value := os.Getenv("APP_MODE")
value, ok := os.LookupEnv("APP_MODE")
err := os.Setenv("APP_MODE", "debug")
expanded := os.ExpandEnv("mode: ${APP_MODE}")
err = os.Unsetenv("APP_MODE")
Example#
package main
import (
"fmt"
"os"
)
const modeKey = "DEVLOOKUP_EXAMPLE_MODE"
func show() {
value, ok := os.LookupEnv(modeKey)
fmt.Printf("value=%q set=%t\n", value, ok)
}
func main() {
args := os.Args[1:] // without the program name
if len(args) == 0 {
args = []string{"build", "--fast"} // sample input
}
fmt.Println("command:", args[0])
fmt.Printf("options: %q\n", args[1:])
for _, value := range []string{"", "debug"} {
if err := os.Unsetenv(modeKey); err != nil {
fmt.Println(err)
}
show()
if err := os.Setenv(modeKey, value); err != nil {
fmt.Println(err)
}
show()
}
fmt.Println(os.Getenv(modeKey))
fmt.Println(os.ExpandEnv("mode: ${DEVLOOKUP_EXAMPLE_MODE}"))
}
Expected output#
This is the output of a run without arguments. Supplying arguments changes the first two lines. The example sets and unsets variables in its own process.
command: build
options: ["--fast"]
value="" set=false
value="" set=true
value="" set=false
value="debug" set=true
debug
mode: debug
Common mistakes#
Reading os.Args[1] panics when no argument was given, so check the length first. Getenv cannot tell an unset variable from an empty one; use LookupEnv when that matters. Use the flag package to parse options.
Version applicability#
Args, Getenv, Setenv and ExpandEnv date back to Go 1.0. Go 1.4 added Unsetenv. The complete example requires Go 1.5 for LookupEnv.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0