4. 命令行历史


这可能是您最常用的命令历史记录功能。 如果您已经执行了很长的命令,您可以简单地使用关键字搜索历史记录并重新执行相同的命令,而无需完整键入它。 只需按 Ctrl+R并输入关键字即可。

在下面的示例中,我搜索了关键字 red,它显示了上一个包含单词 red 的命令(cat /etc/redhat-release)。

$ [Press Ctrl+R from the command prompt]
(reverse-i-search)`red': cat /etc/redhat-release

[Press enter when you see your command to execute it]

$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.0 (Santiago)

有时您想在执行之前编辑历史命令。 例如,您可以搜索关键字 “httpd”,它将从历史记录中显示 service httpd stop命令,选择该命令并将 stop 更改为 start 并重新执行,如下所示。

$ [Press Ctrl+R from the command prompt]
(reverse-i-search)`httpd': service httpd stop

[Press left arrow key when you see your command, edit it, and press Enter to execute it]

$ service httpd start

以下是重复上次执行的命令的 5 种不同方法。

  1. 向上箭头并按Enter
  2. 输入!!然后按Enter
  3. 输入 !-1并按Enter
  4. emacs 模式下,按Control+P并按Enter
  5. vi 模式下,按<Esc>-k并按Enter

在下面的示例中,如果您想重复命令 #4 ,您可以执行!4,如下所示。

$ history | more
1 service network restart
2 exit
3 id
4 cat /etc/redhat-release

$ !4
cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.0 (Santiago)

键入!,接下来是您要重新执行的命令的开头几个字母。

在下面的示例中,输入!ps并按Enter键,执行了上一个以ps开头的命令,即ps aux | grep yp

$ !ps
ps aux | grep yp
root 16947 0.1 1264 ? 0:00 ypbind

有时您可能想清除所有以前的历史记录,但又想让历史记录继续前进。

$ history -c

有时,在搜索历史记录时,您可能想要执行不同的命令,但使用与刚刚在历史记录中找到的命令相同的参数。

在下面的示例中,vi命令旁边的!!:$获取从上一个命令到当前命令的参数。

$ ls anaconda-ks.cfg

$ vi !!:$
vi anaconda-ks.cfg

在下面的示例中,vi命令旁边的!^获取从前一个命令(即cp)到当前命令(即 vi)的第一个参数。

$ cp anaconda-ks.cfg anaconda-ks.cfg.bak

$ vi !^
vi anaconda-ks.cfg

在下面的示例中,!cp:2 搜索历史记录中以cp开头的上一个命令,采用cp的第二个参数并将其替换为ls -l命令,如下所示。

$ cp ~/longname.txt /very/long/path/long-filename.txt

$ ls -l !cp:2
ls -l /very/long/path/long-filename.txt

在下面的示例中,!cp:$搜索历史记录中以cp开头的上一个命令,并采用cp的最后一个参数(在本例中,也是如上所示的第二个参数)并将其替换为ls -l命令如下所示。

$ ls -l !cp:$
ls -l /very/long/path/long-filename.txt