How to Set Environment Variables Permanently in Linux/Unix

Setting the $PATH environment variable on Linux or Unix systems allows you to specify directories where executable programs are located. This guide outlines methods to configure $PATH permanently so that it persists across sessions.

Understanding $PATH

$PATH is a colon-separated list of directories that the shell searches for executable files. When you type a command in the shell, it searches these directories in the order specified to find the executable corresponding to that command.

Methods to Set $PATH Permanently

  1. Using .bashrc or .bash_profile: These files are read and executed by the Bash shell when it starts. You can add or modify the $PATH variable in either of these files:
   # Open .bashrc or .bash_profile in a text editor
   nano ~/.bashrc   # or ~/.bash_profile

   # Add or modify the PATH variable
   export PATH="/new/path/directory:$PATH"

   # Save and close the file
   source ~/.bashrc   # or source ~/.bash_profile
  • export PATH="/new/path/directory:$PATH": Prepends /new/path/directory to the existing $PATH. Ensure to separate directories with a colon (:).
  1. Modifying /etc/profile or /etc/environment: Editing system-wide configuration files like /etc/profile or /etc/environment affects all users. Use a text editor with administrative privileges to modify these files:
   sudo nano /etc/profile   # or sudo nano /etc/environment

   # Add or modify the PATH variable
   PATH="/new/path/directory:$PATH"
   export PATH

   # Save and close the file
  • Ensure to prepend or append directories to the existing $PATH variable as necessary.
  1. Using ~/.profile: Some Unix-like systems use ~/.profile instead of .bashrc or .bash_profile for user-specific environment settings. Edit ~/.profile similarly to .bashrc:
   nano ~/.profile

   # Add or modify the PATH variable
   export PATH="/new/path/directory:$PATH"

   # Save and close the file
   source ~/.profile
  • Remember to source the file after editing to apply changes to the current session.

Verifying $PATH Configuration

After modifying any of the configuration files, verify the changes by echoing $PATH:

echo $PATH

This command displays the current value of $PATH, confirming whether your changes were applied successfully.

Conclusion

Configuring $PATH permanently ensures that directories containing executable programs are always accessible from the command line, enhancing usability and efficiency in Linux/Unix environments. By choosing the appropriate method and correctly modifying the configuration files (~/.bashrc, /etc/profile, etc.), you can customize $PATH to suit your needs across sessions and user environments.