shell

sh

/bin/sh is a wrapper that forwards to another shell. If the link /private/var/select/sh is present, the shell pointed to by this link is started. Otherwise, one of fallbacks (bash, dash, or zsh) is executed.

more info see man sh

指定 sh 为 dash

sudo ln -sf /bin/dash /private/var/select/sh

path helper

macOS 自带的命令行工具,负责整理终端环境变量 PATH。

# path_helper 本身不在 `PATH` 里
/usr/libexec/path_helper -s

终端启动时,/etc/profiles 会调用它,读取:

/etc/paths
/etc/paths.d/*
# 实际文件在 /private/etc/.... ,指向 /etc,由 macos 处理

brew会自动添加 /etc/paths.d/brew

command line tools

Command Line Tools默认安装在:

/Library/Developer/CommandLineTools

其中真实的可执行工具位于:

/Library/Developer/CommandLineTools/usr/bin

PATH

该目录 不会被自动加入 PATH。

/usr/bin 中的开发工具,以 gcc 为例:

which gcc
/usr/bin/gcc
 
ls -l /usr/bin/gcc
-rwxr-xr-x root wheel 116K /usr/bin/gcc

/usr/bin/gcc 是 Apple 提供的 shim(包装器)可执行文件,不是软链接

macOS 使用一个全局的 "Developer Directory" 该路径决定了开发工具的实际来源

xcode-select -p
 
/Library/Developer/CommandLineTools
/Applications/Xcode.app/Contents/Developer

shim 的工作方式

# 当执行:
gcc main.c
# 实际执行流程为:
shell
└── /usr/bin/gcc (shim)
└── xcrun
└── $DEVELOPER_DIR/usr/bin/gcc

shim 程序通过 xcrun:

  1. 读取当前 Developer Directory
  2. 在对应目录下查找同名工具
  3. 执行找到的真实可执行文件

使用 xcrun 可以直接解析真实路径:

xcrun --find gcc
xcrun --find git
xcrun --find clang

shim 优点

  • 支持在 CLT 与 Xcode 之间切换

    切换当前使用的开发工具目录:

    sudo xcode-select --switch /Library/Developer/CommandLineTools
    sudo xcode-select --switch /Applications/Xcode.app

    切换后,/usr/bin/* 的行为会随之改变,无需调整 PATH。

  • xcode-select --switch 可以在不修改 PATH 的情况下生效

  • /usr/bin 受系统完整性保护(SIP),作为稳定入口

  • 允许统一调度所有开发工具,而不是只改变单一可执行文件