Environment Variables (Environment) | Linux

2024/01/20

In Linux, environment variables (Environment) typically refer to the operating system environment in which users or processes execute, including various environment variables, working directories, file permissions, and other related runtime conditions. Environment variables are an important element that contains information about the system and user environment, such as PATH, HOME, USER, etc.

# View all environment variables in Linux
printenv

# Current user
$USER
echo Hello, my name is $USER
# Hello, my name is ben

# If we just want to temporarily change a variable
USER=jack
echo Hello, my name is $USER
# Hello, my name is jack

# If we want to permanently change a Linux environment variable
sudo vim /etc/environment
sudo vim ~/.bashrc
########################################
export TEST1="test1"
########################################
source /etc/environment
source ~/.bashrc
echo $TEST1
# test1
# If we switch to another user
sudo su
echo $TEST1
# test1
# We can see that all users can access and share this environment variable

# If you only want a specific user to use the variable
# Environment variables set this way will only be available to that $USER
sudo vim /etc/profile

Important Notes:

Variables set in /etc/profile are global and apply to all users, while variables set in ~/.bashrc are local and can only inherit variables from /etc/profile. They have a “parent-child” relationship.

profile is used for login shells, while bashrc is used for every interactive shell. ~/.bash_profile runs when entering bash interactively via a login method, and ~/.bashrc runs when entering bash interactively via a non-login method. Usually, the settings in both are largely the same, so the former typically sources the latter.

Applying changes: You can either restart for changes to take effect, or use the source command to reload the Linux environment variables.