Shell Environment Setup
Chapter 1: Shell Environment Setup
Before diving into Linux Shell mastery, building a comfortable development environment is essential. Choosing the right shell, configuring a terminal multiplexer, and mastering editor basics can multiply your productivity. This chapter builds your professional Shell workspace from scratch.
1.1 Shell Comparison: bash vs zsh vs fish
The three mainstream interactive shells on Linux are bash (Bourne Again Shell), zsh (Z Shell), and fish (Friendly Interactive Shell). Each has its strengths — the table below compares them across key dimensions:
| Feature | bash | zsh | fish |
|---|---|---|---|
| Default System Shell | Most Linux distros | macOS 10.15+ | None (manual install) |
| Script Compatibility | POSIX fully compatible | Compatible with bash (mostly) | Non-POSIX, own syntax |
| Auto-completion | Basic (bash-completion ext) | Powerful, context-aware | Out-of-box, most intelligent |
| Prompt Customization | PS1 variable | PROMPT / oh-my-zsh / starship | Built-in config tool |
| Plugin Ecosystem | Limited (bash-it) | Rich (oh-my-zsh, zinit) | fisher / oh-my-fish |
| History | ~/.bash_history | Shared history, more powerful | Per-directory history |
| Learning Curve | Gentle, abundant docs | Moderate, slightly complex config | Lowest, beginner-friendly |
| Best For | Scripting, server admin | Daily dev, heavy customization | Interactive use, beginners |
Recommendation: Use zsh (with oh-my-zsh) for daily interactive work, and always use bash (#!/bin/bash) for scripts to ensure portability. Fish is great for new interactive users, but its non-POSIX scripts make it unsuitable for servers.
1.2 Installing and Switching Shells
Use cat /etc/shells to list all valid shells installed on the system, and echo $SHELL to check your current shell.
# 查看系统可用的 Shell 列表
cat /etc/shells
# 输出示例:
# /bin/sh
# /bin/bash
# /usr/bin/zsh
# /usr/bin/fish
# 查看当前 Shell
echo $SHELL
# /bin/bash
# 查看当前 Shell 版本
bash --version
zsh --version
# 安装 zsh(Ubuntu/Debian)
sudo apt install -y zsh
# 安装 fish
sudo apt install -y fish
# 切换默认 Shell 为 zsh(永久生效,需要重新登录)
chsh -s $(which zsh)
# 切换当前会话的 Shell(临时)
exec zsh
# 验证切换结果
echo $SHELL
Note:
chshchanges the login shell — you must log out and back in for it to take effect. On some systems (like Ubuntu),chshrequires your current password. Ensure the new shell's path exists in/etc/shells, otherwisechshwill refuse the change.
1.3 bash Config: .bashrc vs .bash_profile
bash loads different config files in different scenarios — understanding the difference is key to avoiding "why isn't my config working" headaches:
- ~/.bash_profile — Read by login shells (SSH login, console login). Set PATH and environment variables here
- ~/.bashrc — Read by non-login interactive shells (opening new terminal windows). Aliases, functions, and prompt settings go here
- ~/.bash_logout — Executed when a login shell exits
- /etc/profile — System-wide login shell config, applies to all users
# ~/.bash_profile 推荐内容:让登录 Shell 也读取 .bashrc
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
# 设置 PATH(追加自定义路径)
export PATH="$HOME/.local/bin:$HOME/bin:$PATH"
# ~/.bashrc 推荐结构:
# 1. 环境变量
export EDITOR=vim
export LANG=en_US.UTF-8
# 2. 别名
alias ll='ls -alF --color=auto'
alias la='ls -A'
alias grep='grep --color=auto'
alias ..='cd ..'
alias ...='cd ../..'
# 3. 自定义 PS1 提示符
# \u = 用户名, \h = 主机名, \w = 当前目录
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
# 4. 历史记录设置
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTCONTROL=ignoredups:erasedups # 忽略重复命令
shopt -s histappend # 追加而非覆盖历史文件
# 5. 加载 bash-completion(如果安装)
if [ -f /usr/share/bash-completion/bash_completion ]; then
source /usr/share/bash-completion/bash_completion
fi
# 修改后立即生效(无需重启终端)
source ~/.bashrc
1.4 zsh + oh-my-zsh / starship
Installing oh-my-zsh
# 安装 oh-my-zsh(官方安装脚本)
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
# 安装后编辑 ~/.zshrc
# 修改主题
ZSH_THEME="agnoster" # 常用:robbyrussell, agnoster, powerlevel10k
# 安装 zsh-autosuggestions 插件(命令历史自动补全)
git clone https://github.com/zsh-users/zsh-autosuggestions \
${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
# 安装 zsh-syntax-highlighting 插件(命令语法高亮)
git clone https://github.com/zsh-users/zsh-syntax-highlighting \
${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
# 在 ~/.zshrc 中启用插件(注意:多个插件用空格分隔)
plugins=(
git
docker
kubectl
zsh-autosuggestions
zsh-syntax-highlighting
z # 目录跳转(autojump 替代)
extract # 智能解压(x file.tar.gz)
colored-man-pages
)
# 使配置生效
source ~/.zshrc
Using starship for Cross-Shell Prompt
starship is a blazing-fast cross-shell prompt written in Rust. It supports bash/zsh/fish and shows Git status, language versions, Docker context, and more with zero extra config.
# 安装 starship
curl -sS https://starship.rs/install.sh | sh
# 在 ~/.bashrc 末尾添加(bash)
eval "$(starship init bash)"
# 在 ~/.zshrc 末尾添加(zsh)
eval "$(starship init zsh)"
# 在 ~/.config/fish/config.fish 添加(fish)
starship init fish | source
# starship 配置文件位置
mkdir -p ~/.config
# 编辑 ~/.config/starship.toml
# 示例配置
cat >> ~/.config/starship.toml
## 1.5 tmux Terminal Multiplexer — Complete Guide
**tmux** (Terminal Multiplexer) lets you run multiple sessions and panes in a single terminal window. Programs keep running after SSH disconnects. Mastering tmux is essential for server operations and remote development.
### Installation and Core Concepts
```bash
# 安装 tmux
sudo apt install -y tmux # Ubuntu/Debian
sudo dnf install -y tmux # Fedora/RHEL
sudo pacman -S tmux # Arch Linux
# tmux 三层结构:
# Session(会话) > Window(窗口) > Pane(窗格)
# 启动一个新会话
tmux
# 启动并命名会话
tmux new-session -s myproject
# 简写
tmux new -s myproject
Prefix Key and Common Shortcuts
All tmux shortcuts begin with the Prefix Key, which defaults to Ctrl+b. Press Prefix first, then the function key.
# === 会话管理 ===
tmux new -s work # 新建名为 work 的会话
tmux ls # 列出所有会话
tmux attach -t work # 重新连接 work 会话(简写:tmux a -t work)
tmux kill-session -t work # 删除会话
# Prefix + d → 暂时离开(detach)当前会话,程序继续运行
# Prefix + $ → 重命名当前会话
# Prefix + s → 交互式切换会话列表
# === 窗口管理 ===
# Prefix + c → 新建窗口
# Prefix + , → 重命名当前窗口
# Prefix + n → 切换到下一个窗口
# Prefix + p → 切换到上一个窗口
# Prefix + 0~9 → 切换到指定编号窗口
# Prefix + w → 窗口列表(交互式)
# Prefix + & → 关闭当前窗口
# === 窗格管理(分屏)===
# Prefix + % → 垂直分割(左右两个窗格)
# Prefix + " → 水平分割(上下两个窗格)
# Prefix + 方向键 → 切换窗格
# Prefix + z → 最大化/还原当前窗格
# Prefix + x → 关闭当前窗格
# Prefix + { → 向左移动窗格
# Prefix + } → 向右移动窗格
# Prefix + Alt+方向键 → 调整窗格大小
# === 复制模式(滚动历史)===
# Prefix + [ → 进入复制模式,可用方向键/Page Up/Down 滚动
# q → 退出复制模式
Recommended ~/.tmux.conf
# ~/.tmux.conf — 推荐配置
# 修改 Prefix 为 Ctrl+a(更顺手)
unbind C-b
set-option -g prefix C-a
bind-key C-a send-prefix
# 鼠标支持(点击切换窗格,滚轮滚动)
set -g mouse on
# 窗格分割快捷键(更直觉)
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
unbind '"'
unbind %
# 新建窗口时保持当前目录
bind c new-window -c "#{pane_current_path}"
# vim 风格窗格切换
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
# 256 色支持
set -g default-terminal "screen-256color"
set -ag terminal-overrides ",xterm-256color:RGB"
# 状态栏样式
set -g status-bg colour235
set -g status-fg colour136
set -g status-left "#[fg=green]#S "
set -g status-right "#[fg=yellow]%Y-%m-%d %H:%M"
set -g status-right-length 50
# 窗口编号从 1 开始(而非 0)
set -g base-index 1
setw -g pane-base-index 1
# 历史记录行数
set -g history-limit 50000
# 重新加载配置(无需退出 tmux)
bind r source-file ~/.tmux.conf \; display-message "Config reloaded!"
Pro Tip: After connecting to a server, always run
tmux attach || tmux new -s main: attaches to an existing session if present, or creates one named "main". Add this asRemoteCommandin your local~/.ssh/configto auto-enter tmux on SSH login.
1.6 vim / nano Editor Basics
Servers typically lack a GUI, making vim a required skill for Linux administrators. vim uses modal editing — beginners must first understand how mode switching works.
vim's Three Core Modes
# vim 模式切换
# 普通模式(Normal) → 插入模式(Insert):按 i / a / o
# 插入模式 → 普通模式:按 Esc
# 普通模式 → 命令行模式(Command):按 :
# === 普通模式:移动 ===
# h j k l → 左下上右
# w / b → 下一个单词 / 上一个单词
# 0 / $ → 行首 / 行尾
# gg / G → 文件首行 / 末行
# Ctrl+f/b → 向下/上翻页
# :42 → 跳到第 42 行
# === 普通模式:编辑 ===
# dd → 删除(剪切)当前行
# yy → 复制当前行
# p / P → 粘贴到光标后/前
# u → 撤销
# Ctrl+r → 重做
# x → 删除光标处字符
# r → 替换光标处字符
# === 普通模式:搜索 ===
# /pattern → 向下搜索(n 下一个,N 上一个)
# ?pattern → 向上搜索
# :%s/old/new/g → 全文替换
# === 命令行模式:保存退出 ===
# :w → 保存
# :q → 退出(未修改时)
# :wq 或 :x → 保存并退出
# :q! → 强制退出(放弃修改)
Minimal vimrc Configuration
# ~/.vimrc — 最小化但实用的配置
cat > ~/.vimrc :w
inoremap :wa
EOF
echo "vimrc created!"
nano Quick Start: If vim is too daunting initially, nano is more approachable.
nano filenameopens a file with shortcuts shown at the bottom (^means Ctrl).Ctrl+Xto exit,Ctrl+Oto save,Ctrl+Wto search.
1.7 Package Managers: apt / dnf / pacman
Different Linux distributions use different package managers. Here are the common operations for the three major ones side by side:
# === apt(Ubuntu / Debian / Kali)===
sudo apt update # 更新软件包索引
sudo apt upgrade # 升级所有已安装包
sudo apt install -y vim git curl # 安装软件包
sudo apt remove vim # 卸载(保留配置)
sudo apt purge vim # 彻底卸载(删配置)
sudo apt autoremove # 清理孤立依赖
apt search "text editor" # 搜索包
apt show vim # 显示包详情
dpkg -l | grep vim # 列出已安装包(过滤)
# === dnf(Fedora / RHEL / CentOS 8+)===
sudo dnf check-update # 检查更新
sudo dnf upgrade # 升级所有包
sudo dnf install -y vim git curl # 安装软件包
sudo dnf remove vim # 卸载
sudo dnf autoremove # 清理孤立依赖
dnf search vim # 搜索包
dnf info vim # 显示包详情
dnf list installed | grep vim # 列出已安装包
# === pacman(Arch Linux / Manjaro)===
sudo pacman -Sy # 同步包数据库
sudo pacman -Syu # 完整系统升级
sudo pacman -S vim git curl # 安装软件包
sudo pacman -R vim # 卸载(保留依赖)
sudo pacman -Rs vim # 卸载(同时移除不需要的依赖)
pacman -Ss vim # 搜索包
pacman -Si vim # 显示包详情
pacman -Q | grep vim # 列出已安装包
# === 通用工具(所有发行版)===
# snap(Canonical 出品,沙盒应用)
sudo snap install code --classic # 安装 VS Code
# flatpak(跨发行版桌面应用)
flatpak install flathub org.gimp.GIMP
1.8 dotfiles Management: Version Control Best Practices
dotfiles are configuration files beginning with . (like ~/.bashrc, ~/.tmux.conf). Putting them under Git version control lets you restore your complete environment on a new machine in minutes.
Method 1: Git Bare Repository (Recommended)
# 初始化裸仓库,存放在 ~/.dotfiles
git init --bare $HOME/.dotfiles
# 创建别名(加入 ~/.bashrc 或 ~/.zshrc)
alias dotfiles='git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME'
# 不追踪未被明确添加的文件(防止 HOME 目录被污染)
dotfiles config --local status.showUntrackedFiles no
# 远程仓库(GitHub)
dotfiles remote add origin [email protected]:yourname/dotfiles.git
# 添加并提交配置文件
dotfiles add ~/.bashrc ~/.zshrc ~/.tmux.conf ~/.vimrc
dotfiles commit -m "Initial dotfiles setup"
dotfiles push -u origin main
# === 在新机器上恢复 ===
# 1. 克隆裸仓库
git clone --bare [email protected]:yourname/dotfiles.git $HOME/.dotfiles
# 2. 添加别名
alias dotfiles='git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME'
# 3. 检出文件到 HOME 目录
dotfiles checkout
Method 2: GNU stow (Symlink Manager)
# 安装 GNU stow
sudo apt install -y stow
# 目录结构示例:~/dotfiles/
# dotfiles/
# ├── bash/
# │ └── .bashrc
# ├── vim/
# │ └── .vimrc
# └── tmux/
# └── .tmux.conf
mkdir -p ~/dotfiles/bash ~/dotfiles/vim ~/dotfiles/tmux
mv ~/.bashrc ~/dotfiles/bash/
mv ~/.vimrc ~/dotfiles/vim/
mv ~/.tmux.conf ~/dotfiles/tmux/
# 使用 stow 创建符号链接(从 ~/dotfiles 目录运行)
cd ~/dotfiles
stow bash # 创建 ~/.bashrc -> ~/dotfiles/bash/.bashrc
stow vim # 创建 ~/.vimrc -> ~/dotfiles/vim/.vimrc
stow tmux # 创建 ~/.tmux.conf -> ~/dotfiles/tmux/.tmux.conf
# 将 ~/dotfiles 纳入 Git 管理
cd ~/dotfiles
git init
git remote add origin [email protected]:yourname/dotfiles.git
git add .
git commit -m "Add dotfiles via stow"
git push -u origin main
1.9 Getting Help: man / help / tldr
Linux comes with a comprehensive documentation system. Learning to look things up is more important than memorizing commands.
# === man(Manual Pages)===
man ls # 查看 ls 命令的完整手册
man 5 passwd # 查看 Section 5(文件格式)的 passwd
man -k "copy file" # 关键词搜索手册页(等同 apropos)
# man 手册中的快捷键:
# /pattern → 搜索,n/N 下一个/上一个
# q → 退出
# === --help(快速参考)===
ls --help # 内置帮助,比 man 更简洁
git commit --help # 大多数程序都支持
# === type / which(找命令位置)===
type ls # 判断是别名、内置命令还是外部程序
which python3 # 显示外部命令的路径
whereis bash # 显示二进制、源码和 man 文件的位置
# === tldr(Too Long; Didn't Read)===
# 安装 tldr(社区维护的简洁示例集合)
sudo npm install -g tldr
# 或
pip install tldr
tldr tar # 显示 tar 的常用示例(比 man 更直觉)
tldr find # find 的常用用法
tldr ssh # ssh 的常用示例
# === info(GNU 文档系统)===
info coreutils # GNU 核心工具的详细文档
info bash # Bash 完整参考手册
Chapter Summary: You now have the complete knowledge framework for a professional Shell environment: zsh + oh-my-zsh for powerful interactive experience, tmux so your sessions never get lost, vim for efficient editing on any server, and dotfiles management for reproducible environments. The next chapter dives into Linux filesystem internals.
Previous
← Introduction
Next
Ch2: Filesystem →