Changing Environment Variables Linux: Set Temporary and Permanent Values

Published:

Changing environment variables willy-nilly on Linux is the fastest way to break your shell.
But changing them right is quick and low-risk.
This short guide shows how to set temporary values for a single session and make permanent changes that survive reboots.
You’ll get one-line commands, the exact files to edit (~/.bashrc, /etc/environment, /etc/profile.d), and the common gotchas that cause missing PATH or lost commands.
By the end you’ll be able to update env vars safely and test changes without logging out.

Quick-Start Overview for Working With Linux Environment Variables

nLcsqdk4SDyesl7thaojpQ

Environment variables are dynamic name-value pairs that store configuration details your Linux system and applications use at runtime. They control everything from how your shell prompt looks to which directories get searched when you type a command.

Want to see what a variable holds? Use echo $VARIABLE_NAME. Need to change one for your current session? Run export VARIABLE_NAME=value and check it with echo $VARIABLE_NAME.

Quick actions:

  • View a variable: echo $HOME shows your home directory path
  • Change temporarily: export EDITOR=vim sets your default editor to Vim until you close the terminal
  • Verify it worked: echo $EDITOR confirms the new value

Understanding Linux Environment Variable Basics and Scope

SanipKyzSv2GK9qN7v0uGw

Variable names are case-sensitive. PATH, Path, and path are three different things. Convention says environment variables get UPPERCASE names to keep them separate from regular shell variables and avoid conflicts.

When you set a variable with NAME=value, you’re creating a shell variable visible only in your current shell process. To make it an environment variable that child processes can see, you export it with export NAME. Skip the export and the variable stays local. Any program you launch won’t inherit it.

Linux reads environment variables from different config files depending on your shell type. Login shells (SSH sessions, user switches) and non-login interactive shells (new terminal windows in a desktop) look in different places. User-specific variables live in files like ~/.bashrc or ~/.profile and only affect that user. System-wide variables in /etc/environment or /etc/profile apply to everyone. The inheritance model means a parent shell passes its exported variables to child processes, but a child can never modify the parent’s environment.

Listing and Inspecting Linux Environment Variables

rGIDSe-LTc-xSXfIBwruew

Different commands show different slices of your shell’s variable landscape. printenv lists only environment variables, env does roughly the same thing, echo displays a single variable, and set shows everything including shell functions and non-exported variables.

Use printenv VARIABLE_NAME to check if something’s exported, or echo $VARIABLE_NAME to see its value either way. When you run env versus printenv, you’ll notice the special variable _ points to /usr/bin/env in one case and /usr/bin/printenv in the other. That’s because _ holds the path of the last command executed.

Command Output Description
env Lists all exported environment variables; _ points to /usr/bin/env
printenv Lists all exported environment variables; _ points to /usr/bin/printenv
echo $VAR Displays the value of VAR whether or not it’s exported
set Shows shell variables, environment variables, and shell functions

To compare shell-only variables with environment variables, run comm -23 <( set -o posix ; set | sort ) <( env | sort ). That shows which variables exist in your shell but won’t get passed to child processes.

Setting Temporary Environment Variables in Linux Shell Sessions

5Mpb0GRyQLy9seIBeIGKfQ

Temporary variables exist only in your current terminal session. Close the window and they’re gone. Create a shell variable with NAME=value and it stays in the current shell. Run export NAME=value to make an environment variable that child processes can see.

Shell variables don’t propagate, which makes them faster and safer for sensitive data. Environment variables travel to subshells, scripts, and any program you launch. If you set API_KEY=secret123 without export, a script won’t see it. Export it and every child process inherits that value.

Common patterns:

  • Shell variable only: TEST_VAR='Hello World!' — current shell sees it, nothing else
  • Immediate export: export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64" — one step
  • Export existing variable: DATABASE_URL='postgres://localhost' then export DATABASE_URL — two steps
  • One-off for single command: env LANG=C sort file.txt — temporary variable applies only to that sort process

When modifying PATH, append or prepend to what’s already there. export PATH="$PATH:/opt/mybin" adds /opt/mybin to the end, while export PATH="/opt/mybin:$PATH" puts it first. Never write export PATH=/new/path by itself or you’ll lose access to system commands.

Most common mistake? Adding spaces around the equals sign. VAR = value fails with a “command not found” error. Always use VAR=value with no spaces.

Making Permanent Environment Variable Changes in Linux

9WnaJVnDT563TizFbAfrmw

Permanent variables survive logout and reboot because they’re defined in config files your shell reads at startup. For user-level changes, edit ~/.bashrc if you want the variable in every new terminal window, or ~/.bash_profile and ~/.profile if you only need it in login shells.

System-wide variables go in /etc/environment using simple KEY=value pairs without the export keyword. Or in /etc/profile and /etc/profile.d/*.sh using standard shell export VAR=value syntax. Ubuntu, Debian, CentOS, Red Hat, and Fedora all use this pattern, though some customize which files get sourced first.

File loading order matters. Login shells read /etc/profile then the first file they find among ~/.bash_profile, ~/.bash_login, and ~/.profile. Non-login interactive shells read /etc/bash.bashrc then ~/.bashrc. Many distros configure login files to source ~/.bashrc, so putting exports there covers both cases.

To make a variable permanent in ~/.bashrc:

  1. Open the file: nano ~/.bashrc or vim ~/.bashrc
  2. Scroll to the end and add: export MY_VARIABLE="my_value"
  3. Save and close
  4. Apply immediately: source ~/.bashrc
  5. Verify with echo $MY_VARIABLE
  6. Open a new terminal to confirm it persists

For PATH modifications, always reference the existing value. Add export PATH="$HOME/bin:$PATH" to put your personal ~/bin directory first in the search order. Never replace PATH entirely or you’ll break command lookup.

Modifying and Fixing the Linux PATH Variable Safely

BfOpThXaRt6xA6S1viCy_w

PATH is a colon-separated list of directories the shell searches when you type a command. Order matters. The shell stops at the first match. When you run ls, the shell checks each PATH directory in sequence until it finds /usr/bin/ls or /bin/ls.

Safe patterns:

  • Append a directory: export PATH="$PATH:/opt/custom/bin" — adds to the end, lowest priority
  • Prepend a directory: export PATH="/opt/custom/bin:$PATH" — adds to the beginning, highest priority
  • Add multiple directories: export PATH="/first/dir:/second/dir:$PATH" — preserves left-to-right priority
  • Verify after change: echo $PATH — inspect the full list

Common pitfalls include double colons :: from mistakes like export PATH="$PATH:/new/dir:" (note the trailing colon), which tells the shell to search the current directory and creates a security risk. Typos in directory names mean commands won’t be found. Missing the $PATH reference entirely wipes out system directories and breaks everything.

After modifying PATH in a config file, run source ~/.bashrc to apply it. Then test with which command_name to confirm the shell finds executables from your new directory. If a command stops working, check for extra colons, verify directory spelling with ls /your/new/path, and make sure you didn’t accidentally remove the original $PATH reference.

System-Wide Linux Environment Variable Management

MzQAFJwzRaCDkA-0PSVY7A

System-wide variables affect every user and every login on the machine. Edit these files carefully and always use sudo. The /etc/environment file is the simplest place for global key-value pairs, but it requires plain KEY=value syntax without export because it’s not a shell script.

For shell-specific system-wide configuration, /etc/profile runs for all login shells and accepts standard export VAR=value commands. The /etc/profile.d/ directory holds modular .sh scripts that /etc/profile sources automatically, making it easy to add or remove global settings without editing the main file.

File Shell Type Syntax Typical Use
/etc/environment All (read by PAM) KEY=value Simple global pairs; no export keyword
/etc/profile Login shells export VAR=value Global shell logic and PATH setup
/etc/profile.d/*.sh Login shells export VAR=value Modular per-application global scripts

When you edit /etc/environment, add a line like JAVA_HOME=/usr/lib/jvm/default-java with no quotes and no export. For /etc/profile or a script in /etc/profile.d/, write export JAVA_HOME=/usr/lib/jvm/default-java as you would in a user file. After editing system files, test the change from another user account or a fresh login to confirm it applies globally.

Be cautious with sudo. A typo in a system-wide file can break logins for all users. Test your syntax in a user-level file first, and keep a root shell open while editing global config so you can fix mistakes if a new login fails.

Applying Linux Environment Variable Changes Without Restarting

mmqeTWLYTECdjPn-vQrsBg

The source command (or its alias .) reads a config file and executes its contents in your current shell. Run source ~/.bashrc and any new export statements take effect immediately. No need to open a new terminal. This is faster than logout-login cycles and essential for testing changes.

exec $SHELL replaces your current shell process with a fresh one, re-reading all startup files. It’s more thorough than source but closes the existing shell session, so unsaved history is lost. For system-wide files like /etc/environment, source /etc/environment works, but some changes require a full re-login because desktop sessions and display managers read those files at login time, not during shell startup.

For one-off temporary variables that don’t need persistence, env VAR=value command_to_run sets VAR only for that single command execution. The variable never touches your shell’s environment and disappears when the command finishes.

Unsetting and Troubleshooting Linux Environment Variables

HXA0Ho6ZS3u0_zcNMl7ATA

Remove a variable entirely with unset VARIABLE_NAME. The variable disappears from both shell and environment scope. To demote an environment variable back to a shell-only variable without deleting it, use export -n VARIABLE_NAME. It keeps the value but stops exporting to child processes.

When variables don’t behave as expected, check syntax first. Run bash -n ~/.bashrc to parse your config file without executing it. Bash reports line numbers of syntax errors like unmatched quotes or missing semicolons. Use grep -r "VARIABLE_NAME" ~/.bash* /etc/profile to find every place a variable is defined, because later assignments can overwrite earlier ones.

Common checks:

  • Variable not found: printenv VARIABLE_NAME shows nothing. Likely not exported or defined in the wrong file.
  • Variable appears in set but not env: it’s a shell variable. Add export to make it inheritable.
  • GUI apps don’t see the variable: desktop sessions may bypass shell startup files. Set it in /etc/environment instead.
  • sudo resets variables: run sudo -E command to preserve your environment, or configure /etc/sudoers.
  • Variable disappears after login: make sure it’s in a file your shell type reads. Login shells skip ~/.bashrc unless sourced from ~/.profile.

GUI session quirks are common. A variable set in ~/.bashrc won’t appear in graphical applications launched from a menu because those apps start from the display manager, not a shell. System-wide variables in /etc/environment or desktop-specific files like ~/.pam_environment (deprecated on some distros) fix that.

PATH issues often stem from conflicting definitions. If a command suddenly isn’t found, run echo $PATH and scan for double colons, missing directories, or incorrect order. Use which command_name to see which binary the shell actually finds, and type command_name to check if it’s an alias, function, or executable.

When sudo resets your environment, variables like PATH and JAVA_HOME vanish. The /etc/sudoers file controls this with env_reset and env_keep directives. Edit with sudo visudo to preserve specific variables, or pass sudo -E to keep your entire environment (requires appropriate sudoers permissions).

Final Words

Hands-on: you now know what environment variables do and the fastest ways to inspect and change them—echo $VAR to view, export VAR=value to change temporarily.

You also covered scope and persistence: how values inherit to child processes, when to edit ~/.bashrc or /etc/environment for permanent changes, and safe PATH edits like export PATH=”/new/dir:$PATH”.

For practical changing environment variables linux, run quick checks (echo), source or exec to apply changes, and keep edits minimal. You’ll avoid surprises and move faster.

FAQ

Q: How to change environment variables in Linux?

A: Changing environment variables in Linux is done temporarily with export VAR=value for the current shell, and permanently by adding NAME=value (and export if needed) to ~/.bashrc then sourcing it.

Q: What does $_ mean in bash?

A: The $_ variable in bash means the last argument of the previous command (or the last parameter processed), handy for quickly reusing or checking that value in follow-up commands.

Q: What is Ldlibrarypath in Linux?

A: The LDLIBRARYPATH in Linux is an environment variable that tells the dynamic linker where to look for shared libraries before standard paths; prefer RPATH or system-wide installs to avoid runtime conflicts.

curtisharmon
Curtis has spent over two decades guiding hunters and anglers through the backcountry of Montana and Wyoming. His expertise in elk hunting and fly fishing has made him a sought-after voice in the outdoor community. Curtis combines traditional woodsmanship with modern techniques to help readers succeed in the field.

Related articles

Recent articles