Every process on Linux carries a small bag of NAME=value pairs called its environment. It tells programs who you are, where your home is, which language to print in and, most importantly, where to look for commands. Applications read it too: Orbit’s API finds its database through a variable, and so does nearly every container, CI job and cloud CLI you will ever run.
Most “it works on my machine” puzzles on a server come down to one question: which environment did this process actually get? In this lesson you learn to read and change variables, control PATH, pick the right startup file, and see why systemd services, cron jobs and sudo start with a different environment from your shell. You finish with the part people get wrong in production: secrets. Most commands work in any lab option; the systemd section needs the orbit-lab VM from lesson 1.
Shell variables and environment variables
There are two kinds of variables, and the difference explains half the surprises you will meet:
- A shell variable lives only inside the current shell. Scripts and programs you start do not see it.
- An environment variable is a shell variable marked for export. Every child process receives a copy of it when it starts.
$ greeting=hello
$ echo $greeting
hello
$ bash -c 'echo "child sees: $greeting"'
child sees:
$ export greeting
$ bash -c 'echo "child sees: $greeting"'
child sees: hello
bash -c starts a new shell as a child process, which is exactly what happens when you run any program. Until export, the child gets nothing. Note there are no spaces around =: greeting = hello tries to run a command called greeting.
Inheritance only flows downwards. A child gets a copy, so changes it makes never reach the parent. That is why running a script that sets variables does not change your shell, while source script.sh (or . script.sh) does: sourcing runs the file inside the current shell instead of a child.
Tip: By convention environment variables are UPPER_CASE (ORBIT_ENV) and private shell variables are lower_case (count). Following it avoids accidentally overwriting system variables such as PATH or HOME in your scripts.
Reading the environment
| Command | What it shows |
|---|---|
printenv or env | Every exported variable of the current shell |
printenv HOME | One variable, with no $ |
echo "$HOME" | One variable, expanded by the shell |
declare -p name | A variable and its attributes (-x means exported) |
$ printenv | sort | head -5
HOME=/home/ubuntu
LANG=C.UTF-8
LOGNAME=ubuntu
PATH=/home/ubuntu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
PWD=/home/ubuntu
$ declare -p HOME greeting
declare -x HOME="/home/ubuntu"
declare -x greeting="hello"
Setting, scoping and removing
export NAME=value creates and exports in one step. Three more forms are worth knowing:
# Set a variable for one command only; your shell is unchanged afterwards
$ TZ=Asia/Tokyo date
Tue Nov 3 18:42:10 JST 2026
$ date
Tue Nov 3 09:42:10 UTC 2026
# Run a command with a clean, minimal environment (a good way to reproduce cron or service bugs)
$ env -i PATH=/usr/bin:/bin bash -c 'printenv'
PATH=/usr/bin:/bin
PWD=/home/ubuntu
SHLVL=1
_=/usr/bin/printenv
# Remove a variable completely
$ unset greeting
VAR=value command is the cleanest way to change behaviour for a single run, for example LC_ALL=C sort file for byte-order sorting or ORBIT_ENV=test ./run-tests.sh. env -i starts from an empty environment and env -u NAME cmd removes just one variable for a command.
PATH: how the shell finds commands
When you type curl, the shell does not search the whole disk. It checks, in order: aliases, functions and shell builtins, then each directory in PATH from left to right, and runs the first match.
$ echo "$PATH" | tr ':' '\n'
/home/ubuntu/.local/bin
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
/snap/bin
$ type -a python3
python3 is /usr/local/bin/python3
python3 is /usr/bin/python3
type -a lists every match in order, so you can see that a hand-installed python3 in /usr/local/bin shadows the distribution’s one. command -v name prints only the winner, which is what scripts should use.
To add your own tools, put them in ~/.local/bin (Ubuntu’s ~/.profile already adds it to PATH at login if the directory exists) or prepend a directory yourself:
$ mkdir -p ~/.local/bin
$ export PATH="$HOME/.local/bin:$PATH"
$ hash -r
Order matters: prepending (new:$PATH) makes your copy win, appending ($PATH:new) makes it a fallback. hash -r clears bash’s memory of where it found commands, which fixes “I installed the new version but the old one still runs”.
Warning: Never put . (the current directory) or an empty entry such as a trailing : in PATH. Anyone who can write a file called ls or sudo into a directory you cd into, such as /tmp, would get you to run it. Run local scripts explicitly with ./script.sh.
Variables you will meet everywhere
| Variable | Meaning | Example |
|---|---|---|
HOME | Your home directory, what ~ expands to | /home/maya |
USER, LOGNAME | The logged-in user name | maya |
SHELL | Your login shell (not necessarily the one running now) | /bin/bash |
PATH | Where commands are searched for | see above |
LANG, LC_ALL | Language, character set and sorting rules | C.UTF-8, en_US.UTF-8 |
TZ | Time zone for this process, overriding the system one | Europe/Lisbon |
EDITOR, VISUAL | Editor that crontab -e, git commit and sudoedit open | vim, nano |
PWD, OLDPWD | Current and previous directory | /srv/orbit |
LC_ALL overrides every other locale setting, which makes LC_ALL=C handy in scripts that parse command output: messages stay in English and sorting is predictable.
Startup files: making changes stick
An export typed at the prompt dies with the shell. To keep a setting, put it in a startup file. Which file bash reads depends on how it was started:
- A login shell is the first shell of a session: SSH,
multipass shell, a console login,sudo -iorbash -l. It reads/etc/profile(which also runs every/etc/profile.d/*.sh), then the first of~/.bash_profile,~/.bash_loginor~/.profilethat exists. - An interactive non-login shell is a new terminal tab or typing
bash. It reads/etc/bash.bashrcand~/.bashrc. - A non-interactive shell (a script,
bash -c) reads neither.
$ shopt -q login_shell && echo login || echo "not login"
login
Ubuntu stitches these together: ~/.profile sources ~/.bashrc, so in practice a clean setup looks like this (after editing, reload with source ~/.bashrc or open a new session for profile changes):
| File | Put here | Scope |
|---|---|---|
~/.profile | export lines, PATH changes (read once per login) | You, login shells |
~/.bashrc | Aliases, functions, prompt, shell options | You, interactive bash |
~/.bash_profile | Only if you need it; if it exists, Ubuntu’s ~/.profile is ignored | You, login shells |
/etc/profile.d/orbit.sh | Settings for every user’s login shell | All users |
/etc/environment | Plain KEY=value lines read at login by PAM, no $ expansion, no scripts | All users, all login methods |
Warning: Creating ~/.bash_profile on Ubuntu (some installers do it for you) silently stops ~/.profile from being read, and with it ~/.local/bin in PATH. If you need one, make its first line . ~/.profile.
Aliases
Aliases are shortcuts for interactive use and belong in ~/.bashrc:
alias orbit-logs='journalctl -u orbit-api -f'
alias k='kubectl'
alias lists them, unalias k removes one, and \ls or command ls bypasses an alias once. Aliases are not exported and not used in scripts, so never rely on one inside automation; write a function or a script in ~/.local/bin instead.
Your prompt
The prompt is the PS1 shell variable, set in ~/.bashrc and not exported. Its escapes include \u (user), \h (short host name), \w (current directory) and \$, which prints # for root and $ for everyone else. Add your own at the end of ~/.bashrc so it wins over Ubuntu’s default:
PS1='[\u@\h \w]\$ '
Many teams put the environment in the prompt on servers, such as PS1='[PROD \u@\h \w]\$ ' on orbit-web-01, so nobody mistakes production for the lab.
Red Hat and Alpine
On RHEL, Rocky and Alma the user’s ~/.bash_profile exists by default and sources ~/.bashrc, and the system file is /etc/bashrc. /etc/profile.d/ works the same. Alpine’s default shell is BusyBox ash: it reads /etc/profile, /etc/profile.d/*.sh and ~/.profile, and has no .bashrc unless you install bash. In containers, most images set variables with ENV in the Dockerfile or docker run -e, and no startup file runs at all.
Services do not read your .bashrc
A systemd service is started by PID 1, not by a shell. It never reads ~/.bashrc, ~/.profile or /etc/environment, so a variable you exported for yourself is invisible to it. Give a service its environment in the unit (lesson 9 covers units in depth):
# /etc/systemd/system/orbit-api.service (excerpt)
[Service]
User=orbit
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=/etc/orbit/orbit.env
/etc/orbit/orbit.env holds plain KEY=value lines (no export, no command substitution) and is mode 640, owned by root:orbit. To see what a running service really received, read its starting environment from /proc (tr turns the null bytes between entries into newlines):
$ pid=$(systemctl show -p MainPID --value orbit-api)
$ sudo cat /proc/$pid/environ | tr '\0' '\n'
LANG=C.UTF-8
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
HOME=/srv/orbit
LOGNAME=orbit
USER=orbit
SHELL=/usr/sbin/nologin
...
PYTHONUNBUFFERED=1
ORBIT_ENV=lab
ORBIT_PORT=3000
Note the short PATH, the orbit user’s HOME and the absence of anything from your own shell. Anyone on the machine can read unit files and run systemctl show -p Environment, so secrets go in the protected EnvironmentFile, never in Environment= lines. After changing either, run sudo systemctl daemon-reload and restart the service: a running process never sees new values. A leading dash, EnvironmentFile=-/etc/orbit/orbit.env, makes the file optional.
Cron and sudo
cron runs jobs with an almost empty environment: typically HOME, LOGNAME, SHELL=/bin/sh and PATH=/usr/bin:/bin. A script that calls something in /usr/local/bin works in your terminal and fails at 2 a.m. Use absolute paths or set PATH= at the top of the crontab; lesson 15 covers this in detail.
sudo resets the environment by default (env_reset) and replaces PATH with the secure_path from /etc/sudoers, so your personal ~/.local/bin is not searched as root. Your options:
sudo -E cmdasks to keep your environment; policy may refuse it, andPATHis still replaced bysecure_path.sudo --preserve-env=ORBIT_ENV cmdkeeps only named variables.sudo env ORBIT_ENV=staging /usr/local/bin/toolsets a variable explicitly as root; this form works everywhere.sudo -istarts a root login shell with root’s own startup files.
Tip: Ubuntu 26.04 uses sudo-rs, a Rust rewrite of sudo. It follows the same env_reset and secure_path rules but supports fewer sudoers options, so prefer the explicit sudo env VAR=value cmd form in runbooks.
Secrets and environment variables
Passing secrets through the environment is common (the twelve-factor style, Docker, Kubernetes), but understand where values can leak:
- The process environment file.
/proc/<pid>/environholds the starting environment of every process. Its owner and root can read it, and so can anything running as the same user. - Process listings.
ps eshows environments of processes you own; a debugging habit can put them on screen or in a ticket. - Logs and crash reports: frameworks happily dump the whole environment on an error page or in a debug log.
- Child processes inherit everything, including tools that phone home or upload diagnostics.
- Shell history:
export DB_PASSWORD=...typed at a prompt lands in~/.bash_history.
Safer habits, from good to better:
- Read secrets without echoing or saving them:
read -rs DB_PASSWORD; export DB_PASSWORD. Ubuntu’s defaultHISTCONTROL=ignorebothalso skips commands that start with a space. - Keep them in a root-owned file with mode 600 or 640, like
orbit.env, never in a world-readable unit or script. - Prefer files over variables where the app allows it: systemd’s
LoadCredential=hands the service a private file under$CREDENTIALS_DIRECTORY, and Kubernetes can mount secrets as files. - For teams, use a secret manager (Vault, OpenBao, AWS Secrets Manager, SOPS-encrypted files) and fetch at start-up.
.env files in projects
Developers keep per-project settings in a .env file. To load one into the current shell, export everything it defines:
$ cat .env
ORBIT_ENV=development
ORBIT_PORT=3000
$ set -a; source .env; set +a
$ printenv ORBIT_PORT
3000
set -a marks every variable assigned afterwards for export, and set +a turns that off again. Keep the real file out of Git (echo '.env' >> .gitignore), commit a .env.example with dummy values instead, and run a secret scanner such as gitleaks in CI. If a secret was ever committed, rotate it: deleting it in a later commit does not remove it from history.
direnv automates this: put export lines in a .envrc, approve it once with direnv allow, and the variables load when you cd into the project and disappear when you leave.
Practice lab
Maya reports that orbit-api cannot find its port setting, although she exported ORBIT_PORT in her ~/.bashrc. Fix the setup on orbit-lab (the VM, because of systemd):
- Create
~/.local/bin/orbit-envthat printsORBIT_ENVandPATH, make it executable and run it by name. Then run it withORBIT_ENV=labfor one command only. - Make
ORBIT_ENV=labpermanent for your user and prove a new login shell sees it. - Show that
sudodoes not see your variable, then pass it explicitly. - Start a throwaway service that loads
/etc/orbit/orbit.envas userorbit, and prove from/procthat it gotORBIT_PORTwhile your shell did not. If you skipped lesson 9, first create theorbitsystem user and theorbit.envfile (mode 640,root:orbit) containingORBIT_PORT=3000.
Show a solution
Write #!/bin/bash plus echo "ORBIT_ENV=$ORBIT_ENV"; echo "PATH=$PATH" into ~/.local/bin/orbit-env, run chmod +x ~/.local/bin/orbit-env, and call orbit-env (if it is not found, export PATH="$HOME/.local/bin:$PATH" and hash -r); ORBIT_ENV=lab orbit-env sets it for that run only. Append export ORBIT_ENV=lab to ~/.profile and check with bash -l -c 'echo $ORBIT_ENV'. sudo printenv ORBIT_ENV prints nothing, while sudo env ORBIT_ENV=lab printenv ORBIT_ENV prints lab. For the last task, sudo systemd-run --unit=env-demo -p User=orbit -p EnvironmentFile=/etc/orbit/orbit.env sleep 300 starts a transient service; pid=$(systemctl show -p MainPID --value env-demo) and sudo cat /proc/$pid/environ | tr '\0' '\n' list ORBIT_PORT=3000, while printenv ORBIT_PORT in your shell prints nothing and cat /etc/orbit/orbit.env as ubuntu fails with “Permission denied”; clean up with sudo systemctl stop env-demo.
Exercise
Maya added export ORBIT_DB_URL=... to her ~/.bashrc on orbit-web-01. Running the API by hand works, but the systemd service orbit-api still fails with “ORBIT_DB_URL is not set”. What is the right fix?
Show answer
Answer: C. systemd starts services from PID 1 without any shell, so no bashrc or profile file is read, not even root’s. The environment must come from the unit itself, through Environment= or a protected EnvironmentFile=.
Exercise
You installed a newer kubectl into ~/.local/bin, but kubectl version --client still prints the old version. type -a kubectl lists /usr/local/bin/kubectl first and ~/.local/bin/kubectl second. What do you do?
Show answer
Answer: B. The shell runs the first match in PATH order, so the directory with the version you want must come earlier. hash -r clears the cached location. Adding . to PATH is a security risk, and appending makes your copy a fallback.
Exercise
A teammate wants to give a deployment script the database password quickly and types export DB_PASSWORD=S3cret! on a shared server. Which risk is real?
Show answer
Answer: C. printenv only shows your own environment, but history files and /proc/<pid>/environ keep the value around, and any process started from that shell inherits it. Read secrets with read -rs, or keep them in a protected file or secret manager.
Key takeaways
- A variable reaches child processes only after
export; inheritance flows downwards and children never change the parent. - The shell runs the first match in
PATH, so order matters; never put.inPATH, and usetype -aandhash -rto debug. - Login shells read
~/.profile(or~/.bash_profile), interactive shells read~/.bashrc; system-wide settings go in/etc/profile.d/or/etc/environment. - Services, cron and
sudodo not inherit your shell setup: useEnvironmentFile=, full paths and explicitsudo env VAR=value. - Environment variables are not a vault: protect env files, keep
.envout of Git and prefer credentials files or a secret manager.
FAQ
Why does my environment variable disappear when I open a new terminal?
export only affects the current shell and the processes it starts. A new terminal is a new shell that rebuilds its environment from the startup files, so add the export line to ~/.profile (or ~/.bashrc for things you want in every interactive shell) and reload it with source.
What is the difference between .bashrc and .bash_profile?
~/.bash_profile is read by login shells (SSH, console, bash -l); ~/.bashrc is read by interactive non-login shells such as a new terminal tab. Ubuntu uses ~/.profile instead of ~/.bash_profile and sources ~/.bashrc from it, while RHEL ships a ~/.bash_profile that sources ~/.bashrc. Put exports in the profile file and aliases in .bashrc.
How do I add a directory to PATH permanently?
Add export PATH="$HOME/.local/bin:$PATH" (or your directory) to ~/.profile, then log out and in or run source ~/.profile. For all users, create a small script in /etc/profile.d/, for example /etc/profile.d/orbit-tools.sh. Always keep :$PATH in the line so you extend the existing value instead of replacing it.
Why can’t sudo see my environment variables?
sudo resets the environment for safety and replaces PATH with secure_path, so a privileged command cannot be tricked by your personal settings. Pass what you need explicitly with sudo env NAME=value command, keep specific variables with sudo --preserve-env=NAME, or use sudo -E where the policy allows it.
Are environment variables safe for secrets?
They are acceptable for a single service when the file they come from is protected (mode 640, owned by root), but they leak easily into child processes, debug output, crash reports and /proc/<pid>/environ. Prefer mounting secrets as files (systemd LoadCredential=, Kubernetes secret volumes) or fetching them from a secret manager, and never type them into a shell that saves history.
What is the difference between env and printenv?
Both print the exported environment when run with no arguments. printenv NAME prints one variable cleanly, which is handy in scripts. env can also run a command with a modified environment, as in env -i for an empty one, env -u NAME to drop a variable or env NAME=value cmd to add one.