Skip to content
shellhacks.dev
Go

Read an environment variable

Read an environment variable in Go with os.LookupEnv, which tells an unset variable from an empty one. os.Getenv returns an empty string for both.

1 min read
Summarize in AI

A program reads a setting from the environment, and an empty value must mean something different from no value.

main.goGo
package main

import (
	"fmt"
	"os"
)

func main() {
	for _, name := range []string{"SET_VAR", "EMPTY_VAR", "UNSET_VAR"} {
		v, ok := os.LookupEnv(name)
		fmt.Printf("%-9s Getenv=%q LookupEnv=(%q, %v)\n", name, os.Getenv(name), v, ok)
	}
}
Shell
SET_VAR=on EMPTY_VAR= go run main.go
Text
SET_VAR   Getenv="on" LookupEnv=("on", true)
EMPTY_VAR Getenv="" LookupEnv=("", true)
UNSET_VAR Getenv="" LookupEnv=("", false)

os.Getenv returns the empty string for a missing variable, so its result cannot tell the two cases apart. os.LookupEnv returns the value and a boolean that is true when the variable exists, even when it is empty, as the os package documentation explains. The output shows the third variable is the only one reported as not present.

On Linux, Path and PATH are different variables. For configuration with defaults, a small helper that returns the fallback only when ok is false keeps an explicit empty value working.

Share

More snippets

Go

Exit with a status

Exit with a status using os.Exit(n). It ends the program at once and skips every deferred call, so cleanup in defer is not run before the exit.

1 min read
Go

Raise the scanner line limit

Raise the line limit of bufio.Scanner with Buffer(make([]byte, 0, 64*1024), max). Lines over 64 KB otherwise stop the scan with token too long.

1 min read
Go

Set a timeout for a command

Stop a command that takes too long with exec.CommandContext and context.WithTimeout. In Go 1.19 a shell's child can keep Output() waiting past the deadline.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.