跳转至

如何新增PATH环境变量

概要: Linux如何查看和新增PATH环境变量

创建时间: 2022.11.15 22:39:44

更新时间: 2023.07.30 23:47:39

PATH环境变量是什么

PATH is an environmental variable in Linux and other Unix-like operating systems that tells the shell which directories to search for executable files (i.e., ready-to-run programs) in response to commands issued by a user. It increases both the convenience and the safety of such operating systems and is widely considered to be the single most important environmental variable.

简单来说,PATH 是用来告诉Linux Shell搜索可执行二进制文件的路径的集合,多个PATH使用 : 分割

如何查看PATH

使用 printenv

Bash
printenv PATH

使用 echo

Bash
echo $PATH

image.png

添加新的PATH

假设我们需要将用户主目录下的 bin 文件夹作为新的PATH,即添加 $HOME/binPATH,有两种方式可选

临时添加

Bash
export PATH="$HOME/bin:$PATH"
在临时添加的情况下,可以立即生效,但打开新的终端会失效
image.png

永久添加

/etc/environment

即持久化到配置文件 /etc/environment

Bash
vim /etc/environment
追加自定义的PATH,即 /root/bin 到行尾即可
image.png
重新打开新的终端窗口即可生效
image.png

/etc/profile.d/path.sh

/etc/profile.d 目录下增加一个可执行的sh后缀脚本即可,在用户登录启动shell时,系统会自动执行这些脚本

Bash
echo "export PATH=$HOME/bin:$PATH" > /etc/profile.d/path.sh
同上,重新打开新的终端窗口即可生效

参考