iTerm2终端配置指南

从零打造 macOS 最顺手的终端:iTerm2 + zsh 完全配置指南(小白友好)

一句话:把 macOS 自带的「能用」终端,改造成「顺手、好看、高效」的开发/运维利器。

全文配一份一键脚本,小白照着敲命令也能 30 分钟搞定;每一段配置我都解释了「它到底在干什么」。

目录


一、为什么值得折腾这 30 分钟

macOS 自带 Terminal 能用,但只能用「基本功能」。而作为一名开发者/运维,你每天有大量时间是在终端里度过的------每天敲几百次命令。把这件事的效率提升 30%,一年下来省下的时间相当可观。

iTerm2 本身是个强得多的终端(分屏、搜索、自动补全、Shell Integration),但它默认不做好看、也不做顺手。真正让它脱胎换骨的,是终端 + shell(zsh)+ 一堆命令行小工具的组合拳。

配置完之后你会得到:

  • 一个彩色、带图标、显示 git 分支和命令耗时的提示符
  • Ctrl+R 全屏模糊搜索历史命令(不再靠方向键一条条翻)
  • 彩色 ls、彩色 cat、带行号的漂亮 git diff
  • 智能跳目录 :z 项目名 直达常去目录
  • 分屏、会话保持、图形化 Git(lazygit)
  • 一批运维常用快捷命令:查端口、解压、看目录大小......

这些全部由配置文件驱动------也就是说,今天在 Mac 上配好,以后换任何装了 zsh 的机器(包括 Linux 服务器)都能直接复用同一套配置。


二、你将安装什么(工具清单)

一共 13 个命令行工具,每一个都解决一个具体痛点:

工具 作用 举个例子
fzf 模糊查找神器 Ctrl+T 找文件,Alt+C 跳目录
zoxide 智能目录跳转 z down 直达 ~/Downloads
bat 带语法高亮的 cat cat main.py 自动上色
eza 带图标/颜色的 ls ll 一眼看清文件类型
fd 更快的 find fd test 秒找文件
ripgrep (rg) 更快的 grep 在项目里秒搜关键词
git-delta 美化 git diff gd 输出带行号、彩色并排
direnv 目录级环境变量 进项目自动加载 .envrc
tmux 终端会话复用 断开重连、窗口分屏
atuin 命令历史数据库 Ctrl+R 跨会话搜历史
lazygit 终端 Git 图形界面 键盘操作暂存/提交/分支
zsh-autosuggestions 历史命令自动建议 灰色提示,右方向键采纳
zsh-syntax-highlighting 命令语法高亮 命令打错第一时间变红

外加两个角色:

  • MesloLGS NF 字体------Nerd Font,让终端能显示图标(否则全是方块)
  • Powerlevel10k------最流行的 zsh 提示符主题,好看且信息量大

三、准备工作(两样东西)

3.1 安装 Homebrew(macOS 的软件包管理器)

后面所有工具都靠它装。打开 Terminal 或 iTerm2,执行官方安装命令:

bash 复制代码
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

国内网络如果卡住,换清华镜像版:

bash 复制代码
/bin/bash -c "$(curl -fsSL https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/install.git/install.sh)"

安装过程会要求输入 Mac 登录密码,装完执行 brew --version 有输出即成功。

Apple Silicon(M 系列)机器装完后,可能还需要按提示执行两句把 brew 加进 PATH,照着屏幕上的提示做即可。

3.2 安装 iTerm2

官网下载:https://iterm2.com/downloads.html(下载 .zip 解压后拖进「应用程序」)。

或者用 brew 一条命令:

bash 复制代码
brew install --cask iterm2

装好后打开 iTerm2,本教程的后续操作都在 iTerm2 里进行。


四、正片:一键脚本

4.1 保存脚本

把文末 附录 B 里的完整脚本复制下来,保存成文件 ~/setup.sh。三种办法任选:

办法一:用 nano 编辑器(推荐小白)

bash 复制代码
nano ~/setup.sh

把脚本内容粘贴进去 → 按 Ctrl + O 回车保存 → 按 Ctrl + X 退出。

办法二:用图形化文本编辑器

打开「文本编辑」(TextEdit)→ 新建文稿 → 粘贴内容 → 存为 setup.sh(位置选你的用户主目录,即 ~)。

办法三:如果你把脚本托管在了 GitHub / 自己的博客

bash 复制代码
curl -fsSL https://你的地址/setup.sh -o ~/setup.sh

4.2 运行

bash 复制代码
bash ~/setup.sh

脚本会依次完成:

  1. 检查 Homebrew 是否就位
  2. 安装 13 个命令行工具
  3. 安装 Nerd Font 字体(brew 失败会自动改从官方源下载)
  4. 克隆 Powerlevel10k 并下载预设
  5. 生成 .zshrc / .tmux.conf / lazygit 配置 / iTerm2 主题(旧文件自动备份)
  6. 配置 git 使用 delta
  7. 逐项校验并在最后打印结果

关于网络 :如果你在国内且 GitHub 很慢,打开脚本顶部,把 PROXY="http://127.0.0.1:7897" 这行的注释去掉、改成你自己的代理端口(Clash 默认就是 7897),脚本会自动走代理下载字体和 p10k。

跑完看到 ✅ 全部完成! 就成功了。脚本可以重复执行------已经装好的会自动跳过,中途某个包失败重跑一次即可。

4.3 生效

bash 复制代码
# 完全退出 iTerm2(⌘Q)再重新打开,或者在终端里执行:
source ~/.zshrc

五、逐段拆解:这些配置到底在做什么

一键脚本替你写好了一切,但看懂它才是这篇文章的价值。下面挑几个关键部分讲。

5.1 字体:为什么必须先装

终端里的图标、进度条、git 分支符号,都来自一种叫 Nerd Font 的字体------它在普通字体的基础上「塞」进了几千个图标字形。不装它,你的提示符就会显示成一堆 □ 方块。

我们用的是 MesloLGS NF(Powerlevel10k 官方推荐),手工安装也很简单:

bash 复制代码
brew install --cask font-meslo-lg-nerd-font

装完后字体在系统级生效,任何 app 都能选到它。

5.2 .zshrc:zsh 的总配置

.zshrc 是 zsh 每次启动都会读的配置文件,放在家目录(~/.zshrc)。它分几大块:

(1)历史记录------让它变聪明

zsh 复制代码
HISTSIZE=200000
SAVEHIST=200000
setopt SHARE_HISTORY          # 多个终端窗口共享历史
setopt HIST_IGNORE_ALL_DUPS   # 去掉重复命令
setopt HIST_IGNORE_SPACE      # 以空格开头的命令不记录(临时命令)
setopt INC_APPEND_HISTORY     # 命令立即写入历史(防止崩溃丢失)
setopt EXTENDED_HISTORY       # 记录每条命令的执行时间

最实用的是 HIST_IGNORE_SPACE:命令前敲一个空格,这条命令就不会被记录(比如临时输入的密码相关命令)。以及把历史上限拉到 20 万条,基本等于「永不丢历史」。

(2)交互体验------少打几个字

zsh 复制代码
setopt AUTO_CD               # 直接输入目录名就进入该目录
setopt CORRECT               # 命令拼错时给出纠正建议

AUTO_CD 很爽:想进 ~/projects,直接敲 projects 就行,不用敲 cd。

(3)补全------忽略大小写

zsh 复制代码
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'

敲 cd down 按 Tab,也能补全出 Downloads。

(4)工具集成------把上面的工具接进来

zsh 复制代码
command -v fzf >/dev/null 2>&1 && source <(fzf --zsh)
command -v zoxide >/dev/null 2>&1 && eval "$(zoxide init zsh)"
command -v direnv >/dev/null 2>&1 && eval "$(direnv hook zsh)"
command -v atuin >/dev/null 2>&1 && eval "$(atuin init zsh)"

注意每一行都用 command -v xxx && 包了一层------意思是「这个工具装了才启用」。这样即使某个工具没装成功,也不会报错、不会影响终端启动。

(5)别名与函数------把长命令变短

zsh 复制代码
alias ll='eza -lh --icons --group-directories-first --git'
alias gl='git log --oneline --graph --decorate -20'
alias lg='lazygit'

ports() {   # 查端口占用
  if [ -z "$1" ]; then
    lsof -nP -iTCP -sTCP:LISTEN
  else
    lsof -nP -iTCP:"$1" -sTCP:LISTEN
  fi
}

ports 8080 就能直接告诉你 8080 端口被谁占了------运维救火时非常好用。

5.3 Powerlevel10k:把提示符变好看

p10k 是一款 zsh 主题,能在提示符里显示:当前目录、git 分支与状态、上一条命令是否成功、执行耗时、Python/Node 版本等。

配置里这两行加载它:

zsh 复制代码
[[ -f ~/powerlevel10k/powerlevel10k.zsh-theme ]] && source ~/powerlevel10k/powerlevel10k.zsh-theme
[[ -f ~/.p10k.zsh ]] && source ~/.p10k.zsh

第一行是主题本体,第二行是样式预设。脚本已经帮你下了官方 lean 预设,如果你想要别的风格,终端里执行:

bash 复制代码
p10k configure

会弹出一个交互式向导,问你喜欢什么图标、什么风格,一路选完自动生成新的 ~/.p10k.zsh。

p10k 还有个「瞬时提示符」技巧(脚本已配):它让终端先秒开、再渲染提示符 ,避免启动时卡半秒。这就是 .zshrc 第一段那几行的作用。

5.4 tmux:会话保持与分屏

tmux 是终端复用器。核心价值:SSH 到服务器后,网络断了会话也不丢;以及在一个窗口里分屏跑多个任务。

脚本里把默认前缀键从 Ctrl+b 改成了更好按的 Ctrl+a,并把分屏键位改得更直观:

tmux 复制代码
set -g prefix C-a
bind | split-window -h -c "#{pane_current_path}"   # 前缀 + |  左右分屏
bind - split-window -v -c "#{pane_current_path}"   # 前缀 + -  上下分屏
set -g mouse on                                     # 支持鼠标

常用操作:Ctrl+a 然后按 | 或 - 分屏,Ctrl+a + h/j/k/l 在窗格间移动,Ctrl+a + r 重载配置。

5.5 lazygit:图形化 Git

还在手敲 git add / git commit / git log?lazygit 把 Git 操作变成了键盘驱动的图形界面:左边文件树、右边 diff、下面提交历史,一目了然。

在任意 git 仓库里敲 lg(脚本里的别名)就能打开。配合 delta,diff 显示得非常漂亮。

5.6 git 的 diff 美化

脚本还会顺手把 git 的 diff 分页器换成 delta:

bash 复制代码
git config --global core.pager "delta"
git config --global delta.line-numbers true
git config --global delta.syntax-theme "OneHalfDark"
git config --global merge.conflictStyle "zdiff3"

之后 git diff 就是带行号、语法高亮的输出了。


六、iTerm2 图形界面设置(点几下)

配置文件和 shell 都搞定了,还差 iTerm2 本体的几个开关。打开设置:⌘ + ,

6.1 设为默认配置

Profiles → 左侧选中 OneDark → 左下角 Other Actions... → Set as Default

(脚本写入的主题一般会自动成为默认;若打开终端发现配色字体没变,就做这一步。)

6.2 安装 Shell Integration(强烈建议)

顶部菜单 → iTerm2 → Install Shell Integration

装好后你将获得三个杀手级能力:

  • ⌘ + ↑ / ⌘ + ↓ 在历史命令之间整块跳转(看日志、复跑命令极爽)
  • 每条命令左侧显示退出状态(失败的命令一目了然)
  • 自动记录命令执行的目录与主机名

6.3 两个体验小开关

位置 设置项 建议
General → Selection Copy to pasteboard on selection 勾选(选中即复制)
General → Pointer Focus follows mouse 勾选(鼠标划过即聚焦)

可选 :Profiles → Window → Transparency 调到 10%~15%,背景半透明更好看。


七、快捷键速查

iTerm2 自带

快捷键 功能
⌘ + D / ⌘ + ⇧ + D 左右 / 上下分屏
⌘ + T / ⌘ + W 新标签 / 关标签
⌘ + ← / ⌘ + → 切换标签页
⌥ + ⌘ + 方向键 在分屏之间移动焦点
⌘ + ⇧ + Enter 当前窗格最大化 / 还原
⌘ + K 清屏
⌘ + F / ⌘ + G 搜索 / 下一个
⌘ + ; 基于历史的自动补全
⌘ + ↑ / ⌘ + ↓ 上一条 / 下一条命令(需 Shell Integration)

新工具带来的

快捷键 功能
Ctrl + R atuin 全屏模糊搜索历史命令
Ctrl + T fzf 模糊查找文件,回车插入路径
Alt + C fzf 查找目录并跳转
→(行尾) 采纳灰色自动建议的命令
Ctrl + → 一次采纳建议的一个词

八、别名与函数速查

命令 实际执行
ls / ll / la 彩色 ls / 详细列表+git / 含隐藏文件
lt / ltt 树状显示 2 / 3 层
cat bat(语法高亮)
gs ga gc gp git status / add / commit / pull
gl / gd 漂亮提交图 / 美化 diff
lg 打开 lazygit
.. / ... / .... 返回上 1 / 2 / 3 级目录
reload 重新加载 .zshrc
运维函数 功能
ports / ports 8080 列出监听端口 / 查某端口被谁占用
extract a.tar.gz 万能解压(zip/tar.gz/xz/rar/7z...)
mkcd foo/bar 建多级目录并进入
myip 查看本机局域网 IP
psg nginx 搜索含 nginx 的进程
serve 8080 当前目录起 HTTP 服务
bigdirs 列出当前目录最大的 10 项
z 关键词 zoxide 智能跳转到常去目录

九、常见问题(FAQ)

Q1:提示符图标显示成方块 / 问号?

字体没生效。⌘ + , → Profiles → Text → Font 手动选 MesloLGS NF,字号建议 14。

Q2:终端启动时出现一堆 compinit: 权限 警告?

执行一条命令修复即可:

bash 复制代码
compaudit | xargs chmod g-w

Q3:Ctrl+R 想用回原来的历史搜索?

编辑 ~/.zshrc,把 eval "$(atuin init zsh)" 那行注释掉,reload 即可。

Q4:atuin 一定要注册账号吗?

不用。默认本地模式,历史存在本地 SQLite。注册登录后可跨设备同步历史,多机器运维场景很值。

Q5:p10k 提示符想换风格 / 觉得太花?

终端执行 p10k configure,跟着向导重选一遍即可。

Q6:想换配色?

⌘ + , → Profiles → Colors → Color Presets,选内置方案(如 Solarized Dark),会覆盖当前的 One Dark。

Q7:脚本把 .zshrc 覆盖了,我的旧配置呢?

脚本在覆盖前会自动备份成 ~/.zshrc.bak.时间戳。想还原就把它拷回去。同理 tmux、lazygit、iTerm2 配置都有备份。

Q8:iTerm2 界面全是英文,能变中文吗?

官方没有中文界面(应用内不含任何中文本地化文件,改系统语言也无效)。可以对照文末附录 A 的中英对照表使用。

Q9:想彻底回滚?

bash 复制代码
# 恢复 zsh 配置
cp ~/.zshrc.bak.<时间戳> ~/.zshrc
# 删掉 iTerm2 主题(回到默认外观)
rm ~/Library/Application\ Support/iTerm2/DynamicProfiles/onedark.json

十、结语:这套配置的价值

很多人以为「终端配置」只是折腾好看。其实这套东西的真正价值在于肌肉记忆的复用:

  • .zshrc、.tmux.conf、lazygit 配置都是纯文本,可以直接拷到任何一台装了 zsh 的机器(Mac 或 Linux 服务器),一秒获得同样的顺手环境;
  • 别名和函数是你自己工作流的沉淀,用得越久越值钱;
  • 所有工具都是开源、可替换的,没有厂商锁定。

一次配置,长期受益。配好之后你会发现自己越来越懒得离开终端------这大概就是对它最好的评价。


附录 A:iTerm2 界面中英对照速查表

A.1 顶部菜单栏

英文 中文 快捷键
iTerm2 iTerm2
├ Settings... 设置... ⌘,
├ Check for Updates 检查更新
└ Quit iTerm2 退出 ⌘Q
Shell 命令
├ New Window 新建窗口 ⌘N
├ New Tab 新建标签页 ⌘T
├ Split Vertically 左右分屏 ⌘D
├ Split Horizontally 上下分屏 ⌘⇧D
├ Clear Buffer 清屏 ⌘K
├ Reset 重置(卡死时救命) ⌘R
├ Broadcast Input 广播输入(多窗口同步输入)
└ tmux tmux 集成
Edit 编辑
├ Find... 查找... ⌘F
├ Find Next / Previous 查找下一个 / 上一个 ⌘G / ⌘⇧G

| └ Emoji & Symbols | 表情与符号 | ⌃⌘Space |

| View | 视图 | |

| ├ Show/Hide Tab Bar | 显示 / 隐藏标签栏 | |

| ├ Enter Full Screen | 进入全屏 | ⌘↵ |

| ├ Make Text Bigger / Smaller | 放大 / 缩小字号 | ⌘+ / ⌘- |

| └ Status Bar | 状态栏 | |

| Profiles | 配置 | |

| ├ Manage Profiles... | 管理配置... | |

| └ New Window with Profile | 用指定配置新建窗口 | |

| Window | 窗口 | |

| ├ Minimize | 最小化 | ⌘M |

| └ Merge All Windows | 合并所有窗口 | |

| Help | 帮助 | |

| └ View Keyboard Shortcuts | 查看键盘快捷键 | |

A.2 设置面板左侧标签页(⌘,)

英文 中文 说明
General 通用 启动、关闭、选择、Shell 集成
Appearance 外观 窗口、标签、窗格的样式
Profiles 配置 最常改的都在这(字体/配色/透明度)
Keys 按键 快捷键绑定
Pointer 指针 鼠标行为
Arrangements 窗口排列 保存/恢复窗口布局
Advanced 高级 上百个隐藏开关(右上搜索框直接搜)

Profiles 子标签 :General 通用 · Colors 颜色 · Text 文本 · Window 窗口 · Terminal 终端 · Session 会话 · Keys 按键

A.3 高频英文项

英文 中文 位置
Font / Non-ASCII Font 字体 / 非 ASCII 字体 Profiles → Text
Cursor 光标样式 Profiles → Text
Color Presets 配色预设 Profiles → Colors
Transparency / Blur 透明度 / 背景模糊 Profiles → Window
Unlimited scrollback 无限回滚 Profiles → Terminal
Silence bell 静音响铃 Profiles → Terminal
Badge 徽章(窗格角落水印) Profiles → General
Working Directory 工作目录 Profiles → General
Semantic History 语义历史(⌘点击打开文件) Profiles → General
Status bar enabled 启用状态栏 Profiles → Session

A.4 高频术语

英文 中文 含义
Profile 配置 一套「外观+行为」方案,可建多个
Pane 窗格 分屏出来的一块区域
Tab 标签页 同一窗口内的多个会话页
Session 会话 一个 shell 进程
Buffer / Scrollback 缓冲区 / 回滚历史 往上翻能看到的旧内容
Shell Integration Shell 集成 命令标记、跳转、失败标红
Semantic History 语义历史 ⌘点击文件名直接打开
Trigger 触发器 匹配到指定文本自动执行动作
Badge 徽章 窗格角落的水印文字
Broadcast Input 广播输入 一个窗口打字,多个窗口同步输入
Hotkey Window 热键窗口 按键从屏幕上沿滑出的下拉终端

A.5 常见需求 → 操作路径

我想... 路径
改字体大小 Settings → Profiles → Text → Font
换配色 Settings → Profiles → Colors → Color Presets
让某配置成为默认 Settings → Profiles → 选中 → 左下 Other Actions... → Set as Default
装 Shell Integration 菜单 iTerm2 → Install Shell Integration
背景半透明 Settings → Profiles → Window → Transparency
改快捷键 Settings → Keys → Key Bindings
关掉响铃 Settings → Profiles → Terminal → Silence bell
恢复出厂设置 iTerm2 → Settings → General → Preferences → Load preferences from...

附录 B:完整一键脚本

把下面内容整段复制,保存为 ~/setup.sh,然后在 iTerm2 里执行 bash ~/setup.sh。

bash 复制代码
#!/usr/bin/env bash
# ============================================================================
#  iTerm2 完美终端 ------ 一键安装脚本
# ----------------------------------------------------------------------------
#  作用:把 iTerm2 从「能用的裸奔状态」变成「运维开发顺手的利器」
#  内容:安装 13 个命令行工具 + Nerd Font 字体 + Powerlevel10k 提示符
#        并自动生成 .zshrc / .tmux.conf / lazygit / iTerm2 主题配置
#
#  用法:打开 iTerm2,执行
#           bash setup.sh
#
#  说明:仅支持 macOS。脚本可重复执行,已装的会自动跳过;
#        会覆盖的旧配置一律先备份成 xxx.bak.时间戳
# ============================================================================

set -uo pipefail

# ---------- 若在国内且 GitHub 慢,取消下面一行的注释填上你的代理端口 ----------
# PROXY="http://127.0.0.1:7897"

PROXY="${PROXY:-}"
CURL_OPTS=(-fsSL)
GIT_OPTS=()
if [ -n "$PROXY" ]; then
  CURL_OPTS+=(-x "$PROXY")
  GIT_OPTS+=(-c "http.proxy=$PROXY" -c "https.proxy=$PROXY")
fi

# ---------- 颜色输出 ----------
GREEN='\033[0;32m'; BLUE='\033[0;34m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
info() { printf "${BLUE}▶ %s${NC}\n" "$*"; }
ok()   { printf "${GREEN}  ✓ %s${NC}\n" "$*"; }
warn() { printf "${YELLOW}  ! %s${NC}\n" "$*"; }
err()  { printf "${RED}  ✗ %s${NC}\n" "$*"; }
title() { printf "\n${BLUE}══════════════════════════════════════════════${NC}\n  %s\n${BLUE}══════════════════════════════════════════════${NC}\n" "$*"; }

backup() {  # backup <文件>:存在则备份
  if [ -e "$1" ]; then
    local b="$1.bak.$(date +%Y%m%d-%H%M%S)"
    cp -R "$1" "$b" && warn "已备份原文件 → $b"
  fi
}

title "iTerm2 完美终端 · 一键安装"

# ============================================================================
# 0. 环境检查
# ============================================================================
info "[0/6] 环境检查"
if [ "$(uname -s)" != "Darwin" ]; then
  err "本脚本仅支持 macOS。"; exit 1
fi
ok "macOS $(sw_vers -productVersion)"

if ! command -v brew >/dev/null 2>&1; then
  err "未检测到 Homebrew(macOS 的软件包管理器),它是后续安装的基础。"
  echo
  echo "  请先执行下面这条命令安装 Homebrew(需要输入 Mac 登录密码):"
  echo
  echo '  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
  echo
  echo "  国内网络慢的话,用清华镜像版:"
  echo
  echo '  /bin/bash -c "$(curl -fsSL https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/install.git/install.sh)"'
  echo
  echo "  装好后重新运行:bash setup.sh"
  exit 1
fi
ok "Homebrew $(brew --version | head -1 | awk '{print $2}')"

if [ "$(uname -m)" = "arm64" ]; then BREW_PREFIX=/opt/homebrew; else BREW_PREFIX=/usr/local; fi
ok "CPU 架构 $(uname -m)(brew 前缀 $BREW_PREFIX)"

export HOMEBREW_NO_AUTO_UPDATE=1

# ============================================================================
# 1. 安装命令行工具
# ============================================================================
info "[1/6] 安装 13 个命令行工具(首次约 1~3 分钟)"
brew install fzf zoxide bat eza fd ripgrep git-delta direnv tmux atuin lazygit \
             zsh-autosuggestions zsh-syntax-highlighting || warn "部分包安装失败,可再次运行本脚本重试"

# ============================================================================
# 2. 安装 Nerd Font 字体(图标不乱码的关键)
# ============================================================================
info "[2/6] 安装 Meslo Nerd Font 字体"
if brew install --cask font-meslo-lg-nerd-font >/dev/null 2>&1; then
  ok "字体已通过 Homebrew 安装"
else
  warn "Homebrew 安装字体失败,改用官方源直接下载..."
  mkdir -p ~/Library/Fonts
  for f in "MesloLGS NF Regular.ttf" "MesloLGS NF Bold.ttf" "MesloLGS NF Italic.ttf" "MesloLGS NF Bold Italic.ttf"; do
    enc=$(printf '%s' "$f" | sed 's/ /%20/g')
    if curl "${CURL_OPTS[@]}" -o "$HOME/Library/Fonts/$f" \
        "https://github.com/romkatv/powerlevel10k-media/raw/master/$enc"; then
      ok "下载 $f"
    else
      err "下载 $f 失败"
    fi
  done
fi

# ============================================================================
# 3. 安装 Powerlevel10k 提示符主题
# ============================================================================
info "[3/6] 安装 Powerlevel10k 提示符"
if [ ! -d ~/powerlevel10k ]; then
  if ! git "${GIT_OPTS[@]}" clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k 2>/dev/null; then
    warn "GitHub 直连失败,改用镜像 gh-proxy.com..."
    git "${GIT_OPTS[@]}" clone --depth=1 https://gh-proxy.com/https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k \
      || err "p10k 克隆失败,请配置代理后重试(见脚本顶部 PROXY)"
  fi
fi
[ -d ~/powerlevel10k ] && ok "powerlevel10k 就位"

# 下载官方 lean 预设(省去手动跑配置向导)
if [ ! -f ~/.p10k.zsh ]; then
  if curl "${CURL_OPTS[@]}" -o ~/.p10k.zsh \
      "https://raw.githubusercontent.com/romkatv/powerlevel10k/master/config/p10k-lean.zsh"; then
    ok "已下载 p10k lean 预设(想自定义可执行 p10k configure)"
  else
    warn "预设下载失败,首次打开终端时执行 p10k configure 按向导配置即可"
  fi
fi

# ============================================================================
# 4. 生成配置文件
# ============================================================================
info "[4/6] 生成配置文件(旧文件自动备份)"

# ---------- 4.1 ~/.zshrc ----------
backup "$HOME/.zshrc"
cat > "$HOME/.zshrc" <<'ZSHRC_EOF'
# ============================================================
#  zsh 配置 ------ iTerm2 完美终端增强版
#  修改后执行 `reload`(即 source ~/.zshrc)或重开终端生效
# ============================================================

# ---------- Powerlevel10k 瞬时提示符(必须放最前,让终端秒开)----------
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi

# ---------- 自装工具路径(若你用 uv / pipx,取消下面注释)----------
# [[ -f "$HOME/.local/bin/env" ]] && . "$HOME/.local/bin/env"
export PATH="$HOME/.local/bin:$PATH"

# ---------- 历史记录 ----------
HISTFILE=~/.zsh_history
HISTSIZE=200000
SAVEHIST=200000
setopt SHARE_HISTORY          # 多个终端窗口共享历史
setopt HIST_IGNORE_ALL_DUPS   # 去掉重复命令
setopt HIST_IGNORE_SPACE      # 以空格开头的命令不记录(临时命令)
setopt HIST_REDUCE_BLANKS
setopt INC_APPEND_HISTORY     # 命令立即写入历史(防止崩溃丢失)
setopt EXTENDED_HISTORY       # 记录每条命令的执行时间

# ---------- 交互体验 ----------
setopt AUTO_CD               # 直接输入目录名就进入该目录
setopt CORRECT               # 命令拼错时给出纠正建议
setopt INTERACTIVE_COMMENTS  # 命令行里允许写 # 注释
setopt NO_BEEP               # 关掉提示音
setopt PROMPT_SUBST

# ---------- 编码(中文友好)----------
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
export EDITOR=vim

# ---------- 补全系统 ----------
autoload -Uz compinit
compinit -C                                  # -C 跳过安全检查,终端启动更快
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'   # 补全忽略大小写
zstyle ':completion:*:descriptions' format '%F{yellow}-- %d --%f'
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
zstyle ':completion:*' group-name ''

# ============================================================
#  插件
# ============================================================
# 历史自动建议(灰色提示你之前敲过的命令,右方向键采纳)
[[ -f /opt/homebrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh ]] && \
  source /opt/homebrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh

# Powerlevel10k 主题
[[ -f ~/powerlevel10k/powerlevel10k.zsh-theme ]] && source ~/powerlevel10k/powerlevel10k.zsh-theme
[[ -f ~/.p10k.zsh ]] && source ~/.p10k.zsh

# ============================================================
#  工具集成
# ============================================================
# fzf ------ Ctrl-R 模糊搜历史、Ctrl-T 找文件、Alt-C 跳目录
command -v fzf >/dev/null 2>&1 && source <(fzf --zsh)

# zoxide ------ 智能跳目录:z <关键词>,如 z proj
command -v zoxide >/dev/null 2>&1 && eval "$(zoxide init zsh)"

# direnv ------ 进入目录自动加载 .envrc / 离开自动卸载
command -v direnv >/dev/null 2>&1 && eval "$(direnv hook zsh)"

# atuin ------ 命令历史数据库,Ctrl-R 全屏搜索历史
command -v atuin >/dev/null 2>&1 && eval "$(atuin init zsh)"

# ============================================================
#  别名
# ============================================================
# ls 系列(eza:彩色 + 图标 + git 状态)
if command -v eza >/dev/null 2>&1; then
  alias ls='eza --icons --group-directories-first'
  alias ll='eza -lh --icons --group-directories-first --git'
  alias la='eza -lah --icons --group-directories-first --git'
  alias lt='eza --tree --level=2 --icons'
  alias ltt='eza --tree --level=3 --icons'
fi

# cat -> bat(语法高亮;管道中自动退化为纯文本)
command -v bat >/dev/null 2>&1 && alias cat='bat --style=plain --paging=never'

# git 快捷
alias gs='git status -sb'
alias ga='git add'
alias gc='git commit'
alias gco='git checkout'
alias gp='git pull'
alias gl='git log --oneline --graph --decorate -20'
alias gd='git diff'
alias gnb='git switch -c'

# 其他
alias lg='lazygit'
alias grep='grep --color=auto'
alias df='df -h'
alias du='du -h'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias reload='source ~/.zshrc'
alias path='echo -e ${PATH//:/\\n}'

# ============================================================
#  运维常用函数
# ============================================================

# 查端口占用:ports [端口号],不带参数列出所有监听端口
ports() {
  if [ -z "$1" ]; then
    lsof -nP -iTCP -sTCP:LISTEN
  else
    lsof -nP -iTCP:"$1" -sTCP:LISTEN
  fi
}

# 万能解压:extract <文件>
extract() {
  if [ -f "$1" ]; then
    case "$1" in
      *.tar.bz2|*.tbz2) tar xjf "$1" ;;
      *.tar.gz|*.tgz)   tar xzf "$1" ;;
      *.tar.xz|*.txz)   tar xJf "$1" ;;
      *.tar)            tar xf  "$1" ;;
      *.bz2)            bunzip2 "$1" ;;
      *.gz)             gunzip  "$1" ;;
      *.zip)            unzip   "$1" ;;
      *.rar)            unrar x "$1" ;;
      *.7z)             7z x    "$1" ;;
      *) echo "❌ 无法识别的压缩格式: $1" ;;
    esac
  else
    echo "❌ 文件不存在: $1"
  fi
}

# 建目录并进入:mkcd <目录名>
mkcd() { mkdir -p "$1" && cd "$1"; }

# 查看本机局域网 IP
myip() { ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null; }

# 进程搜索:psg <关键词>
psg() { ps aux | grep -i -- "$1" | grep -v grep; }

# 快速 HTTP 服务:serve [端口],默认 8000
serve() { python3 -m http.server "${1:-8000}"; }

# 查看当前目录下最大的 N 个目录/文件(默认 10)
bigdirs() { du -sh * 2>/dev/null | sort -rh | head -"${1:-10}"; }

# ---------- 语法高亮必须最后加载 ----------
[[ -f /opt/homebrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ]] && \
  source /opt/homebrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

# ---------- iTerm2 Shell Integration(装了才生效)----------
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"
ZSHRC_EOF
ok "已写入 ~/.zshrc"

# ---------- 4.2 ~/.tmux.conf ----------
backup "$HOME/.tmux.conf"
cat > "$HOME/.tmux.conf" <<'TMUX_EOF'
# ============================================================
#  tmux 配置 - 运维友好版
#  重载配置:前缀键(默认 Ctrl-a) + r
# ============================================================

# ---------- 基础 ----------
set -g default-terminal "screen-256color"
set -ga terminal-overrides ",xterm-256color:Tc"    # 开启真彩色
set -g base-index 1                                 # 窗口编号从 1 开始
setw -g pane-base-index 1                           # 窗格编号从 1 开始
set -g renumber-windows on                          # 关闭窗口后自动重排编号
set -g history-limit 100000                         # 回滚缓冲行数
set -sg escape-time 0                               # 消除 ESC 延迟(vim 必备)
set -g mouse on                                     # 支持鼠标点击/滚动/拖拽
set -g focus-events on                              # 焦点事件(配合 vim/tmux)
setw -g aggressive-resize on

# ---------- 前缀键:改为 Ctrl-a(与 screen 一致,更好按)----------
set -g prefix C-a
unbind C-b
bind C-a send-prefix

# ---------- 分屏:更直观的键位 ----------
bind | split-window -h -c "#{pane_current_path}"    # 前缀 + |  左右分屏
bind - split-window -v -c "#{pane_current_path}"    # 前缀 + -  上下分屏
unbind '"'
unbind %

# ---------- 窗格间移动:vim 风格 hjkl ----------
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

# ---------- 快速重载配置 ----------
bind r source-file ~/.tmux.conf \; display "tmux 配置已重载 ✔"

# ---------- 复制模式:vi 键位,复制进 macOS 剪贴板 ----------
setw -g mode-keys vi
bind -T copy-mode-vi v send-keys -X begin-selection
bind -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy"
bind -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel "pbcopy"
bind -T copy-mode-vi MouseDragEnd1Pane send-keys -X copy-pipe-and-cancel "pbcopy"

# ---------- 状态栏(One Dark 配色)----------
set -g status-interval 5
set -g status-justify left
set -g status-left-length 40
set -g status-right-length 80
set -g status-style "fg=#abb2bf,bg=#282c34"
set -g status-left "#[fg=#282c34,bg=#98c379,bold] #S #[fg=#98c379,bg=#282c34,nobold] "
set -g status-right "#[fg=#e5c07b]#{?window_zoomed_flag,[ZOOM] ,}#[fg=#98c379]%H:%M #[fg=#e06c75]%Y-%m-%d "
setw -g window-status-format " #I:#W "
setw -g window-status-current-format " #I:#W "
setw -g window-status-current-style "fg=#282c34,bg=#61afef,bold"
setw -g window-status-style "fg=#5c6370,bg=#282c34"
setw -g pane-border-style "fg=#3e4451"
setw -g pane-active-border-style "fg=#61afef"

# ---------- 新窗口/新窗格保留当前路径 ----------
bind c new-window -c "#{pane_current_path}"
TMUX_EOF
ok "已写入 ~/.tmux.conf"

# ---------- 4.3 lazygit ----------
mkdir -p "$HOME/.config/lazygit"
backup "$HOME/.config/lazygit/config.yml"
cat > "$HOME/.config/lazygit/config.yml" <<'LG_EOF'
# lazygit 配置 - 终端 Git 图形界面
# 打开:在仓库目录敲 `lg` 或 `lazygit`

gui:
  # Nerd Fonts v3(与 iTerm2 字体匹配,图标才正常)
  nerdFontsVersion: "3"
  theme:
    activeBorderColor:
      - '#61afef'
      - bold
    inactiveBorderColor:
      - '#5c6370'
    optionsTextColor:
      - '#98c379'
    selectedLineBgColor:
      - '#3e4451'
    cherryPickedCommitBgColor:
      - '#c678dd'
    cherryPickedCommitFgColor:
      - '#282c34'
    unstagedChangesColor:
      - '#e06c75'
    defaultFgColor:
      - '#abb2bf'
  border: rounded
  showFileTree: true          # 文件树视图
  showRandomTip: false        # 不显示随机提示
  showCommandLog: false       # 底部不显示命令日志
  showBottomLine: true
  commitLength:
    show: true
  mouseEvents: true           # 支持鼠标
  scrollHeight: 2

git:
  paging:
    colorArg: always
    pager: delta --dark --paging=never --line-numbers --side-by-side
  autoFetch: true
  autoRefresh: true
  parseEmoji: true
  log:
    showGraph: always         # 提交历史显示分支图

os:
  editPreset: vim             # 编辑器(按 e 编辑文件时使用)

# 自定义命令:在 lazygit 里按 x 打开自定义命令菜单,再按对应字母执行
customCommands:
  - key: 'f'
    command: 'git fetch --all --prune'
    context: 'global'
    description: '拉取所有远程分支并清理'
LG_EOF
ok "已写入 ~/.config/lazygit/config.yml"

# ---------- 4.4 iTerm2 主题(Dynamic Profile)----------
ITERM_DIR="$HOME/Library/Application Support/iTerm2/DynamicProfiles"
mkdir -p "$ITERM_DIR"
backup "$ITERM_DIR/onedark.json"
cat > "$ITERM_DIR/onedark.json" <<'ITERM_EOF'
{
  "Profiles": [
    {
      "Name": "OneDark",
      "Guid": "E4B1A2C3-0001-4A2B-9C3D-000000000001",
      "Dynamic Profile Parent Name": "Default",
      "Default Bookmark": "Yes",

      "Normal Font": "MesloLGS-NF-Regular 14",
      "Non Ascii Font": "MesloLGS-NF-Regular 14",
      "Use Non-ASCII Font": false,
      "Use Italic Font": true,
      "ASCII Anti Aliased": true,
      "Non-ASCII Anti Aliased": true,
      "Draw Powerline Glyphs": true,

      "Terminal Type": "xterm-256color",
      "Unlimited Scrollback": true,
      "Scrollback Lines": 10000,
      "Send Code When Idle": false,
      "Silence Bell": true,
      "Visual Bell": false,
      "Flashing Bell": false,
      "Blinking Cursor": false,
      "Blinking Text": false,
      "Cursor Type": 1,
      "Use Bright Bold": true,
      "Ambiguous Double Width": false,

      "Left Option Key Sends": 2,
      "Right Option Key Sends": 2,
      "Mouse Reporting": true,
      "Focus Reporting": true,
      "Allow Title Setting": true,

      "Working Directory": "Reuse previous session's directory",
      "Prompt Before Closing 2": 1,
      "Status Bar Enabled": true,
      "Custom Command": "No",

      "Foreground Color": { "Red Component": 0.670588, "Green Component": 0.698039, "Blue Component": 0.749020, "Alpha Component": 1, "Color Space": "sRGB" },
      "Background Color": { "Red Component": 0.156863, "Green Component": 0.172549, "Blue Component": 0.203922, "Alpha Component": 1, "Color Space": "sRGB" },
      "Bold Color": { "Red Component": 0.901961, "Green Component": 0.929412, "Blue Component": 0.980392, "Alpha Component": 1, "Color Space": "sRGB" },
      "Cursor Color": { "Red Component": 0.321569, "Green Component": 0.545098, "Blue Component": 1.000000, "Alpha Component": 1, "Color Space": "sRGB" },
      "Cursor Text Color": { "Red Component": 0.156863, "Green Component": 0.172549, "Blue Component": 0.203922, "Alpha Component": 1, "Color Space": "sRGB" },
      "Cursor Guide Color": { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 0.250000, "Color Space": "sRGB" },
      "Selection Color": { "Red Component": 0.243137, "Green Component": 0.266667, "Blue Component": 0.317647, "Alpha Component": 1, "Color Space": "sRGB" },
      "Selected Text Color": { "Red Component": 0.901961, "Green Component": 0.929412, "Blue Component": 0.980392, "Alpha Component": 1, "Color Space": "sRGB" },
      "Link Color": { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 1, "Color Space": "sRGB" },
      "Badge Color": { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 0.600000, "Color Space": "sRGB" },
      "Underline Color": { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 1, "Color Space": "sRGB" },
      "Match Background Color": { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 1, "Color Space": "sRGB" },
      "Match Text Color": { "Red Component": 0.156863, "Green Component": 0.172549, "Blue Component": 0.203922, "Alpha Component": 1, "Color Space": "sRGB" },

      "Ansi 0 Color":  { "Red Component": 0.156863, "Green Component": 0.172549, "Blue Component": 0.203922, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 1 Color":  { "Red Component": 0.878431, "Green Component": 0.423529, "Blue Component": 0.458824, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 2 Color":  { "Red Component": 0.596078, "Green Component": 0.764706, "Blue Component": 0.474510, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 3 Color":  { "Red Component": 0.898039, "Green Component": 0.752941, "Blue Component": 0.482353, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 4 Color":  { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 5 Color":  { "Red Component": 0.776471, "Green Component": 0.470588, "Blue Component": 0.866667, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 6 Color":  { "Red Component": 0.337255, "Green Component": 0.713725, "Blue Component": 0.760784, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 7 Color":  { "Red Component": 0.670588, "Green Component": 0.698039, "Blue Component": 0.749020, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 8 Color":  { "Red Component": 0.360784, "Green Component": 0.388235, "Blue Component": 0.439216, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 9 Color":  { "Red Component": 0.878431, "Green Component": 0.423529, "Blue Component": 0.458824, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 10 Color": { "Red Component": 0.596078, "Green Component": 0.764706, "Blue Component": 0.474510, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 11 Color": { "Red Component": 0.898039, "Green Component": 0.752941, "Blue Component": 0.482353, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 12 Color": { "Red Component": 0.380392, "Green Component": 0.686275, "Blue Component": 0.937255, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 13 Color": { "Red Component": 0.776471, "Green Component": 0.470588, "Blue Component": 0.866667, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 14 Color": { "Red Component": 0.337255, "Green Component": 0.713725, "Blue Component": 0.760784, "Alpha Component": 1, "Color Space": "sRGB" },
      "Ansi 15 Color": { "Red Component": 1.000000, "Green Component": 1.000000, "Blue Component": 1.000000, "Alpha Component": 1, "Color Space": "sRGB" }
    }
  ]
}
ITERM_EOF
ok "已写入 iTerm2 主题(OneDark)"

# ============================================================================
# 5. git 使用 delta 美化 diff
# ============================================================================
info "[5/6] 配置 git 的 diff 显示"
if command -v delta >/dev/null 2>&1; then
  git config --global core.pager "delta"
  git config --global interactive.diffFilter "delta --color-only"
  git config --global delta.navigate true
  git config --global delta.line-numbers true
  git config --global delta.side-by-side false
  git config --global delta.syntax-theme "OneHalfDark"
  git config --global merge.conflictStyle "zdiff3"
  ok "git 已配置 delta(git diff 会变成彩色带行号的漂亮输出)"
else
  warn "未找到 delta,跳过 git 配置"
fi

# ============================================================================
# 6. 校验
# ============================================================================
info "[6/6] 安装结果校验"
missing=0
for t in fzf zoxide bat eza fd rg tmux atuin lazygit delta direnv; do
  if command -v "$t" >/dev/null 2>&1; then
    ok "$t"
  else
    err "$t 未安装"
    missing=$((missing+1))
  fi
done

echo
if [ "$missing" -eq 0 ]; then
  title "✅ 全部完成!"
else
  title "⚠️ 完成,但有 $missing 个工具未装上"
  echo "   常见原因:网络波动。再次运行 bash setup.sh 即可续装(已装的会跳过)。"
fi

cat <<'NEXT'

  👉 接下来做 2 件事:

  1) 完全退出 iTerm2(⌘Q)再重新打开,然后执行一次:
       source ~/.zshrc

  2) 在 iTerm2 里点几下(⌘, 打开设置):
     · Profiles → 选中 OneDark → 左下 Other Actions... → Set as Default
     · 顶部菜单 iTerm2 → Install Shell Integration(强烈建议)
     · General → Selection 勾「Copy to pasteboard on selection」
     · General → Pointer 勾「Focus follows mouse」

  遇到图标显示成方块:⌘, → Profiles → Text → Font 选 MesloLGS NF 即可。

NEXT
相关推荐
棉猴1 小时前
玩游戏学Python5-函数
开发语言·python·函数·玩游戏·游戏编程
Rain的Java大神之路1 小时前
[特殊字符]8年Java老兵转型AI Agent:90%的人挂在同一个坑,根本不用学Python!(万字实战复盘,建议收藏)
java·数据库·人工智能·后端·python·spring·ai编程
高级程序源1 小时前
springboot本地生活服务平台33399-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·小程序·flask·课程设计
高级程序源1 小时前
springboot社区旧物回收管理系统25381-计算机课程设计、毕业设计
vue.js·spring boot·python·django·课程设计
高级程序源1 小时前
springboot大学生体测系统72170-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·django·课程设计
祖力551 小时前
Linux系统移植、烧录与环境的搭建
linux·运维·服务器
谢亮_vipxieliang1 小时前
JavaScript this 指向完全指南:调用位置决定一切
开发语言·javascript·ecmascript
打工仔折腾 AI1 小时前
极空间用 Docker 部署 Photopea:网页版 PS 的私有化实践
运维·后端·python·docker·容器·langchain·ai agent 实战
Eiceblue1 小时前
使用 Python 实现 Excel 行列转置(保留单元格样式)
前端·python·excel