首页 > 编程笔记 > Linux笔记 阅读:74

Linux history命令详解(非常全面)

Bash 具有完善的历史命令,这对于简化管理操作、排查系统错误都起到了重要的作用,而且使用起来简单、方便,善用历史命令可以有效地提高我们的工作效率。

系统保存的历史命令可以使用 history 命令查询,命令格式如下:
[root@localhost~]# history [选项][历史命令保存文件]
选项:
如果 history 命令直接执行,就可用于查询系统中的历史命令,命令如下:
[root@localhost~]# history
...省略部分输出...
525 ls
526 cd /opt/
527 cd /tmp/
528 ls
529 pwd
530 history
这样就可以查询我们刚刚输入的系统命令,而且每条命令都是有编号的。历史命令默认会保存 1000 条,这是通过环境变量 HISTSIZE 来设置的,我们可以在环境变量配置文件 /etc/profile 中进行修改,如修改为保存 10000 条,命令如下:
[root@localhost~]# vi /etc/profile
HISTSIZE=10000
...省略部分输出...
大家需要注意,每个用户的历史命令是单独保存的,因此每个用户的家目录中都有 .bash_history 这个历史命令文件。

如果某个用户的历史命令总条数超过了历史命令保存条数,那么新命令会变成最后 1 条命令,最早的命令则会被删除。假设系统能够保存 1000 条历史命令,而系统中已经保存了 1000 条历史命令,那么新输入的命令会被保存成第 1000 条命令,而最早的第 1 条命令会被删除。

还要注意的是,我们使用 history 命令查看的历史命令和 ~/.bash_history 文件中保存的历史命令是不同的。这是因为当前登录操作的命令并没有直接写入 ~/.bash_history 文件,而是保存在缓存中,需要等当前用户注销(退出登录)后,缓存中的命令才会写入 ~/.bash_history 文件。

如果我们需要把内存中的命令立即写入 ~/.bash_history 文件,而不等用户注销时再写入,就需要使用“-w”选项,命令如下:
[root@localhost~]# history -w
#把缓存中的历史命令立即写入~/.bash_history文件

命令执行后查询 ~/.bash_history 文件,历史命令文件中的内容就和 history 命令查询的结果一致了。同时,我们可以在执行“-w”选项后指定一个文件名,表示将当前的历史命令写入指定的文件,命令如下:
[root@localhost~]# history -w /root/linux_hb.his
#将历史命令写入/root/linux_hb.his文件
[root@localhost~]# cat -n /root/linux_hb.his
696 ls
697 pwd
698 history
699 cd
700 history -w /root/linux_hb.his
#通过查看,发现linux_hb.his文件中保存了700条历史命令

此时,如果我们使用“-a”选项将历史命令保存到指定文件中,就只能在文件中看到当前终端执行过的命令,而不是全部历史命令,命令如下:
[root@localhost~]# history -a /root/linux_hb.his2
#使用“-a”选项将当前终端的历史命令保存到指定文件中
[root@localhost~]# cat -n /root/linux_hb.his2
1 cd
2 history -w /root/linux_hb.his
3 cat -n /root/linux_hb.his
4 history -a /root/linux_hb.his2
#查看保存历史命令的文件

可以看到,使用“-a”选项与使用“-w”选项后将所有历史命令保存到文件中的差别非常明显。
[root@localhost~]# touch /root/aa1
[root@localhost~]# touch /root/aa2
[root@localhost~]# touch /root/aa3
#通过创建文件,产生历史命令
[root@localhost~]# history -w
#将历史命令以“-w”选项的方式写入默认历史命令文件
[root@localhost~]# tail -n 5 ~/.bash_history
#查看历史命令文件后 5 行内容
vim ~/.bash_history
touch /root/aa1
touch /root/aa2
touch /root/aa3
history -w
[root@localhost~]#touch /root/bb1
[root@localhost~]#touch /root/bb2
[root@localhost~]#touch /root/bb3
#通过创建文件的方式产生不同的历史命令
[root@localhost~]# history -a
#通过“-a”选项的方式将历史命令写入默认历史命令文件
[root@localhost~]# tail -n 10 ~/.bash_history
#查看历史命令后 10 行内容
vim ~/.bash_history
touch /root/aa1
touch /root/aa2
touch /root/aa3
history -w
tail -n 5 ~/.bash_history
touch /root/bb1
touch /root/bb2
touch /root/bb3
通过上述操作可以看到,在执行“-a”选项或“-w”选项不指定文件时,都表示将当前终端执行过的命令保存到 ~/.bash_history 文件中。

如果需要清空历史命令,那么只需要执行如下命令:
[root@localhost~]# history -c
#清空当前终端产生的历史命令

相关文章