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
相关推荐
Damon小智8 小时前
玩转CodeX:CodeX安装教程(Windows+Linux+MacOS)
linux·windows·macos·ai·ai编程·codex·gpt-5
小番茄夫斯基12 小时前
团队效率神器!Mac 下 Homebrew 从入门到精通
macos
空安小菜鸟19 小时前
Mac 重启电脑导致代理失效
macos
sweethhheart3 天前
【typora激活使用】mac操作方式
前端·数据库·macos
库奇噜啦呼3 天前
【iOS】简单的四则运算
macos·ios·cocoa
HoJunjie3 天前
macOS sequoia 15.7.1 源码安装node14,并加入nvm管理教程
macos·node.js
心灵宝贝3 天前
Principal v6.15 中文汉化版安装教程|Mac .dmg 文件安装步骤详解
macos
你好龙卷风!!!3 天前
mac | Windows 本地部署 Seata1.7.0,Nacos 作为配置中心、注册中心,MySQL 存储信息
windows·mysql·macos
源文雨4 天前
MacOS 下 Warp ping 局域网设备报错 ping: sendto: No route to host 的解决方法
运维·网络协议·安全·macos·网络安全·ping
liulilittle4 天前
macOS 内核路由表操作:直接 API 编程指南
网络·c++·macos·策略模式·路由·route·通信