Part III · Shell and commands
27.1 Where environment variables come from
alsoenvenvironmentenvironment variablesenv varsexportprintenv/etc/environmentlocalelang
TL;DR
- Every process gets a copy of its parent's environment: a list of
NAME=valuestrings. export NAME=valuesets it for the current shell and the programs it starts, not for its parent or for other terminals.- To keep it, put the
exportin a startup file (27.2). For graphical apps on systemd desktops, use a file in~/.config/environment.d/.
printenv LANG
export EDITOR=nvim
LANG=C sort names.txt # set for one command only
On your machine
$ atfq 27.1 SHELL /bin/bash HOME /home/alice LANG en_US.UTF-8 EDITOR nvim TERM xterm-256color Login /bin/zsh (SHELL says /bin/bash: changed since login?) In all 8 variables set; only well-known ones are shown here
An example: Alice's laptop, one of the test machines. In your terminal, this block shows your own machine, read live.
Pitfalls
- A variable set without
exportstays in the shell: the programs it starts don't see it. - A change never reaches programs already running, nor other terminals:
open a new one, or
source ~/.bashrc. - systemd services don't read your shell files: give them variables with
Environment=in a drop-in (see 22.3). sudoresets most of the environment.sudo -Ekeeps it, when sudoers allows it.- Variables are visible to every process you run, in
/proc/PID/environ: avoid keeping secrets there for long.
Deep dive 2 questions
Where does the first environment come from?
At login, PAM and the login program set HOME, USER, SHELL and a
default PATH; pam_env adds what's in /etc/environment. The login
shell then runs its startup files, which add more. Desktop sessions started
by systemd also read environment.d files. Every program after that
inherits the result.
What do LANG and LC_ALL do?
They choose the language of messages, the format of numbers and dates, the
sort order and the character encoding. LC_ALL overrides everything,
LANG is the fallback. locale shows the current values, and LC_ALL=C
gives scripts stable, byte-based behaviour.