4. 命令行历史
使用 Ctrl+R
搜索历史记录
这可能是您最常用的命令历史记录功能。 如果您已经执行了很长的命令,您可以简单地使用关键字搜索历史记录并重新执行相同的命令,而无需完整键入它。
只需按 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 种不同方法。
- 向上箭头
↑
并按Enter
键 - 输入
!!
然后按Enter
键 - 输入
!-1
并按Enter
键 - 在
emacs
模式下,按Control+P
并按Enter
键 - 在
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
使用选项 -c
清除所有以前的历史记录
有时您可能想清除所有以前的历史记录,但又想让历史记录继续前进。
$ 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