歷史命令

  • history 的用法:
    [root@linux ~]# history [n]
    [root@linux ~]# history [-c]
    [root@linux ~]# history [-raw] histfiles
    選項:
    n   :數字,『列出最近的 n 筆命令列表』。
    -c  :將目前的 shell 中所有 history 內容全部消除
    -a  :將目前新增的 history 指令新增入 histfiles 中,若沒有加 histfiles ,
          則預設寫入 ~/.bash_history
    -r  :將 histfiles 的內容讀到目前這個 shell 的 history 記憶中;
    -w  :將目前的 history 記憶內容寫入 histfiles 中,histfiles 內容會被覆蓋。
    #範例:
    #範例一:列出目前記憶體內的所有 history 記憶
    [root@linux ~]# history
    # 前面省略
     1017  man bash
     1018  ll
     1019  history 
     1020  history
    # 列出的資訊當中,共分兩欄,第一欄為該指令在這個 shell 當中的代碼,
    # 另一個則是指令本身的內容。至於會秀出幾筆指令記錄,則與 HISTSIZE 有關。
    
    #範例二:列出目前最近的 3 筆資料
    [root@linux ~]# history 3
     1019  history 
     1020  history
     1021  history 3
    
    #範例三:立刻將目前的資料寫入 histfile 當中
    [root@linux ~]# history -w
    # 在預設的情況下,會將歷史紀錄寫入 ~/.bash_history 當中。
    [root@linux ~]# echo $HISTSIZE
    1000
    
  • 假設 HISTSIZE=1000,這次登入主機共下達過 100 次指令,『登出時,系統就會將 101~1100 這總共 1000 筆歷史命令更新到 ~/.bash_history 當中。』
  • 利用相關的功能執行歷史命令:
    [root@linux ~]# !number
    [root@linux ~]# !command
    [root@linux ~]# !!
    參數:
    number  :執行第幾筆指令;
    command :由最近的指令向前搜尋『指令串開頭為 command』的那個指令,並執行;
    !!      :就是執行上一個指令(相當於按↑按鍵後,按 Enter)
    #範例:
    [root@linux ~]# history
       66  man rm
       67  alias
       68  man history
       69  history 
    [root@linux ~]# !66  %*<==執行第 66 筆指令*)
    [root@linux ~]# !!   %*<==執行上一個指令,本例中亦即 !66 *)
    [root@linux ~]# !al  %*<==執行最近以 al 為開頭的指令(上頭列出的第 67 個)*)
    
  • 歷史命令字串搜尋
    1. 按 [Ctrl]+r 後,輸入欲搜尋的字串,bash 會顯示最近一項匹配的命令;
    2. 連續按 [Ctrl]+r 則繼續搜尋前面的歷史命令;
    3. 按 [Enter] 執行顯示的命令,按 [Ctrl]+g 則放棄搜尋。
練習題
  1. 在 bash shell 環境下,如何列出目前記憶體內的所有 history 記憶?
    Sol. history
  2. 在 bash shell 環境下,如何列出目前最近的 6 筆指令資料?
    Sol. history 6
  3. 在 bash shell 環境下,如何將目前 shell 中的所有 history 內容全部消除?
    Sol. history -c
  4. 在 bash shell 環境下,如何將目前新增的 history 指令新增入 histfile 中?
    Sol. history -a histfile
  5. 在 bash shell 環境下,如何將 histfile 的內容讀到目前 shell 的 history 記憶中?
    Sol. history -r histfile
  6. 在 bash shell 環境下,如何將目前 history 記憶內容寫入並覆蓋 histfile?
    Sol. history -w histfile
  7. 在 bash shell 環境下,如何得知 history 記憶容量?
    Sol. echo $HISTSIZE
  8. 在 bash shell 環境下,歷史命令預設存在那個檔案?
    Sol. ~/.bash_history
  9. 在 bash shell 環境下,如何執行第 123 筆歷史命令?
    Sol. !123
  10. 在 bash shell 環境下,如何執行上一筆歷史命令?
    Sol. !!
  11. 在 bash shell 環境下,如何執行最近以 st 開頭的指令?
    Sol. !st
  12. 在 bash shell 環境下,如何搜尋歷史命令含有 st 字串的指令?
    Sol. 按 [Ctrl]+r 後,輸入 st,連續按 [Ctrl]+r 則繼續搜尋前面的歷史命令;按 [Enter] 執行顯示的命令,按 [Ctrl]+g 則放棄搜尋。