现有教程存在的问题
现在的教程,不是放在 /etc/environment、/etc/profile 就是 ~/.bashrc
/etc/environment及~/.config/environment.d/仅接受key=value格式,这将导致部分重复使用变量的写法不可用,比如:1export $JAVA_HOME="/path/to/jdk" 2export $PATH="${JAVA_HOME}/bin:${PATH}"~/.bashrc仅对 bash 中运行的程序有效,对于桌面程序无效/etc/profile为全局变量,会造成用户 Token 泄露
优雅的解决方案
- 使用
/etc/profile.d/usr_env.sh加载对应用户的的~/.local/profile.d/*.sh - 对应用户只会加载自己目录下的环境变量文件,不会将一些关于密钥的环境变量泄露到其他用户
- 环境变量在对应用户的作用域下是全局生效的,不局限于终端
- 如果要设置系统变量,创建并编辑
/etc/profile.d/global.sh
创建并编辑
/etc/profile.d/usr_env.sh1#!/bin/sh 2if test -d ${HOME}/.local/profile.d; then 3 for profile in ${HOME}/.local/profile.d/*.sh; do 4 test -r "$profile" && . "$profile" 5 done 6 unset profile 7fi创建
~/.local/profile.d文件夹并创建编辑*.sh,比如bin.sh:1if test -d ${HOME}/.local/bin; then 2 export PATH="${HOME}/.local/bin:${PATH}" 3fi注销后重新登录生效