如何在Linux上使用history命令

A terminal prompt on a Linux laptop computer.
Fatmawati Achmad Zaenuri/Shutterstock Fatmawati Achmad Zaenuri / Shutterstock

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 "history" command in a terminal window.

The list of previously used commands is then written to the terminal window.

然后将先前使用的命令列表写入终端窗口。

An example of output from the "history" command in a 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
The "history 10" command in a terminal window.

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
The "history | tail -n 10" command in a terminal window.

重复指令 (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
An "!37" command in a terminal window.

To repeat the last command, type two exclamation points, again, without spaces:

要重复最后一个命令,请再次输入两个感叹号,不要带空格:

!!
An "!!" command in a terminal window.

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 !!
An "mv ./my_script.sh /usr/local/bin/" command in a terminal window.

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
An "!-13" command in a terminal window.

通过字符串搜索命令 (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
An "!sudo" command in a terminal window.

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
An "!sudo:p" command in a terminal window.

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
An "!?aliases" command in a terminal window.

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即可开始搜索。

A terminal window after "Ctrl+r" is pressed.

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.

键入搜索线索时,将出现第一个匹配的命令。 您键入的字母出现在反引号(`)和撇号(')之间。 键入每个字母时,匹配的命令会更新。

A "Ctrl+r" search with "sudo" typed as the search clue.

Each time you press Ctrl+r, you’re searching backward for the next matching command, which appears in the terminal window.

每次按Ctrl + r,都会向后搜索下一个匹配命令,该命令显示在终端窗口中。

A "Ctrl+r" search showing a matching command in a terminal window.

When you press Enter, the displayed command will execute.

当您按Enter键时,将执行显示的命令。

The "gedit" command in a terminal window launched from a "Ctrl+r" search command.

To edit a command before you execute it, press either the Left or Right arrow key.

要在执行命令之前对其进行编辑,请按向左或向右箭头键。

A "Ctrl+r" search in a terminal window.

The command appears on the command line, and you can edit it.

该命令出现在命令行上,您可以对其进行编辑。

A command on the command line with editing enabled.

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
The "history | grep aliases" command in a terminal window.

修改最后一个命令 (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^
A "sudo systemctl start shhd" command in a terminal window.

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
The "history | grep shhd" command in a terminal window.

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 "history -a" command in a terminal window.

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
The "history -w" command in a terminal window.

清除历史记录列表 (Clearing the History List)

To clear all commands from the history list, you can use the -c (clear) option, as follows:

要清除历史记录列表中的所有命令,可以使用-c (清除)选项,如下所示:

history -c
history -c in a terminal window

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
A "special-app my-secret-password;history -d $(history 1)" command in a terminal window.

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 of history. 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. The history 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
A " special-app another-password" command in a terminal window.

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
The "gedit .bashrc" command in a terminal window.

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 历史文件可以包含的行数限制。

".bashrc" in the gedit editor.

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. If histappend 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 than HISTFILESIZE lines.

    将历史记录中的命令保存到.bash_history ,历史记录文件将被截断以包含不超过HISTFILESIZE行。

Also near the top of the file, you see an entry for the HISTCONTROL value.

同样在文件顶部附近,您会看到一个HISTCONTROL值的条目。

The "HISTCONTROL" entry in the ".bashrc" file in gedit.

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"
An "export HISTIGNORE="ls:history" command in gedit.

使用时间戳 (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.

请注意,右引号前有一个空格。 这样可以防止时间戳与命令列表中的命令对接。

An "export HISTTIMEFORMAT="%c " command in gedit.

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。

A history list with timestamps in a terminal window.

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 export HISTTIMEFORMAT="%d n%m %T " command in gedit.

The output uses the day, month, and time.

输出使用日期,月份和时间。

A history list with timestamps in a terminal window.

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 HISTTIMEFORMATdirective 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 "
The "export HISTTIMEFORMAT="%T" command in gedit.

Our output is now more manageable.

现在,我们的输出更易于管理。

A history list with timestamps in a terminal window.

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/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值