善用Bash history 命令
- 2020 年 9 月 2 日
- 筆記
大家好,我是良許
相信大家平時都有用 history
命令來查看命令歷史記錄,但是實際上 history
命令並非只有這個功能,history
還有很多有用的功能。尤其是 Bash 版本的 history
命令,它所提供的功能比所有其他的 Linux Shell history
命令所提供的都要多。
Bash 的歷史悠久,是一個古老的 Shell ,並且它還有一個更古老的前身 the Bourne Shell (sh) 。因此,Bash 的 history
命令是所有的 Linux Shell history
命令中功能最豐富的。Bash 版本的 history
命令不僅支援反向搜索、快速調用,還支援重寫歷史記錄等等功能。
善用 Bash history
命令以上的這些功能都可以提高你的工作效率,因此,讓良許為你一一講解 Bash history
命令以及它常用的功能:
history 是內置的命令
history
命令與許多其他的命令不同。你可能習慣於命令都作為可執行文件放置在常見的系統級的位置,例如 /usr/bin
,/usr/local/bin
或 〜/ bin
。但是,內置的 history
命令並不在你的環境變數 PATH
保存的路徑中的。
實際上,history
命令並沒有保存在物理位置中:
$ which history
which: no history in [PATH]
history
其實是 Shell 本身的一個內置函數:
$ type history
history is a shell builtin
$ help history
history: history [-c] [-d offset] [n] or
history -anrw [filename] or
history -ps arg [arg...]
Display or manipulate the history list.
[...]
由於 history
是 Shell 的內置函數,所以每種 Shell 的 history
函數都是獨一無二的。因此,你在 Bash 中能使用的功能可能無法在 Tcsh,Fish 或 Dash 中使用,同樣的,在 Tcsh,Fish 或 Dash 中能使用的功能也可能無法在 Bash 中使用。
查看你的 Bash 命令歷史記錄
history
命令最基本,最頻繁的用法就是查看你的 Shell 會話的命令歷史記錄:
$ echo "hello"
hello
$ echo "world"
world
$ history
1 echo "hello"
2 echo "world"
3 history
事件提示符
事件提示符 (!) 是按事件搜索歷史記錄的。這裡的事件,指的是每一條記錄在歷史記錄里的命令。換句話說,它就是一行命令,並被數字索引標記著以供引用。
要重新運行歷史記錄中的一個命令,用 ! 直接加上 (無空格) 你想要運行的命令前面的索引數字即可。例如,假設歷史記錄中的第一條指令是 echo hello
,然後你想重新運行它:
$ !1
echo "hello"
hello
你還可以通過從歷史記錄中的當前位置開始提供負數的行來使用相對定位。例如,返回歷史記錄中倒數第3條命令:
$ echo "alvin"
alvin
$ echo "hello"
hello
$ echo "world"
world
$ !-3
echo "alvin"
alvin
如果你只想返回上一條命令,你可以使用簡寫 !! 來替代 !-1。這整整節省了一次按鍵的時間!!!
$ echo "alvin"
alvin
$ !!
echo "alvin"
alvin
字元串搜索
你也可以通過特定的字元串來搜索歷史記錄中的命令並運行它。
若是想要搜索以特定字元串開頭的命令,就用 ! 直接加上 (無空格) 你想要搜索的字元串:
$ echo "alvin"
alvin
$ true
$ false
$ !echo
echo "alvin"
alvin
你還可以搜索在任意位置包含特定字元串的命令。要做到這點,你只需要用 ! 直接加上前後兩端都被 ? 包圍的特定字元串即可,像這樣:
$ echo "alvin"
alvin
$ true
$ false
$ !?alvin?
echo "alvin"
alvin
如果你知道你想要搜索的字元串在命令的最後面,那就可以省略字元串後面的 ?,像這樣:
$ echo alvin
alvin
$ !?alvin
echo alvin
alvin
值得注意的是,若是歷史記錄中包含目標字元串的命令不止一條,則它只會執行符合條件的命令中最後的一條:
$ echo "hello world"
hello world
$ echo "hello alvin"
hello alvin
$ !?hello?
echo "hello alvin"
hello alvin
字元串替換
你可以搜索一個特定的字元串並用新字元串替換它,從而更改命令:
$ echo "hello"
hello
$ echo "world"
world
$ ^hello^alvin
echo "alvin"
alvin
但是它只能替換第一次出現的目標字元串,若是命令中出現兩次目標字元串,則只有第一次出現的會被替換,像這樣:
$ echo "hello hello"
hello hello
$ ^hello^alvin
echo "alvin hello"
alvin hello
與字元串搜索一樣,當歷史記錄中包含目標字元串的命令不止一條時,只替換並執行最後一條:
$ echo "hello world"
hello world
$ echo "hello"
hello
$ ^hello^alvin
echo "alvin"
alvin
充分利用 history 命令
實際上,Bash 的 history
命令的功能遠不止本文所提到的,但這是你習慣使用 history
命令的一個很好的開始,而不僅僅是利用 history
來查看歷史記錄。要經常使用 history
命令,看看你只利用 history
命令而不輸入具體的指令能完成多少事情,你會被驚艷到的。
最後,希望本文對你的工作有所幫助,如果你對 history
命令還有疑問,或者你還知道 history
命令一些更有用的功能,請留言告訴我唄!
公眾號:良許Linux