Environment Variables Reach Child Processes Only When Exported

In progress Linux

Every process gets a copy of its parent's environment when it starts. In a shell, NAME=value creates a shell variable that only the shell sees; export puts it into the environment so scripts and programs started afterwards inherit it. Changes never flow back: a child can't change its parent's environment.

Three Ways to Set a Value

GREETING="hi"                 # shell variable: a script started now won't see it
export GREETING="hi"          # environment variable: every child process gets it
GREETING="hi" ./script.sh     # for this one command only, the shell is unaffected
unset GREETING                # remove it

Inside a script, read it with $GREETING (or "${GREETING:?not set}" to stop with an error when it's missing). By convention names are uppercase with underscores.

Inspecting the Environment

env                           # every exported variable
env | grep TERM               # filter by name
printenv HOME                 # a single value

Persisting Variables

  • For every new shell: add the export line to ~/.bashrc or ~/.zshrc.
  • In Gitpod workspaces: gp env NAME=value stores it for your future workspaces of the current repository.
  • For services: the systemd unit's Environment= / EnvironmentFile=, or the container's env_file.

References

Review cards

Flashcard Why can't running ./set-vars.sh set variables in your current shell, and what does?

The script runs in a child process, and a child's environment changes vanish when it exits. Source it instead: source ./set-vars.sh.

Flashcard What is the difference between GREETING=hi and export GREETING=hi?

The first creates a shell variable that only the shell sees. export puts it into the environment, so programs started afterwards inherit it.