Several common ways of environment variable configuration in Linux

direct configuration

export PATH=$PATH:/usr/local/go/bin

This method configures temporary environment variables, which are only valid for the current shell process and fail immediately after switching

modify file

This method is to
add the code for configuring environment variables in the appropriate position of the file. There are many files that can be modified, such as ~/.bashrc, ~/.bash_profile, /etc/bashrc(/etc/bash.bashrc in ubuntu), /etc/profile, /etc/environmentetc.
At the same time, among these configuration files, the ones under the /etc/ directory are for everyone, while the ones under ~/ are only for the current user. Let’s introduce the differences between these
files.

environment variable precedence

The order in which Linux loads environment variables is as follows:
system environment variables -> user-defined environment variables /etc/environment -> /etc/profile -> ~/.profile

The /.profile file is only read once when the user logs in, while /.bashrc is read every time the shell script is run.

The /.profile file is a file that a user logs in and is read and executed before any shell session begins. It is used to set user environment variables as well as some basic configurations such as PATH or umask etc. Because /.profile is only read once at login, it is more suitable for setting those environment variables and configurations that only need to be set once during each login.

The ~/.bashrc file is only read at the start of each new bash shell. It is used to define bash specific configuration like bash aliases, command history, color themes etc. Since each new bash shell starts a new process, the ~/.bashrc file redefines and resets these configurations and variables each time it is loaded, ensuring there are no conflicts with previously created shells.

Therefore, the environment variables configured in the profile will become invalid after switching users, because switching users is switching a shell environment, so if you want every user to be able to use it, you can configure it in /etc/bash.bashrc or ~/.bashrc of each user

Guess you like

Origin blog.csdn.net/x646602196/article/details/130401363