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

URL: https://levelrail.com/learn/linux/environment-variables-and-shell-profile/
Updated: 2026-11-27

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](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)) for how to handle them in deployments, and the [glossary entry for environment variable](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/linux/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](https://levelrail.com/learn/linux/users-groups-and-sudo/)) for the shell options.

## Step 5: Variables for systemd services

A [systemd](https://levelrail.com/learn/glossary/#systemd)) service does not start a shell and never reads `~/.profile` or `~/.bashrc`. Set variables in the unit:

```text
[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](https://levelrail.com/learn/linux/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](https://levelrail.com/learn/docker/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

```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
```

## Related lessons

- [Environment variables and secrets](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)): how to keep secrets out of code and logs.
- [Run a service with systemd](https://levelrail.com/learn/server-basics/run-a-service-with-systemd/)): where Environment= lives.
- [Schedule tasks with cron](https://levelrail.com/learn/server-basics/schedule-tasks-with-cron/)): the other minimal environment.
- [Docker Compose environment variables](https://levelrail.com/learn/docker/docker-compose-environment-variables/)): the container side.

For a practical view of secrets in deployments, see [manage secrets in self-hosted Docker](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)).

## Next

Now connect commands together with [pipes, redirects and xargs](https://levelrail.com/learn/linux/pipes-redirects-and-xargs/)).

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

- [Bash reference manual, Bash startup files](https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html)
- [systemd.exec, environment variables in service units](https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html)
