Run Commands With Env Overrides

Build cmd.Env from os.Environ plus overrides so children see staged configuration, and filter secrets out of the inherited environment before spawn.

GoConfig Management

Code

snippet
package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

// childEnv 复制父环境,滤掉要覆盖与要清除的键,再追加覆盖项。
// 同名键先被滤掉,子进程读到的一定是覆盖值而不是父进程旧值。
func childEnv() []string {
	env := []string{}
	for _, kv := range os.Environ() {
		if strings.HasPrefix(kv, "APP_MODE=") || strings.HasPrefix(kv, "SECRET_TOKEN=") {
			continue
		}
		env = append(env, kv)
	}
	return append(env, "APP_MODE=staging")
}

func main() {
	// cmd.Env 为 nil 才表示完全继承父进程;一旦显式赋值就是整体替换
	env := childEnv()

	mode := exec.Command("printenv", "APP_MODE")
	mode.Env = env
	out, err := mode.Output()
	if err != nil {
		fmt.Println("APP_MODE missing:", err)
	} else {
		fmt.Println("APP_MODE:", strings.TrimSpace(string(out)))
	}

	secret := exec.Command("printenv", "SECRET_TOKEN")
	secret.Env = env
	if _, err := secret.Output(); err != nil {
		fmt.Println("SECRET_TOKEN absent in child")
	}
}

How it all comes together

The snippet is organized around the functions childEnv and main.

The loop for _, kv := range os.Environ() is the only repeated construct. err is inspected at 2 call sites before any result is trusted.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func childEnv() []string

The file’s steps show up in the output as APP_MODE missing:, APP_MODE:, SECRET_TOKEN absent in child.

The demo flow inside main is childEnv — run the file to see it end to end.

Core lines

return append(env, "APP_MODE=staging")
for _, kv := range os.Environ() {
	if strings.HasPrefix(kv, "APP_MODE=") || strings.HasPrefix(kv, "SECRET_TOKEN=") {
		continue
	}
	env = append(env, kv)
}
if err != nil {
	fmt.Println("APP_MODE missing:", err)
} else {
	fmt.Println("APP_MODE:", strings.TrimSpace(string(out)))
}

Interactive Tools for This Topic

FAQ

What does Run Commands With Env Overrides print when run?
No setup needed: run the file and look for labeled lines like `APP_MODE missing:`, `APP_MODE:`, `SECRET_TOKEN absent in child` in the output.