如何使終端機根據先前輸入的命令自動完成?

如何使終端機根據先前輸入的命令自動完成?

使用終端機時,按向上和向下循環按時間順序輸入先前的命令是正常的。

我從一個網站了解到如何透過在按下向上和向下鍵時根據先前輸入的命令自動完成我在遊標處輸入的內容來添加該行為。

例如,假設我按此順序鍵入以下命令:

  1. ls Videos
  2. ls Vids
  3. lsomething
  4. ls Videos/Funny/Old
  5. vi file
  6. ls Music

如果我沒有輸入任何內容,則按向上和向下鍵將像平常一樣循環瀏覽所有行。但是,如果我輸入了ls,則按向上和向下鍵會循環瀏覽前 2 個字元所在的所有命令ls(上面的第 1、2、3、4、6 行)。但輸入ls(後面有一個空格)只會讓上下迴圈遍歷第 1、2、4、6 行。同樣,ls Vid讓箭頭在第 1、2、4 行之間循環,但ls Videos只允許在第 1 行和第 4 行之間循環。

完成特定於您需要一遍又一遍輸入的命令的值非常有用,而不必循環瀏覽您在它們之間輸入的每個不相關的命令。例如,我正在嘗試測試env值(例如區域設定)對事物的影響:

env [many different values] [command]
[insert many different commands here]
env [slightly different values from before] [command]
[doing other stuff]

我只需在輸入後按幾次向上鍵即可env在我嘗試過的值之間循環。

如果描述起來有點長,我深感抱歉。我不知道它叫什麼。我的終端曾經有這種行為,但他們似乎已經失去了它,我找不到我從中學到它的網站。我認為這與編輯有關~/.bashrc

答案1

要獲得您想要的行為,請將這些行新增至您的檔案~/.inputrc(如果檔案不存在,請建立該檔案):

"\e[A": history-search-backward
"\e[B": history-search-forward

然後,打開一個新終端,它將按預期工作。此行為由/etc/inputrc和中的設定控制~/.inputrc。您可以在以下Readline Command Names部分閱讀有關它們的更多資訊man bash

   non-incremental-forward-search-history (M-n)
          Search forward  through  the  history  using  a  non-incremental
          search for a string supplied by the user.
   history-search-forward
          Search  forward through the history for the string of characters
          between the start of the current line and the point.  This is  a
          non-incremental search.

相關內容