Linux 系统 history 命令详解

  history 命令在 Linux 系统中可以说是为我们提供了很大的便利,详细了解其用法可以有效提高工作效率。
  在默认环境下,系统(以Centos 6.2为例)中默认 history 命令执行的效果是:

  983  ls
  984  cat iptables 
  985  ifconfig
  986  mysql -u root -p
  987  ssh root@192.168.0.51
  988  df -h
  989  history

  以上是截取的部分结果,下面来详细说说其用法:


  1.命令的用法及参数usage: history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]
  参数:
  n :数字,要列出最近的若干命令列表
  -c :将目前的 shell 中的所有 history 内容全部消除
  -a :将目前新增的 history 指令新增入 histfiles 中,若没有加 histfiles ,则预设写入 ~/.bash_history
  -r :将 histfiles 的内容读到目前这个 shell 的 history 记忆中
  -w :将目前的 history 记忆内容写入 histfiles

  重复以前的指令:

[root@keystone ~]# history 10 # 列出最后10条执行的命令
[root@keystone ~]# !988 # 执行第988条指令
[root@keystone ~]# !! # 执行最后一条指令
[root@keystone ~]# history -c # 清除所有的指令记录

  history 命令的用途确实很大,但需要小心安全的问题,尤其是 root 的历史纪录档案,因为这将很多的重要资料在执行的过程中会被纪录在 ~/.bash_history 当中,需要使用过程中恰当的管理。


  2.使用 HISTTIMEFORMAT 显示时间戳在 /etc/bashrc 中编辑:

export HISTTIMEFORMAT='%F %T '
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S  `whoami`  " # 这将显示执行命令的用户

  这个功能只能用在当 HISTTIMEFORMAT 这个环境变量被设置之后,之后的那些新执行的 bash 命令才会被打上正确的时间戳。在此之前的所有命令,都将会显示成设置 HISTTIMEFORMAT 变量的时间。


  3.使用 HISTSIZE 控制历史命令记录的总行数

  在 /etc/bashrc 中编辑:

export HISTSIZE=100 # history 命令的记录数量。The number of commands to remember in the command history. The default value is 500.
export HISTFILESIZE=100 # 记录文件的行数。The maximum number of lines contained in the history file. When this variable is assigned a value, the his-tory file is truncated, if necessary, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file  is also truncated to this size after writing it when an interactive shell exits.

  如果你想禁用 history,可以将 HISTSIZE 设置为 0。


  4.使用 HISTFILE 更改历史文件名称

  默认情况下,命令历史存储在 ~/.bash_history 文件中。
  在 /etc/bashrc 中编辑:

export HISTFILE=/var/log/command_history

  5.使用 HISTCONTROL 从命令历史中剔除连续重复的条目


  在 /etc/bashrc 中编辑:

export HISTCONTROL=ignoredups # ignoredups 只能剔除连续的重复条目。要清除整个命令历史中的重复条目,可以将 HISTCONTROL 设置成 erasedups
export HISTCONTROL=erasedups


  6.使用 HISTCONTROL 强制 history 不记住特定的命令

  在 /etc/bashrc 中编辑:

export HISTIGNORE='ls' # A colon-separated list of patterns used to decide which command lines should be saved on the history list.Each pattern is anchored at the beginning  of the line and must match the complete line 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值