Mac 环境变量配置基础教程

MacOS 下一般配置有多个 Shell,如 Bash、ZSH 等,不同的 Shell 其创建 Terminal 时使用的环境变量配置文件也不尽相同,但一般都会读取并执行脚本文件 /etc/profile 来加载系统级环境变量,而用户级别环境变量,一般都会在各自 Shell 的 Home 路径下配置,即 Bash~/.bash_profileZSh~/.zprofile,以及 SH 的 ~/.profile 等。

配置系统环境变量

为了尽量统一控制系统级别环境变量,同时支持可插拔,因此本文参考了 Ubuntu 的 Bash Shell 加载方式,通过修改 /etc/profile 脚本来实现。

/etc/profile 脚本中增加下列内容(如果没有写入权限,建议先用 sudo 来进行 chmod +w,之后再执行 chmod -w 还原权限):

bash 复制代码
if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

然后创建 /etc/profile.d 文件夹,并在其中增加需要加载环境变量的 sh 脚本,如:

bash 复制代码
# /etc/profile.d/
$ tree /etc/profile.d/
/etc/profile.d/
└── env.sh

# env.sh
eval "$(/opt/homebrew/bin/brew shellenv)"

修改用户环境变量

用户级别环境变量,一般都会在各自 Shell 的 Home 路径下配置,即 Bash~/.bash_profileZSh~/.zprofile,以及 SH 的 ~/.profile 等。

因为不同 Shell 的用户路径和环境变量配置脚本不同,因此可能无法实现统一配置,目前还是需要在各自的脚本文件中分别多次配置。

当然,也可以将相同的配置抽离成一个公共的脚本文件,每次在配置时,都执行其脚本即可。

验证结果

关闭所有 Terminal 后重启 Shell,然后验证环境变量是否配置成功。

bash 复制代码
brew help
相关推荐
Swift社区19 小时前
Mac与Windows终端常用指令对比整理(实用避坑分享)
macos
Java小白笔记20 小时前
Docker 安装配置完全指南:MacOS 、Windows、Linux环境下的安装、配置与验证
linux·macos·docker
芯日记1 天前
Mac-使用文本编辑的html浏览器打开出现源代码问题
macos·html
一牛1 天前
Swift 循环引用
macos·ios
食尘者1 天前
MacBook Pro M5Max 本地大模型推理实践
macos·aigc
x-cmd2 天前
Mac 涨价后,本地 AI 还能千元入门吗?
linux·人工智能·macos·ai·agent·amd·本地ai入门
m0_377108142 天前
小智ai-esp32
人工智能·macos·xcode
测试改改2 天前
共享mac有线网络手机可连接
macos·智能手机
Lvan的前端笔记3 天前
python:Mac 系统 uv 完整安装+入门实战
python·macos·uv
pop_xiaoli3 天前
【iOS】离屏渲染
macos·ios·objective-c·cocoa