[← 返回首页]

Zsh 与 Oh My Zsh 安装配置指南

#document
参考来源:[zsh 安装与配置 Leehow的小站](https://www.haoyep.com/posts/zsh-config-oh-my-zsh/)

OS -> Ubuntu

1. 环境准备

更新软件源并安装必要依赖:

sudo apt update && sudo apt upgrade -y
sudo apt install zsh git curl -y

设置 Zsh 为默认 Shell(无需 sudo,注销或重启生效):

chsh -s /bin/zsh

2. 安装 Oh My Zsh

安装过程中如提示覆盖 .zshrc,请选择同意。

官方源

工具 安装命令
curl sh -c "$(curl -fsSL https://install.ohmyz.sh/)"
wget sh -c "$(wget -O- https://install.ohmyz.sh/)"

3. 配置迁移 Bash → Zsh

若之前在 bash 中有自定义环境变量或别名,需手动迁移:

# 1. 查看旧配置
cat ~/.bashrc
# 2. 编辑新配置
nano ~/.zshrc
# 3. 加载配置
source ~/.zshrc

4. 主题配置

haoomz 主题为例 (也可使用内置主题如 ys, robbyrussell)。

下载第三方主题:

sudo wget -O $ZSH_CUSTOM/themes/haoomz.zsh-theme https://cdn.haoyep.com/gh/leegical/Blog_img/zsh/haoomz.zsh-theme

启用主题: 编辑 ~/.zshrc,修改 ZSH_THEME 字段:

ZSH_THEME="haoomz"
# ZSH_THEME="robbyrussell" # 备选内置主题

5. 插件配置

插件分为内置插件(可直接启用)和第三方插件(需下载)。

第三方插件下载

  1. zsh-autosuggestions(自动补全建议)

    git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
    
  2. zsh-syntax-highlighting(语法高亮校验)

    git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
    

推荐内置插件

  • git: 显示 Git 仓库状态(默认开启)。
  • z: 快速跳转常用目录(智能记忆)。
  • extract: 万能解压命令,使用 x filename 即可。
  • web-search: 命令行搜索,如 google 搜索内容

启用插件

编辑 ~/.zshrc,找到 plugins=(...) 并修改:

plugins=(
  git
  zsh-autosuggestions
  zsh-syntax-highlighting
  z
  extract
  web-search
)

保存后执行 source ~/.zshrc 重新加载。

6. 高级配置

Root 用户配置

root 用户的 Shell 配置与普通用户独立。建议:

  1. 切换到 root (sudo su) 并重新安装 Oh My Zsh。
  2. 使用不同的主题以区分身份。
  3. 插件配置可与普通用户保持一致。

快捷代理设置

~/.zshrc 中添加函数,实现一条命令开关代理(根据实际端口修改):

# 开启代理
proxy () {
  export HTTP_PROXY="http://127.0.0.1:7890"
  export HTTPS_PROXY="https://127.0.0.1:7890"
}

7. 维护命令

  • 手动更新 Oh My Zsh

    upgrade_oh_my_zsh
    
  • 卸载 Oh My Zsh

    uninstall_oh_my_zsh