golang/go · error
%s can only be set using the OS environment
Error message
%s can only be set using the OS environment
What it means
Returned by checkEnvWrite for GOENV and GODEBUG when set via `go env -w`. GOENV names the env file itself (chicken-and-egg) and GODEBUG must take effect before the go command reads its env file, so both are restricted to the OS environment only.
Source
Thrown at src/cmd/go/internal/envcmd/env.go:647
return ""
}
func checkEnvWrite(key, val string) error {
switch key {
case "GOEXE",
"GOGCCFLAGS",
"GOHOSTARCH",
"GOHOSTOS",
"GOMOD",
"GOROOT",
"GOTELEMETRY",
"GOTELEMETRYDIR",
"GOTOOLDIR",
"GOVERSION",
"GOWORK":
return fmt.Errorf("%s cannot be modified", key)
case "GOENV", "GODEBUG":
return fmt.Errorf("%s can only be set using the OS environment", key)
}
// To catch typos and the like, check that we know the variable.
// If it's already in the env file, we assume it's known.
if !cfg.CanGetenv(key) {
return fmt.Errorf("unknown go command variable %s", key)
}
// Some variables can only have one of a few valid values. If set to an
// invalid value, the next cmd/go invocation might fail immediately,
// even 'go env -w' itself.
switch key {
case "GO111MODULE":
switch val {
case "", "auto", "on", "off":
default:
return fmt.Errorf("invalid %s value %q", key, val)
}View on GitHub (pinned to b6b368adc5)
Solutions
- For GOENV: export it in your shell/CI environment (`export GOENV=$HOME/.config/go/env-custom`).
- For GODEBUG: export it in the OS environment (`export GODEBUG=...`) or set it per-invocation.
- Update dotfiles (e.g. ~/.zshrc, ~/.bashrc) or your CI runner's env injection to set these at the process level.
Example fix
# before $ go env -w GODEBUG=panicnil=1 error: GODEBUG can only be set using the OS environment # after $ export GODEBUG=panicnil=1 && go build ./...
Defensive patterns
Strategy: validation
Validate before calling
var osOnly = map[string]bool{"GOENV": true, "GODEBUG": true}
func setEnv(key, val string) error {
if osOnly[key] {
return fmt.Errorf("%s must be set in the OS environment", key)
}
return runGoEnvW(key, val)
} Prevention
- Centralise GODEBUG/GOENV configuration in shell rc files or CI env injection.
- Never let config-management scripts route GOENV or GODEBUG through `go env -w`.
- Cross-check against `go env -json` — GOENV/GODEBUG are not listed as writable.
When it happens
Trigger: `go env -w GOENV=/path/to/env` or `go env -w GODEBUG=...`.
Common situations: Users trying to relocate the go env config file with `go env -w GOENV=...`; users wanting to tweak GODEBUG flags persistently via the env file rather than the OS env.
Related errors
- %s cannot be modified
- unknown go command variable %s
- invalid %s value %q
- GOPATH entry cannot start with shell metacharacter '~': %q
- GOPATH entry is relative; must be absolute path: %q
AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12).
Data as JSON: /api/errors/bc602d6d4940c055.
Report an issue: GitHub.