Chapter 7 · Lesson 6 of 11
Linux for servers

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.

By the end you will

Set and export variables, fix a PATH problem, pick the right startup file, and pass variables to a systemd service with Environment= or EnvironmentFile=.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • 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.
  • sudo builds 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#

bash
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:

bash
APP_PORT=9000 node server.js

To 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.

bash
echo "$PATH"
which node
type -a python3

To add a folder for this session:

bash
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/environment is not a script. It is a plain NAME=value list read by PAM at login, with no export and no $PATH expansion. It applies to all users, including non-shell sessions. Edit it as root.
  • /etc/profile and /etc/profile.d/*.sh run for login shells.
  • ~/.profile runs for login shells of that user. If ~/.bash_profile exists, bash reads it instead, so Ubuntu does not create one by default.
  • ~/.bashrc runs for interactive non-login shells. Ubuntu’s default ~/.profile loads it, so SSH logins get both. Note that the top of .bashrc returns 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:

bash
shopt -q login_shell && echo login || echo non-login

Step 4: sudo and the environment#

bash
export MY_VAR=hello
sudo printenv MY_VAR
sudo MY_VAR=hello printenv MY_VAR
sudo -E printenv MY_VAR
sudo -i printenv PATH

The 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:

output
[Service]
Environment="NODE_ENV=production" "PORT=3000"
EnvironmentFile=/etc/myapp/myapp.env
ExecStart=/usr/bin/node /srv/myapp/server.js

Environment= 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:

bash
sudo install -m 600 -o root -g root /dev/null /etc/myapp/myapp.env

Then reload and check:

bash
sudo systemctl daemon-reload
sudo systemctl restart myapp
sudo systemctl show myapp --property=Environment

Files 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#

bash
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 world fails. Write MY_VAR="hello world".
  • EnvironmentFile syntax is not shell. export A=1 or A=$B do 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 .bashrc may return early and PATH can 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 -e or Compose, see Docker Compose environment variables.

Troubleshooting#

SymptomLikely causeFix
bash: node: command not found over SSH or in cronNode’s folder is not in the non-interactive PATHUse the full path, or set PATH in the crontab or unit
Script prints an empty variableVariable set but not exportedexport NAME before starting the script
sudo: node: command not foundsecure_path ignores your PATHUse sudo $(which node) or install system-wide
Service logs undefined for a settingUnit does not load your variablesAdd Environment= or EnvironmentFile= and restart
Failed to load environment files: No such file or directoryWrong EnvironmentFile= pathFix the path, or prefix with - to make the file optional
New .bashrc alias missing in login SSH~/.bash_profile exists and hides .profileSource .bashrc from .bash_profile
/etc/environment change has no effectOld session, or you used export or $PATH thereLog out and in, and use plain NAME=value lines
Environment set but a variable looks wrongMissing quotes around a value with spacesQuote the whole pair: Environment="A=b c"

Quick reference#

bash
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.env

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 learned4 questions
1What does export API_URL=https://example.com do that API_URL=https://example.com alone does not?
2A command works in your SSH session but fails in cron with command not found. What is the likely cause?
3Where do you put variables for a systemd service?
4Which file is read by a login shell on Ubuntu, for example over SSH?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios