Rocky Linux 环境变量配置

所属分类:Linux | 浏览:40 | 发布于 2025-12-30

环境变量在一组变量,它们存储在系统的环境里,可以被程序访问。这些变量可以包含各种信息,如用户名、路径、配置选项等。

PATH是一个环境变量,它告诉操作系统在执行命令时,在哪些目录中查找可执行文件(程序)。系统通过查找PATH环境变量中列出的路径来找到执行命令的程序文件。

 

1、环境变量分类

1.1、按生效范围分类

  • 系统环境变量:对所有用户生效,通常在系统启动时加载。
  • 用户环境变量:仅对当前用户生效,通常在用户登录时加载。

1.2、按生存周期分类

  • 永久环境变量:通过配置文件设置,每次系统启动或用户登录时自动加载。
  • 临时环境变量:在Shell会话中设置,关闭Shell后失效。

2、环境变量的几个文件

  • ~/.bashrc
  • ~/.bash_profile
  • /etc/bashrc
  • /etc/profile
  • /etc/profile.d/*.sh

rc文件:存放方法和别名

profile文件:存放环境变量和启动程序

3、配置文件调用顺序

  1. ~/.bash_profile 调用 ~/.bashrc;
  2. ~/.bashrc 调用 /etc/bashrc
  3. 登录时调用 /etc/profile
  4. 非登录时调用 /etc/bashrc

4、PATH环境变量配置实践

4.1、在/etc/profile.d/目录下新建 paths.sh 文件,专门用来管理 环境变量

mysql path 环境变量 示例

# /etc/profile.d/paths.sh

MYSQL_HOME=/usr/local/mysql
export PATH=$MYSQL_HOME/bin:$PATH

4.2、重新加载环境变量文件

source /etc/profile.d/paths.sh

# 或者
source /etc/profile

5、环境变量文件详解

5.1、~/.bashrc

if [ -f /etc/bashrc ]; then
	. /etc/bashrc
fi

这段的意思是如果存在 /etc/bashrc 文件,则先加载 /etc/bashrc 文件

5.2、/etc/bashrc

# /etc/bashrc

# System wide functions and aliases
# Environment stuff goes in /etc/profile

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

系统级别的功能和别名

环境相关的内容会放在/etc/profile中

更改这个文件不是一个好主意,除非你知道这样做的意义

更好的做法是在/etc/profile.d/目录下新建一个custom.sh 的shell文件来存放相关内容

5.3、/etc/profile

# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

文件中下面还有一段

if [ -n "${BASH_VERSION-}" ] ; then
        if [ -f /etc/bashrc ] ; then
                # Bash login shells run only /etc/profile
                # Bash non-login shells run only /etc/bashrc
                # Check for double sourcing is done in /etc/bashrc.
                . /etc/bashrc
       fi
fi

5.4、~/bash_profile

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi

# User specific environment and startup programs

如果存在 ~/.bashrc 文件,则先加载 ~/.bashrc 文件

用户自定义环境和启动程序在这里定义

 

海涛贝塔(https://haitaobeta.com)属于海涛个人博客,欢迎浏览使用

联系方式:qq:52292959 邮箱:52292959@qq.com

备案号:粤ICP备18108585号 友情链接