跳转到内容

macOS 命令速查

新机第一件事。官方安装脚本会自行处理 Command Line Tools 依赖。

终端窗口
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Apple Silicon 上 Homebrew 装在 /opt/homebrew,需要把它写进当前 shell 的环境:

终端窗口
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"

把已装的东西导出成清单,换机时一条命令还原,比逐个 brew install 可靠得多。

终端窗口
# Export what is currently installed
brew bundle dump --describe --force --file=~/Brewfile
# Restore on a new machine
brew bundle install --file=~/Brewfile
# Remove anything not listed in the Brewfile
brew bundle cleanup --force --file=~/Brewfile

默认用 ed25519,比 RSA 更短也更快。注释里写清楚这把钥匙属于哪台机器。

终端窗口
ssh-keygen -t ed25519 -C "laptop-$(date +%Y%m)" -f ~/.ssh/id_ed25519
# Load it into the agent and the macOS keychain
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
# Copy the public key to the clipboard
pbcopy < ~/.ssh/id_ed25519.pub

启动开发服务器之前先确认端口是空的。

终端窗口
# Who is listening on port 4321
lsof -nP -iTCP:4321 -sTCP:LISTEN
# Kill it once you are sure
kill -15 <PID>

典型症状:能连上 Wi-Fi,但什么都打不开;同一个网络下别人正常;这台机器换个网络也正常。这说明网卡和路由器本身都没坏,问题出在「这台机器 × 这个网络」这一对组合上。

有网的时候(比如手机热点)直接跑脚本,它会从网卡往上逐层探测,指出第一个断掉的层:

终端窗口
curl -fsSL https://hub.skillnav.dev/net.sh | sh
# Same run, plus the two safe repairs: flush DNS, renew an existing DHCP lease
curl -fsSL https://hub.skillnav.dev/net.sh | sh -s -- --fix

脚本下载不下来的时候(网全断了就是这种情况),手敲下面四条,按同样的顺序判断:

终端窗口
# 1. Address, and whether it came from DHCP or was typed in by hand
ipconfig getifaddr en0
networksetup -getinfo "Wi-Fi" | head -n 5
# 2. Can the router be reached at all
netstat -nrf inet | awk '/^default/ {print $2; exit}'
ping -c 2 $(netstat -nrf inet | awk '/^default/ {print $2; exit}')
# 3. Public IP, bypassing DNS entirely
ping -c 2 223.5.5.5
# 4. Name resolution, and which servers are configured
networksetup -getdnsservers "Wi-Fi"
dscacheutil -q host -a name www.apple.com

怎么读这四条:

卡在哪 结论
拿不到地址,或是 169.254.x.x DHCP 没应答。可以试 sudo ipconfig set en0 DHCP,但注意它会先拆掉该接口上已有的 IPv4 服务再建一个临时服务(见 man ipconfig),不是无害的续租;仍是这个地址就是路由器侧拦了这台机器
第二行显示 Manual Configuration,且网关 ping 不通 静态 IP 是别的网络留下的残留,sudo networksetup -setdhcp "Wi-Fi" 改回自动
网关 ping 不通 路由器按 MAC 过滤。「私有 Wi-Fi 地址」开着时,这台机器每次都像陌生设备
网关通、223.5.5.5 不通 Portal 认证没过,或这台设备被上游拦了
223.5.5.5 通、域名解析失败 DNS 问题。networksetup -getdnsservers 有值就说明手工填过别处的 DNS
全通但浏览器打不开 代理残留,查 networksetup -getwebproxy "Wi-Fi"
终端窗口
# Update formulae and upgrade everything
brew update && brew upgrade
# Reclaim disk space from old versions
brew cleanup --prune=all
# Check for problems before filing a bug
brew doctor