Mac 终端命令与 Linux 有高度相似性,但也存在关键差异。以下是详细对比分析及注意事项:
ls, cd, cp, mv, rm, grep, cat, chmod 等)在两者中行为一致。bash(macOS 10.15+ 已改为 zsh,但 bash 仍可安装使用)。/bin, /usr, /etc, /tmp 等目录(但 macOS 部分路径不同,如用户目录在 /Users 而非 /home)。| 命令/功能 | macOS (BSD 系) | Linux (GNU 系) |
|---|---|---|
sed/awk |
BSD 版本,参数可能不同 | GNU 版本,功能更丰富 |
ps |
选项为 -ef 或 -aux |
通常仅 -aux(BSD 风格兼容) |
grep |
默认不支持 -P(PCRE 正则) |
通常支持 -P |
find |
-print0 需显式指定 |
部分发行版默认支持 |
brew(包管理)、say(语音合成)、open(打开文件/应用)、diskutil(磁盘工具)。apt/yum(包管理)、systemctl(服务管理)、ip(网络配置,macOS 用 ifconfig/netstat)。brew(第三方),Linux 原生支持 apt/dnf/pacman 等。launchctl,Linux 用 systemd/sysvinit。APFS/HFS+,支持 brew install coreutils 安装 GNU 工具。# 通过 Homebrew 安装 GNU 核心工具
brew install coreutils findutils gnu-sed grep
安装后,命令会带 g 前缀(如 gsed, ggrep),可通过 PATH 配置覆盖默认命令。
在 ~/.zshrc 或 ~/.bashrc 中添加别名或 PATH 调整:
# 优先使用 GNU 工具
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
#!/bin/bash)。bash
if [[ "$(uname)" == "Darwin" ]]; then
# macOS 专用代码
else
# Linux 专用代码
fised -i 报错sed 必须指定备份后缀(如 sed -i '' 's/foo/bar/' file)。gsed(GNU 版本)或适配语法。/bin/sh 行为不同/bin/sh 是 BSD bash,某些 Linux 发行版链接到 dash。#!/bin/bash。man command 查看当前系统的手册页,确认参数是否兼容。通过上述方法,可以最大限度减少 macOS 与 Linux 终端命令的差异影响。