Linux 设置环境变量

优雅的在 Linux 上设置环境变量

现有教程存在的问题

现在的教程,不是放在 /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
  1. 创建并编辑 /etc/profile.d/usr_env.sh

    1#!/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
    
  2. 创建 ~/.local/profile.d 文件夹并创建编辑 *.sh,比如 bin.sh:

    1if test -d ${HOME}/.local/bin; then
    2    export PATH="${HOME}/.local/bin:${PATH}"
    3fi
    
  3. 注销后重新登录生效

CC BY-NC-SA 4.0 转载或引用本文时请遵守许可协议,注明出处、不得用于商业用途!
最后更新于 Apr 28, 2023 02:38 +0800
人最重要的特点是会思考,写博客的初衷是保存思维的电子快照。 当然各种文档工具亦或是简单的文本编辑器也能随时记录点滴,选择建个人网站无非是想满足技术爱好者的偏执。
Built with Hugo
主题 StackJimmy 设计