Linux下History命令說明

2021-07-03 13:04:26 字數 3116 閱讀 9371

一.命令說明

history命令為bash自帶的命令,使用者可以通過此命令來檢視和管理此使用者執行過的命令。每個會話登陸的時候會將histfile中的命令歷史記錄載入到記憶體中,每個會話退出時會將記憶體中的歷史記錄刷入histfile使用方式後續依次進行說明:

二.使用說明

history [n]

數字n表示檢視

最新的n條

歷史命令(總共行數為histsize變數控制,10000000都可以的)。如果不指定行數則顯示當前會話快取的所有

history -c

將載入在當前shell記憶體中命令歷史記錄清理,同樣會等到登出的時候才會寫到histfile中。

history -d n

將記憶體中數字n指定的行數的命令記錄刪除。

history -anrw [filename]

[filename]:修改預設的histfile,預設為環境變數histfile所對應的名字;

-r:將histfile中的歷史記錄載入到當前shell會話並作為歷史記錄;

-w:將當前會話中的命令歷史記錄重寫到histfile(

覆蓋原有記錄);

-n:將當前會話啟動後histfile中新生成的記錄載入到當前會話記憶體中;

history -ps arg [arg...]

-p:將多個arg分行列印出來,但是不會寫入到history記憶體記錄;

-s:將多個arg分行寫入到history 記憶體記錄

三.相關環境變數

可以將以下環境變數設定到/etc/bashrc中,每個會話登陸的時候都會自動載入。(bashrc中設定這些變數時直接寫var=content就行,無需寫export)

histignore(hist-ignore)

:忽略掉常用的命令(alias),不將他們記錄到日誌中,冒號為分隔符。

histignore="ls *:ll:ls:l:ll *:freq*:cd *:*.log:dl:dc:des:bi:pic:sublime:brackets:open*"

histsize

:表示最多可以存多少條命令(先進先出),可以在/etc/bashrc和~/.bash_profile裡面設定(1000000不會報錯)。

histfilesize

:表示檔案的最大大小,預設也是1000,可以自行設定;

histtimeformat(hist-time-format):記錄命令執行的時間格式(存到histfile的為%s的格式),如果不設定此變數histfile檔案中將不會記錄命令執行的時間戳;

histtimeformat="%f_%t"

histfile

:設定歷史檔名,預設為~/.bash_history,如果想要另外指定地方可以手工設定;

histfile="/home/$user/test_2015

四.使用技巧

1.每次條命令執行完後立即寫入histfile,無需等待退出會話。可以在bashrc中加入以下內容(prompt_command即命令列提示符):

prompt_command="history -a; $prompt_command"

2.為防止會話退出時覆蓋其他會話寫到histfile的內容,可以在/etc/bashrc中加入以下內容:

3.執行歷史命令:

!n:檢視並執行第n條命令;

!!:檢視並執行上一條命令;

!str:檢視以str打頭的命令

五.使用案例

1.在/etc/bashrc中加入以下內容,每年將使用者的命令歷史儲存到/

security/bash_history/$user下:

##for security log

uip=`who am i|awk ''`

syear=`date +%y`

if [ -d /security/bash_history/$user ] ; then :

else

mkdir -p /

security/bash_history/$user

fiif [ -e /

security/bash_history/$user/$user_$syear ] ; then :

else

touch /

security/bash_history/$user/bashhistory_$syear

fihistfile="/

security/bash_history/$user/bashhistory_$syear"

histsize=100000000

histfilesize=100000000

histtimeformat="%f_%t  "

prompt_command="history -a;$prompt_command"

其實,我的初衷是想記錄每個會話:執行時間 登陸ip及登入名 所執行的命令。如果哪位大神有好的建議請不吝提出,謝謝!

linux下history命令的使用小結

1.history 使用history命令檢視之前執行過的命令。在命令提示符中執行命令時,會被記錄在 bash history檔案中,可以通過history命令檢視。2.關於history的一些常用的用法 1 讓history命令輸出的歷史命令時,列印出時間戳 即使用環境變數histtimeform...

Linux基礎命令 history

shell內建命令 history命令用於顯示指定數目的指令命令,讀取歷史命令檔案中的目錄到歷史命令緩衝區和將歷史命令緩衝區中的目錄寫入命令檔案。該命令單獨使用時,僅顯示歷史命令,在命令列中,可以使用符號 執行指定序號的歷史命令。例如,要執行第2個歷史命令,則輸入 2。歷史命令是被儲存在記憶體中的,...

linux下history命令的使用方法

如果你經常使用linux命令,那麼使用history命令無疑會提公升你的工作效率。history命令主要用於顯示歷史指令記錄內容,下達歷史紀錄中的指令 1 history命令語法 test linux history n test linux history c test linux history...