Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Zsh 實戰技巧 10 連發:通配符、補全、糾錯、歷史替換與右側提示符

編輯:關於 Linux

Zsh 的設計哲學是「讓常用操作極簡,複雜操作可控」。本文精選 10 個高頻實戰場景,展示 Zsh 獨有的擴展通配符、上下文感知補全、智能糾錯、歷史修改重跑、右側提示符等殺手級功能,助你從 Bash 使用者進階為 Zsh 高手。

1. ** 遞歸通配符 —— 橫掃子目錄

# 列出所有 .pyc 檔 (含子目錄)
ls **/*.pyc
# foo.pyc bar.pyc lib/wibble.pyc

# 遞歸刪除
rm **/*.pyc

# 驗證
ls **/*.pyc
# (無輸出)

原理:** 等同 **/*,遞歸匹配任意深度目錄,無需 find 或 globstar 選項。

2. 文件過濾模式 —— 正則風格擴展

# 同時匹配 .py 和 .sh
ls *.py|sh    # Zsh 原生支援 | 分隔
# 或
ls *. (py|sh)  # 括號分組 (需 setopt EXTENDED_GLOB)

3. 修飾符 精準過濾檔案類型

# 僅符號連結
ls -l *(@)

# 僅目錄
ls -ld *(/)

# 僅可執行檔
ls -l *(*)

# 僅大於 10MB 的一般檔案
ls -lh *(.L+10m)

# 組合:最近 1 小時修改的 .c 檔
ls -l *.c(mh-1)

修飾符速查:(@) 符號連結、(/) 目錄、(*) 可執行、(.) 一般檔、(r/w/x) 權限、(Lk/m/g) 大小、(mh/d/w) 時間。

4. Tab 補全 Man Page 章節

man zsh
# 顯示菜單:zsh(1) zshall(1) zshbuiltins(1) zshcalsys(1) ...
# 選擇章節後直接開啟

5. Tab 補全命令選項 (自動解析 --help/man)

python -
# 顯示:-B -b -c -d -E -h -i -m -O -Q -s -S -u -v -V -W -x -X --help --version ...
# 選項描述同步顯示

6. Tab 補全 Kill 進程 (名稱 + PID 雙模式)

kill Dock
# 顯示:Dock(1234)  Dock(5678)  等同 kill 1234 5678

7. 補全菜單鍵盤導航 (類 IDE 體驗)

man zsh
# 方向鍵在補全菜單中自由移動選擇,Enter 確認

8. 自動糾錯命令拼寫

pythn -V
# zsh: correct 'pythn' to 'python' [nyae]? y
# Python 2.7.1
# 選項:n(no) y(yes) a(abort) e(edit)

需 setopt correctall (已在配置指南中啟用)。

9. r 歷史修改重跑 —— 批量重命名神器

touch foo.htm bar.htm
mv foo.htm foo.html
r foo=bar
# 自動展開為:mv bar.htm bar.html
# 執行後 bar.htm → bar.html

原理:r 重跑上一條歷史命令,支援 舊=新 字串替換,多重替換用空格分隔 r foo=bar htm=html。

10. 右側提示符 (RPROMPT) —— 邊角資訊不佔主提示符空間

# 顯示當前時間 (HH:MM:SS)
RPROMPT="%*"

# 顯示 Git 狀態 (需 vcs_info)
autoload -Uz vcs_info
precmd() { vcs_info }
setopt prompt_subst
RPROMPT='${vcs_info_msg_0_}'

# 顯示返回碼 (非零時紅色)
RPROMPT='%(?.%F{green}✓.%F{red}✗ %?)%f'

# 組合:時間 + Git + 返回碼
RPROMPT='%* ${vcs_info_msg_0_} %(?.%F{green}✓.%F{red}✗ %?)%f'

Zsh 實戰技巧示意圖

安裝建議

# Debian/Ubuntu
apt-get install zsh

# Fedora/CentOS
dnf install zsh

# macOS (Homebrew)
brew install zsh

這 10 個技巧僅是 Zsh 功能冰山一角,配合 zsh-autosuggestions (灰色建議)、zsh-syntax-highlighting (語法高亮)、fzf (模糊歷史/檔案搜尋) 等外掛,可構建極致高效的終端工作流。建議逐一實操,內化為肌肉記憶。

Copyright © Windows教程網 All Rights Reserved