How to set environment variables persistently

Topic: Servers linux

Summary

Set environment variables for a user in ~/.profile, ~/.bashrc, or ~/.bash_profile, and for a systemd service in the unit file or EnvironmentFile. Use this when an app or script needs VAR=value across logins or at service start.

Intent: How-to

Quick answer

  • User shell: add export VAR=value to ~/.bashrc (for interactive bash) or ~/.profile (login); source the file or log out and back in. For all users, add to /etc/environment (format VAR=value, no export) or /etc/profile.d/myapp.sh.
  • systemd unit: add Environment=VAR=value or EnvironmentFile=/path/to/file in the [Service] section; file format VAR=value one per line. Then systemctl daemon-reload and restart the unit.
  • Verify: echo $VAR in shell; systemctl show UNIT --property=Environment for a service. Avoid secrets in world-readable files; use EnvironmentFile with mode 600 or a secrets manager.

Prerequisites

Steps

  1. Set for user shell

    Add export MYVAR=value to ~/.bashrc; run source ~/.bashrc or open a new terminal. For login-wide: ~/.profile or ~/.bash_profile. For all users: /etc/environment (no export) or a file in /etc/profile.d/.

  2. Set for systemd service

    Edit the unit (or drop-in in /etc/systemd/system/UNIT.d/): [Service] Environment=MYVAR=value or EnvironmentFile=/etc/myapp/env. Run systemctl daemon-reload; systemctl restart UNIT.

  3. Verify and secure

    echo $MYVAR in shell; systemctl show nginx --property=Environment. Do not put secrets in world-readable files; restrict EnvironmentFile to root or the service user (chmod 600).

Summary

Set user env vars in ~/.bashrc or ~/.profile; set system-wide in /etc/environment or /etc/profile.d. Set service env vars in the systemd unit with Environment or EnvironmentFile. Use this so apps and scripts see the right values at login or service start.

Prerequisites

Steps

Step 1: Set for user shell

Add export MYVAR=value to ~/.bashrc (or ~/.profile). Run source ~/.bashrc or log in again.

Step 2: Set for systemd service

In the unit [Service] section add Environment=MYVAR=value or EnvironmentFile=/etc/myapp/env. Run systemctl daemon-reload and systemctl restart UNIT.

Step 3: Verify and secure

Check with echo $MYVAR or systemctl show UNIT --property=Environment. Restrict env files containing secrets to root or the service user.

Verification

  • Variable is set in the intended scope (user shell or service); it persists across logins or service restarts.

Troubleshooting

Not set in cron — Cron runs with a minimal env; set vars in the crontab line or in the script. Service does not see var — Ensure EnvironmentFile path is correct and daemon-reload was run after editing.

Next steps

Continue to