Linux environment variables and shell profile (PATH, .bashrc, export)
Environment variables are named values a process inherits from its parent, and which file sets them depends on whether the shell is a login shell, an interactive shell, or a systemd unit.
- Updated Nov 27, 2026
- Markdown
Set and export variables, fix a PATH problem, pick the right startup file, and pass variables to a systemd service with Environment= or EnvironmentFile=.
- An Ubuntu or Debian server you can reach over SSH
A program behaves differently depending on its environment: which PATH it searches, which database URL it uses, which proxy it talks through. Most “works in my terminal, fails in the service” problems come down to the environment being different. This lesson shows how to read it, change it, and where each kind of process gets it from.
How it works#
The environment is a list of NAME=value pairs that a process receives when it starts. A child process gets a copy of its parent’s environment, and changes in the child never flow back. So export only affects programs you start afterwards from that shell.
Where the first environment comes from depends on how the process starts:
- An SSH login starts a login shell, which reads startup files and then passes the result down to everything you run.
- A terminal opened inside a desktop session starts a non-login interactive shell.
- A cron job or a systemd service starts with a minimal environment and reads none of your shell files.
sudobuilds a fresh, filtered environment for the command it runs.
Secrets in the environment are convenient, but they are also visible to anyone who can read /proc/<pid>/environ. See environment variables and secrets for how to handle them in deployments, and the glossary entry for environment variable for the definition.
Step 1: Read and set variables#
env
printenv HOME
echo "$PATH"
MY_VAR=hello
echo "$MY_VAR"
export MY_VAR
bash -c 'echo "child sees: $MY_VAR"'env and printenv print the environment. printenv NAME prints one value without needing $. MY_VAR=hello creates a shell variable. export MY_VAR marks it for inheritance, which the bash -c child proves. You can do both at once with export MY_VAR=hello.
Run a command with a variable only for that command:
APP_PORT=9000 node server.jsTo remove a variable, run unset MY_VAR. Quote expansions as "$MY_VAR" so spaces do not split the value.
Step 2: Understand PATH#
PATH is a colon-separated list of directories the shell searches for commands.
echo "$PATH"
which node
type -a python3To add a folder for this session:
export PATH="$HOME/bin:$PATH"Put your folder first to override a system command, or last ($PATH:$HOME/bin) to avoid overriding. If you write export PATH="$HOME/bin" you lose the system folders and nothing works until you reconnect. Use type -a name to see every match and which wins. The which command only reports the first one.
Step 3: Pick the right startup file#
For bash on Ubuntu and Debian:
/etc/environmentis not a script. It is a plainNAME=valuelist read by PAM at login, with noexportand no$PATHexpansion. It applies to all users, including non-shell sessions. Edit it as root./etc/profileand/etc/profile.d/*.shrun for login shells.~/.profileruns for login shells of that user. If~/.bash_profileexists, bash reads it instead, so Ubuntu does not create one by default.~/.bashrcruns for interactive non-login shells. Ubuntu’s default~/.profileloads it, so SSH logins get both. Note that the top of.bashrcreturns early for non-interactive shells.
A practical split: put export lines and PATH changes in ~/.profile, and aliases, prompt and history settings in ~/.bashrc. Apply a change to the current shell with source ~/.profile, or reconnect. Before you edit, back up the file as described in read and edit files on Linux.
To check which type of shell you have:
shopt -q login_shell && echo login || echo non-loginStep 4: sudo and the environment#
export MY_VAR=hello
sudo printenv MY_VAR
sudo MY_VAR=hello printenv MY_VAR
sudo -E printenv MY_VAR
sudo -i printenv PATHThe first sudo printenv prints nothing because sudo resets the environment. Setting VAR=value after sudo passes it explicitly, and -E asks to keep your environment, which only works if the sudoers policy allows it. sudo -i gives root’s login environment, and PATH is also reset by secure_path in sudoers, which is why a tool in ~/bin can be missing under sudo. See users, groups and sudo for the shell options.
Step 5: Variables for systemd services#
A systemd service does not start a shell and never reads ~/.profile or ~/.bashrc. Set variables in the unit:
[Service]
Environment="NODE_ENV=production" "PORT=3000"
EnvironmentFile=/etc/myapp/myapp.env
ExecStart=/usr/bin/node /srv/myapp/server.jsEnvironment= takes quoted NAME=value pairs. EnvironmentFile= points at a file of NAME=value lines, one per line, with no export and no shell expansion. Create it with restrictive permissions because it often holds secrets:
sudo install -m 600 -o root -g root /dev/null /etc/myapp/myapp.envThen reload and check:
sudo systemctl daemon-reload
sudo systemctl restart myapp
sudo systemctl show myapp --property=EnvironmentFiles are read when the service starts, so a change needs a restart. The unit file basics are in run a service with systemd. Cron has a similar trap, covered in cron vs systemd timers.
Check it worked#
printenv MY_VAR
sudo systemctl show myapp --property=Environment
sudo cat /proc/$(systemctl show -p MainPID --value myapp)/environ | tr '\0' '\n'The last line reads the live environment of the service’s main process. It needs root, and the output may include secrets, so do not paste it into tickets.
Edge cases and gotchas#
- Quotes and spaces.
MY_VAR=hello worldfails. WriteMY_VAR="hello world". - EnvironmentFile syntax is not shell.
export A=1orA=$Bdo not work. Quote values with spaces and keep one pair per line. - Changes do not reach running processes. A service started before you edited the file still has the old values until restart.
- Non-interactive SSH commands.
ssh host 'cmd'runs a non-login, non-interactive shell, so.bashrcmay return early andPATHcan differ from your normal session. - Secrets in history. Typing
export TOKEN=...stores it in~/.bash_history. Prefer a file with mode 600. - Docker is separate. A container does not inherit the host’s environment. Pass variables with
-eor Compose, see Docker Compose environment variables.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
bash: node: command not found over SSH or in cron | Node’s folder is not in the non-interactive PATH | Use the full path, or set PATH in the crontab or unit |
| Script prints an empty variable | Variable set but not exported | export NAME before starting the script |
sudo: node: command not found | secure_path ignores your PATH | Use sudo $(which node) or install system-wide |
Service logs undefined for a setting | Unit does not load your variables | Add Environment= or EnvironmentFile= and restart |
Failed to load environment files: No such file or directory | Wrong EnvironmentFile= path | Fix the path, or prefix with - to make the file optional |
New .bashrc alias missing in login SSH | ~/.bash_profile exists and hides .profile | Source .bashrc from .bash_profile |
/etc/environment change has no effect | Old session, or you used export or $PATH there | Log out and in, and use plain NAME=value lines |
Environment set but a variable looks wrong | Missing quotes around a value with spaces | Quote the whole pair: Environment="A=b c" |
Quick reference#
env # show everything
printenv NAME # show one value
export NAME=value # set for children
unset NAME # remove
export PATH="$HOME/bin:$PATH" # prepend to PATH
source ~/.profile # reload a startup file
sudo VAR=value command # pass a variable through sudo
# systemd unit:
# Environment="NAME=value"
# EnvironmentFile=/etc/myapp/myapp.envRelated lessons#
- Environment variables and secrets: how to keep secrets out of code and logs.
- Run a service with systemd: where Environment= lives.
- Schedule tasks with cron: the other minimal environment.
- Docker Compose environment variables: the container side.
For a practical view of secrets in deployments, see manage secrets in self-hosted Docker.
Next#
Now connect commands together with pipes, redirects and xargs.
Check what you learned
Frequently asked questions
What is the difference between a shell variable and an environment variable?
A shell variable exists only in the current shell. An environment variable has been exported, so child processes the shell starts inherit a copy.
Should I put variables in .bashrc or .profile?
On Ubuntu, .profile runs for login shells and loads .bashrc for interactive bash, so put PATH and exports in .profile and aliases or prompt settings in .bashrc. Neither is read by systemd services.
Why does my script not see a variable I set in my terminal?
You probably did not export it. VAR=value sets a shell variable only, while export VAR=value passes it to child processes such as your script.
Why does sudo not see my environment variables?
sudo resets the environment by default and passes only a safe list. Use sudo VAR=value command, or sudo -E if your policy allows keeping the environment.
Sources
Keep going: guides and tutorials
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.