如果你經常使用 Linux 命令行,那麼使用 history(歷史)命令可以有效地提升你的效率。
現在我將通過實例的方式向你介紹 history 命令的15個用法。
1. 使用 HISTTIMEFORMAT 顯示時間戳
當你從命令行執行 history 命令後,通常只會顯示已執行命令的序號和命令本身。如果你想要查看命令歷史的時間戳,那麼可以執行:
# export HISTTIMEFORMAT='%F %T '
# history | more
1 2008-08-05 19:02:39 service network restart
2 2008-08-05 19:02:39 exit
3 2008-08-05 19:02:39 id
4 2008-08-05 19:02:39 cat /etc/RedHat-release
2. 使用 Ctrl+R 搜索歷史
Ctrl+R 是我經常使用的一個快捷鍵。此快捷鍵讓你對命令歷史進行搜索,對於想要重復執行某個命令的時候非常有用。當找到命令後,通常再按回車鍵就可以執行該命令。如果想對找到的命令進行調整後再執行,則可以按一下左或右方向鍵。
# [Press Ctrl+R from the command prompt, which will display the reverse-i-search prompt]
(reverse-i-search)`red‘: cat /etc/redhat-release
[Note: Press enter when you see your command, which will execute the command from the history]
# cat /etc/redhat-release
Fedora release 9 (Sulphur)
3. 快速重復執行上一條命令
有 4 種方法可以重復執行上一條命令:
1. 使用上方向鍵,並回車執行。
2. 按 !! 並回車執行。
3. 輸入 !-1 並回車執行。
4. 按 Ctrl+P 並回車執行。
4. 從命令歷史中執行一個指定的命令
在下面的例子中,如果你想重復執行第 4 條命令,那麼可以執行 !4:
# history | more
1 service network restart
2 exit
3 id
4 cat /etc/redhat-release
# !4
cat /etc/redhat-release
Fedora release 9 (Sulphur)
5. 通過指定關鍵字來執行以前的命令
在下面的例子,輸入 !ps 並回車,將執行以 ps 打頭的命令:
# !ps
ps aux | grep yp
root 16947 0.0 0.1 36516 1264 ? Sl 13:10 0:00 ypbind
root 17503 0.0 0.0 4124 740 pts/0 S+ 19:19 0:00 grep yp
6. 使用 HISTSIZE 控制歷史命令記錄的總行數
將下面兩行內容追加到 .bash_profile 文件並重新登錄 bash shell,命令歷史的記錄數將變成 450 條:
# vi ~/.bash_profile
HISTSIZE=450
HISTFILESIZE=450
7. 使用 HISTFILE 更改歷史文件名稱
默認情況下,命令歷史存儲在 ~/.bash_history 文件中。添加下列內容到 .bash_profile 文件並重新登錄 bash shell,將使用 .commandline_warrior 來存儲命令歷史:
# vi ~/.bash_profile
HISTFILE=/root/.commandline_warrior