Export and environment inheritance
What you need to know
A shell variable belongs to the shell. A set scalar variable marked for export is included in the environment passed to subsequently launched programs. An exported name without a value is not passed until a value is assigned; an assigned empty string is passed as an empty value. The environment is a collection of name-value strings. A child process can change its own copy but cannot change the parent shell variable merely by assigning or exporting it. Use a made-up variable name, not credentials.
Run each example separately as a new Bash script (Chapter 1). Tested with Bash 5.2.37 on Debian 13, default shell options; no personal configuration is required.
Compare before and after export
unset BM_THEMEBM_THEME=lightbash -c 'printf "%s\n" "${BM_THEME-unset}"'export BM_THEMEbash -c 'printf "%s\n" "$BM_THEME"'Expected stdout:
unsetlightThe first child has no BM_THEME. The second receives light. Single quotes prevent the parent from expanding the child command string; double quotes inside it preserve the value.
A child changes only its copy
export BM_THEME=lightbash -c 'BM_THEME=dark; printf "%s\n" "$BM_THEME"'printf '%s\n' "$BM_THEME"Expected stdout:
darklightThe child prints dark. The parent still has light. A semicolon separates two commands within the child.
Pass a temporary environment value
export BM_THEME=lightBM_THEME=dark bash -c 'printf "%s\n" "$BM_THEME"'printf '%s\n' "$BM_THEME"Expected stdout:
darklightThe assignment before this external command changes the environment for that command only. Builtins and functions have additional rules discussed later. printenv BM_THEME can inspect this one exported value if the external utility is installed.
Common mistakes
Do not print the entire environment in logs: it can contain credentials. Export is inheritance, not a global setting for all processes or a mechanism for updating already-running children.
Practice
Use BM_COLOR with values blue and green to demonstrate an unexported value, an exported value and a temporary child override.
Next lesson: PATH and command lookup