
Linux’s shell saves a history of the commands you run, and you can search it to repeat commands you’ve run in the past. Once you understand the Linux history command and how to use it, it can significantly boost your productivity.
Linux的外殼程序保存了您運行的命令的歷史記錄,您可以搜索它以重復您過去運行的命令。 一旦您了解了Linux歷史記錄命令以及如何使用它,它將極大地提高您的生產率。
操縱歷史 (Manipulating History)
As George Santayana famously said, “Those who cannot remember the past are condemned to repeat it.” Unfortunately, on Linux, if you can’t remember the past, you can’t repeat it, even if you want to.
正如喬治·桑塔亞那(George Santayana)所說的那樣:“那些不記得過去的人會被譴責以重蹈覆轍。” 不幸的是,在Linux上,即使您不記得過去,也無法重復過去。
That’s when the Linux history
command comes in handy. It allows you to review and repeat your previous commands. This isn’t intended to just encourage laziness or save time—there’s also an efficiency (and accuracy) factor at play. The lengthier and more complicated a command is, the harder it is to remember and type without making an error. There are two types of errors: one that prevents the command from working, and one that allows the command to work, but makes it do something unexpected.
那就是Linux history
命令派上用場的時候。 它允許您查看并重復以前的命令。 這不只是為了鼓勵懶惰或節省時間,還有效率(和準確性)因素在起作用。 命令越長,越復雜,記住和鍵入而不出錯就越難。 有兩種類型的錯誤:一種阻止命令運行,而另一種允許命令運行,但使其無法正常工作。
The?history
command eliminates those issues. Like most Linux commands, there’s more to it than you might think. However, if you learn how to use the history
command, it can improve your use of the Linux command line, every single day. It’s a good investment of your time.?There are far better ways to use the history
?command than just?hitting the Up arrow repeatedly.
history
命令消除了這些問題。 像大多數Linux命令一樣,它所具有的功能超出您的想象。 但是,如果您學習如何使用history
命令,它可以每天改善您對Linux命令行的使用。 這是您寶貴的時間投入。 有比使用history
命令更好的方法,而不僅僅是反復按向上箭頭。
歷史命令 (The history Command)
In its simplest form, you can use the history
command by just typing its name:
以最簡單的形式,您只需鍵入其名稱即可使用history
命令:
history

The list of previously used commands is then written to the terminal window.
然后將先前使用的命令列表寫入終端窗口。

The commands are numbered, with the most recently used (those with the highest numbers) at the end of the list.
這些命令已編號,最近使用的(編號最高的命令)位于列表的末尾。
To see a certain number of commands, you can pass a number to history
on the command line. For example, to see the last 10 commands you’ve used, type the following:
要查看一定數量的命令,可以在命令行上將數字傳遞給history
。 例如,要查看您使用的最后10個命令,請鍵入以下內容:
history 10

You can achieve the same result if you pipe history
through the tail
command. To do so, type the following:
你可以達到同樣的效果,如果你管history
通過tail
命令。 為此,請鍵入以下內容:
history | tail -n 10

重復指令 (Repeating Commands)
If you want to reuse a command from the history list, type an exclamation point (!), and the number of the command with no spaces in-between.
如果要重用歷史記錄列表中的命令,請鍵入一個感嘆號(!),以及命令號之間不要有空格。
For example, to repeat command number 37, you would type this command:
例如,要重復命令號37,請鍵入以下命令:
!37

To repeat the last command, type two exclamation points, again, without spaces:
要重復最后一個命令,請再次輸入兩個感嘆號,不要帶空格:
!!

This can be useful when you issue a command and forget to use sudo
. Type sudo
, one space, the double exclamation points, and then hit Enter.
當您發出命令而忘記使用sudo
時,這很有用。 鍵入sudo
,一個空格,雙倍感嘆號,然后按Enter。
For the following example, we typed a command that requires sudo
. Instead of retyping the whole line, we can save a bunch of keystrokes and just type?sudo !!
, as shown below:
對于以下示例,我們鍵入了一個需要sudo
。 無需重新輸入整個代碼行,我們可以節省大量擊鍵,只需鍵入sudo !!
, 如下所示:
mv ./my_script.sh /usr/local/bin/
sudo !!

So, you can type the corresponding number from the list to repeat a command or use the double exclamation points to repeat the last command you used. However, what if you want to repeat the fifth or eighth command?
因此,您可以從列表中鍵入相應的數字以重復執行命令,或使用雙感嘆號重復上次使用的命令。 但是,如果要重復第五或第八條命令怎么辦?
You can use one exclamation point, a hyphen (-), and the number of any previous command (again, without spaces) to repeat it.
您可以使用一個感嘆號,一個連字符(-)和任何先前命令的編號(同樣,不帶空格)來重復它。
To repeat the 13th previous command, you would type the following:
要重復前面的第13條命令,請鍵入以下內容:
!-13

通過字符串搜索命令 (Searching for Commands by String)
To repeat the last command that starts with a particular string, you can type an exclamation point, and then the string with no spaces, and then hit Enter.
要重復以特定字符串開頭的最后一條命令,可以鍵入一個感嘆號,然后鍵入不帶空格的字符串,然后按Enter。
For example, to repeat the last command that started with sudo
, you would type this command:
例如,要重復以sudo
開頭的最后一個命令,請輸入以下命令:
!sudo

There’s an element of danger in this, though. If the last command that started with sudo
?isn’t the one you think it is, you’ll launch the wrong command.
但是,這有一個危險因素。 如果以sudo
開頭的最后一個命令不是您認為的那個命令,則會啟動錯誤的命令。
To provide a safety net, though, you can use the :p
(print) modifier, as shown below:
但是,要提供安全網,可以使用:p
(打印)修飾符,如下所示:
!sudo:p

This instructs history
to print the command to the terminal window, rather than executing it. This allows you to see the command before you use it. If it is the command you want, press the Up arrow, and then hit Enter to use it.
這指示history
將命令打印到終端窗口,而不是執行命令。 這使您可以在使用命令之前先查看該命令。 如果這是您想要的命令,請按向上箭頭,然后按Enter鍵以使用它。
If you want to find a command that contains a particular string, you can use an exclamation point and question mark.
如果要查找包含特定字符串的命令,則可以使用感嘆號和問號。
For example, to find and execute the first matching command that contains the word “aliases,” you would type this command:
例如,要查找并執行第一個包含單詞“ aliases”的匹配命令,可以鍵入以下命令:
!?aliases

This will find any command that contains the string “aliases,” regardless of where it appears in the string.
這將查找包含字符串“ aliases”的任何命令,而不管其在字符串中的位置如何。
互動搜尋 (Interactive Search)
An interactive search allows you to hop through a list of matching commands and repeat the one you want.
交互式搜索使您可以瀏覽一系列匹配的命令,然后重復所需的命令。
Just press Ctrl+r to start the search.
只需按Ctrl + r即可開始搜索。

As you type the search clue, the first matching command will appear. The letters you type appear between the backtick (`) and the apostrophe (‘). The matching commands update as you type each letter.
鍵入搜索線索時,將出現第一個匹配的命令。 您鍵入的字母出現在反引號(`)和撇號(')之間。 鍵入每個字母時,匹配的命令會更新。

Each time you press Ctrl+r, you’re searching backward for the next matching command, which appears in the terminal window.
每次按Ctrl + r,都會向后搜索下一個匹配命令,該命令顯示在終端窗口中。

When you press Enter, the displayed command will execute.
當您按Enter鍵時,將執行顯示的命令。

To edit a command before you execute it, press either the Left or Right arrow key.
要在執行命令之前對其進行編輯,請按向左或向右箭頭鍵。

The command appears on the command line, and you can edit it.
該命令出現在命令行上,您可以對其進行編輯。

You can use other Linux tools to search the history list. For example, to pipe the output from history
into grep
?and search for commands that contain the string “aliases” you could use this command:
您可以使用其他Linux工具來搜索歷史記錄列表。 例如,要將history
的輸出傳遞到grep
并搜索包含字符串“ alias”的命令,可以使用以下命令:
history | grep aliases

修改最后一個命令 (Modifying the Last Command)
If you need to fix a typo, and then repeat the command, you can use the caret (^) to modify it. This a great trick to have up your sleeve for whenever you misspell a command or want to rerun one with a different command-line option or parameter.
如果需要修復拼寫錯誤,然后重復該命令,則可以使用插入符號(^)對其進行修改。 每當您拼寫錯誤的命令或想使用其他命令行選項或參數重新運行該命令時,這都是一個絕妙的技巧。
To use it, type (without spaces) a caret, the text you want?to replace, another caret, the text you want to replace it with, another caret, and then press Enter.
若要使用它,請鍵入(無空格)插入記號,要替換的文本,另一個插入記號,要替換為的文本,另一個插入記號,然后按Enter。
For example, suppose you type the following command, accidentally typing “shhd” instead of “sshd”:
例如,假設您鍵入以下命令,而無意中鍵入了“ shhd”而不是“ sshd”:
sudo systemctl start shhd
You could correct this easily by typing the following:
您可以通過鍵入以下內容來更正此錯誤:
^shhd^sshd^

The command is executed with “shhd” corrected to “sshd.”
在將“ shhd”更正為“ sshd”的情況下執行命令。
從歷史記錄列表中刪除命令 (Deleting Commands from the History List)
You can also delete commands from the history list with the -d
(delete) option. There’s no reason to keep your misspelled command in the history list.
您還可以使用-d
(刪除)選項從歷史記錄列表中刪除命令。 沒有理由將拼寫錯誤的命令保留在歷史記錄列表中。
You can use grep
to find it, pass its number to history
with the -d
option to delete it, and then search again to make sure it’s gone:
您可以使用grep
查找它,使用-d
選項將其編號傳遞到history
以將其刪除,然后再次搜索以確保它消失了:
history | grep shhd
history -d 83
history | grep shhd

You can also pass a range of commands to the -d
option. To delete all list entries from 22 to 32 (inclusive), type this command:
您還可以將一系列命令傳遞給-d
選項。 要將所有列表條目從22刪除到32(包括32),請鍵入以下命令:
history -d 22 32
To delete only the last five commands, you can type a negative number, like so:
要僅刪除最后五個命令,可以鍵入一個負數,如下所示:
history -d -5
手動更新歷史記錄文件 (Manually Updating the History File)
When you log in or open a terminal session, the history list is read in from the history file. In Bash, the default history file is .bash_history
.
登錄或打開終端會話時,將從歷史文件中讀取歷史列表。 在Bash中,默認歷史記錄文件是.bash_history
。
Any changes you make in your current terminal window session are only written to the history file when you close the terminal window or log out.
您在當前終端窗口會話中所做的任何更改僅在您關閉終端窗口或注銷時才寫入歷史文件。
Suppose you want to open another terminal window to access the full history list, including commands you typed in the first terminal window. The -a
(all) option allows you to do this in the first terminal window before you open the second.
假設您想打開另一個終端窗口以訪問完整的歷史記錄列表,包括您在第一個終端窗口中鍵入的命令。 -a
(所有)選項允許您在打開第二個終端窗口之前在第一個終端窗口中執行此操作。
To use it, type the following:
要使用它,請鍵入以下內容:
history -a

The commands are written silently to the history file.
這些命令將以靜默方式寫入歷史文件。
If you want to write all changes to the history list to the history file (if you deleted some old commands, for example), you can use the -w
(write) option, like so:
如果要將對歷史記錄列表的所有更改都寫入歷史記錄文件(例如,如果刪除了一些舊命令),則可以使用-w
(寫)選項,如下所示:
history -w

清除歷史記錄列表 (Clearing the History List)
To clear all commands from the history list, you can use the -c
(clear) option, as follows:
要清除歷史記錄列表中的所有命令,可以使用-c
(清除)選項,如下所示:
history -c

If you additionally want to force these changes to the history file, use the -w
option, like so:
如果您還想將這些更改強制添加到歷史記錄文件,請使用-w
選項,如下所示:
history -w
安全性和歷史記錄文件 (Security and the History File)
If you use any applications that require you to type sensitive information (like passwords) on the command line, remember this will also be saved in the history file. If you don’t want certain information saved, you can use the following command structure to delete it from the history list immediately:
如果您使用任何需要在命令行上鍵入敏感信息(例如密碼)的應用程序,請記住,這些信息也將保存在歷史記錄文件中。 如果您不想保存某些信息,則可以使用以下命令結構立即將其從歷史記錄列表中刪除:
special-app my-secret-password;history -d $(history 1)
history 5

This structure includes two commands separated with a semicolon (;). Let’s break this down:
該結構包括兩個用分號(;)分隔的命令。 讓我們分解一下:
special-app: The name of the program we’re using.
special-app :我們正在使用的程序的名稱。
my-secret-password: The secret password we need to provide for the application on the command line. This is the end of command one.
my-secret-password :我們需要在命令行上為應用程序提供的秘密密碼。 這是命令一的結尾。
history -d: In command two, we invoke the
-d
(delete) option ofhistory
. What we’re going to delete comes is in the next portion of the command.history -d :在命令二中,我們調用
history
的-d
(刪除)選項。 我們要刪除的內容位于命令的下一部分。$(history 1): This uses a command substitution.? The portion of the command contained in the?
$()
?is executed in a subshell. The result of that execution posts as text in the original command. Thehistory 1
command returns the previous command. So, you can think of the second command as history -d “last command here.”$(history 1) :這使用命令替換。
$()
包含的命令部分在子shell中執行。 執行結果以文本形式發布在原始命令中。history 1
命令返回上一條命令。 因此,您可以將第二個命令視為history -d“此處的最后一個命令”。
You can use the history 5
command to make sure the command containing the password was removed from the history list.
您可以使用history 5
命令來確保從歷史記錄列表中刪除了包含密碼的命令。
There’s an even simpler way to do this, though. Because Bash ignores lines that begin with a space by default, just include a space at the start of the line, as follows:
不過,還有一種更簡單的方法可以做到這一點。 由于Bash默認情況下會忽略以空格開頭的行,因此只需在行的開頭添加一個空格,如下所示:
special-app another-password
history 5

The command with the password isn’t added to the history list. The reason this trick works is contained within the .bashrc
file.
帶有密碼的命令不會添加到歷史記錄列表中。 該技巧起作用的原因包含在.bashrc
文件中。
.bashrc文件 (The .bashrc File)
The?.bashrc
?file executes each time you log in or open a terminal window. It also contains some values that control the behavior of the history
command.?Let’s edit this file?with?gedit
.
.bashrc
文件在您每次登錄或打開終端窗口時執行。 它還包含一些控制history
命令行為的值。 讓我們使用gedit
編輯該文件。
Type the following:
輸入以下內容:
gedit .bashrc

Near the top of the file, you see two entries:
在文件頂部附近,您會看到兩個條目:
HISTSIZE
:?The maximum number of entries the history list can contain.HISTSIZE
:歷史記錄列表可以包含的最大條目數。HISTFILESIZE
:?The limit for the number of lines a history file can contain.HISTFILESIZE
:歷史文件可以包含的行數限制。

These two values interact in the following ways:
這兩個值以下列方式相互作用:
When you log in or start a terminal window session, the history list is populated from the
.bash_history
file.登錄或啟動終端窗口會話時,將從
.bash_history
文件填充歷史記錄列表。When you close a terminal window, the maximum number of commands set in
HISTSIZE
?are saved to the.bash_history
?file.關閉終端窗口時,在
HISTSIZE
中設置的最大命令數將保存到.bash_history
文件中。If the
histappend
shell option is enabled, the commands are appended to.bash_history
. Ifhistappend
isn’t set,.bash_history
is overwritten.如果
histappend
外殼選項啟用,該命令被追加到.bash_history
。 如果histappend
沒有設置,.bash_history
被覆蓋。After saving the commands from the history list to
.bash_history
, the history file is truncated to contain no more thanHISTFILESIZE
lines.將歷史記錄中的命令保存到
.bash_history
,歷史記錄文件將被截斷以包含不超過HISTFILESIZE
行。
Also near the top of the file, you see an entry for the HISTCONTROL
value.
同樣在文件頂部附近,您會看到一個HISTCONTROL
值的條目。

You can set this value to do any of the following:
您可以將此值設置為執行以下任一操作:
ignorespaces:
Lines that begin with a space aren’t added to the history list.ignorespaces :
以空格開頭的行不會添加到歷史記錄列表中。ignoredups:
Duplicate commands aren’t added to the history file.ignoredups :
重復的命令不會添加到歷史文件中。ignoreboth:
Enables both of the above.ignoreboth :
啟用上述兩項。
You can also list specific commands you don’t want added to your history list. Separated these with a colon (:) and put them in quotation marks (“…”).
您還可以列出不想添加到歷史記錄列表中的特定命令。 用冒號(:)隔開,并用引號(“…”)引起來。
You would follow this structure to add a line to your?.bashrc
file, and substitute the commands you want to be ignored:
您將按照以下結構在.bashrc
文件中添加一行,并替換要忽略的命令:
export HISTIGNORE="ls:history"

使用時間戳 (Using Timestamps)
If you want to add timestamps to the history list, you can use the HISTIMEFORMAT
setting. To do so, you just add a line like the following to your .bashrc
file:
如果要將時間戳添加到歷史記錄列表,則可以使用HISTIMEFORMAT
設置。 為此,您只需在.bashrc
文件中添加以下內容即可:
export HISTTIMEFORMAT="%c "
Note that there’s a space before the closing quotation marks. This prevents the timestamp from butting up to the commands in the command list.
請注意,右引號前有一個空格。 這樣可以防止時間戳與命令列表中的命令對接。

Now, when you run the history command, you see date- and timestamps. Note that any commands that were in the history list before you added the timestamps will be timestamped with the date and time of the first command that receives a timestamp. In this example shown below, this was command 118.
現在,當您運行history命令時,您會看到日期和時間戳。 請注意,在添加時間戳之前,歷史記錄列表中的所有命令都將帶有第一個接收時間戳的命令的日期和時間作為時間戳。 在下面顯示的示例中,這是命令118。

That’s a very long-winded timestamp. However, you can use tokens other than?%c
?to refine it. The other tokens you can use are:
那是一個非常漫長的時間戳。 但是,您可以使用%c
以外的標記來優化它。 您可以使用的其他令牌是:
%d
: Day%d
:天%m
: Month%m
:月份%y
: Year%y
:年份%H
:?Hour%H
:小時%M
:?Minutes%M
:分鐘%S
: Seconds%S
:秒%F
: Full date (year-month-date format)%F
:完整日期(年月日格式)%T
: Time (hour:minutes:seconds format)%T
:時間(小時:分鐘:秒格式)%c
: Complete date and time stamp (day-date-month-year, and hour:minutes:seconds formats)%c
:完整的日期和時間戳記(日-日期-月-年,以及小時:分鐘:秒格式)
Let’s experiment and use a few different tokens:
讓我們進行實驗并使用一些不同的令牌:
export HISTTIMEFORMAT="%d n%m %T "

The output uses the day, month, and time.
輸出使用日期,月份和時間。

If we remove the day and month, though, it will just show the time.
但是,如果我們刪除日期和月份,它將只顯示時間。
Any changes you make to HISTIMEFORMAT
apply themselves to the entire history list. This is possible because the time for each command is stored as the?number of seconds from the Unix epoch. The HISTTIMEFORMAT
directive simply specifies the format used to render that number of seconds into a human-readable style, such as:
您對HISTIMEFORMAT
任何更改HISTIMEFORMAT
將其自身應用于整個歷史記錄列表。 這是可能的,因為每個命令的時間都存儲為從Unix紀元開始的秒數。 HISTTIMEFORMAT
指令僅指定用于將該秒數呈現為人類可讀樣式的格式,例如:
export HISTTIMEFORMAT="%T "

Our output is now more manageable.
現在,我們的輸出更易于管理。

You can also use the history
command to audit. Sometimes, reviewing?commands?you’ve used in the past can help you identify what might have caused an issue.
您還可以使用history
命令進行審核。 有時,查看過去使用的命令可以幫助您確定可能導致問題的原因。
Just as you can in life, on Linux, you can use the?history
?command to relive the good times and learn from the bad.
就像您在生活中一樣,在Linux上,您可以使用history
命令重溫美好時光并從不幸中學習。
翻譯自: https://www.howtogeek.com/465243/how-to-use-the-history-command-on-linux/