Bash 提供強大的歷史擴展功能,讓你無需重複輸入即可複用、修改歷史命令。掌握這些技巧能大幅提升終端操作效率。
| 語法 | 說明 | 範例 |
|---|---|---|
!! | 重複執行上一條命令 | !! → 執行上條 apt update |
!n | 執行第 n 條歷史命令 | !1024 |
!-n | 執行倒數第 n 條命令 | !-2 → 倒數第二條 |
!string | 執行最近以 string 開頭的命令 | !git → 最近的 git 命令 |
!?string? | 執行最近包含 string 的命令 | !?config? |
^old^new | 將上條命令中首個 old 替換為 new | ^cat^vim → cat→vim |
!!:gs/old/new | 全局替換上條命令所有 old 為 new | !!:gs/test/prod |
格式:!事件指示符:詞指示符(事件指示符省略時預設為上一條)
| 語法 | 含義 | 範例場景 |
|---|---|---|
!:0 | 命令名(第 0 個詞) | 只想重用命令不帶參數 |
!^ | 第一個參數 | cp !^ /backup/ 複製上條第一個參數 |
!$: 或 !* | 最後一個參數 / 所有參數 | vim !$ 編輯上條最後參數 |
!:n | 第 n 個參數 | scp !:2 server:/dest |
!:m-n | 第 m 到 n 個參數 | tar -czf !:1-3 |
!:* | 所有參數(同 !*) | 重用所有參數 |
# 1. 修正上條命令拼寫錯誤
$ git comit -m "fix"
$ ^comit^commit # → git commit -m "fix"
# 2. 針對同一文件連續操作
$ vim /etc/nginx/nginx.conf
$ cp !$ !$ .bak # → cp nginx.conf nginx.conf.bak
$ nginx -t -c !$ # → nginx -t -c nginx.conf
# 3. 重用複雜參數組合
$ rsync -avz --exclude='*.log' --exclude='node_modules' src/ dest/
$ !!:2* # 重用除命令名外所有參數
# 4. 批量處理同一組文件
$ ls *.jpg
$ convert !*:1-3 -resize 50% thumb/
$ tar -czf images.tar.gz !*
# 5. 快速切換目錄並操作
$ cd /var/log/nginx
$ tail -f !$
$ grep error !$
$ ls -lh !^
# ~/.bashrc 中設定
export HISTSIZE=10000 # 記憶體中保留條數
export HISTFILESIZE=20000 # 文件中保留條數
export HISTCONTROL=ignoredups:erasedups # 去重
export HISTTIMEFORMAT="%F %T " # 顯示時間戳
export HISTIGNORE="ls:cd:pwd:clear:history" # 忽略常用無關命令
# ~/.bashrc
shopt -s histappend
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
history # 顯示全部歷史
history 20 # 顯示最近 20 條
history -c # 清空當前會話歷史
history -w # 強制寫入歷史文件
history -d 1024 # 刪除指定行號
grep ssh ~/.bash_history # 搜索歷史
!$ 引用上條最後參數,配合 vim、cat、cp 等高頻命令history -w 持久化,避免異常退出丟失!! 確認上條命令無誤再執行fc 命令編輯執行複雜歷史命令