原創 良許 良許Linux shell
點擊「閱讀原文」查看良許原創精品視頻。微信
你們好,我是良許
相信你們平時都有用 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 命令以及它經常使用的功能:ide
history 命令與許多其餘的命令不一樣。你可能習慣於命令都做爲可執行文件放置在常見的系統級的位置,例如 /usr/bin,/usr/local/bin 或 〜/ bin。可是,內置的 history 命令並不在你的環境變量 PATH 保存的路徑中的。
實際上,history 命令並無保存在物理位置中:函數
$ which history which: no history in [PATH]
history 實際上是 Shell 自己的一個內置函數:ui
$ 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 中使用。code
history 命令最基本,最頻繁的用法就是查看你的 Shell 會話的命令歷史記錄:視頻
$ echo "hello" hello $ echo "world" world $ history 1 echo "hello" 2 echo "world" 3 history
事件提示符 (!) 是按事件搜索歷史記錄的。這裏的事件,指的是每一條記錄在歷史記錄裏的命令。換句話說,它就是一行命令,並被數字索引標記着以供引用。
要從新運行歷史記錄中的一個命令,用 ! 直接加上 (無空格) 你想要運行的命令前面的索引數字便可。例如,假設歷史記錄中的第一條指令是 echo hello ,而後你想從新運行它:blog
$ !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
實際上,Bash 的 history 命令的功能遠不止本文所提到的,但這是你習慣使用 history 命令的一個很好的開始,而不只僅是利用 history 來查看歷史記錄。要常用 history 命令,看看你只利用 history 命令而不輸入具體的指令能完成多少事情,你會被驚豔到的。
最後,但願本文對你的工做有所幫助,若是你對 history 命令還有疑問,或者你還知道 history 命令一些更有用的功能,請留言告訴我唄!
良許我的微信