5. 历史相关环境变量
使用 HISTTIMEFORMAT
显示时间戳
通常,当您从命令行键入history
,它只会显示命令。 出于审核目的,将时间戳与命令一起显示可能会有所帮助,如下所示。
$ export HISTTIMEFORMAT='%F %T '
$ history | more
1 2011-08-06 19:02:39 service network restart
2 2011-08-06 19:02:39 exit
3 2011-08-06 19:02:39 id
4 2011-08-06 19:02:39 cat /etc/redhat-release
使用 HISTSIZE
控制历史记录大小
您可以使用
HISTSIZE
控制历史记录中的总行数。 将以下两行附加到.bash_profile
并再次重新登录 bash shell 以查看更改。
在此示例中,bash 历史记录中将仅存储 450 个命令。
$ vi ~/.bash_profile
HISTSIZE=450
HISTFILESIZE=450
如果您想完全禁用历史记录,请将
HISTSIZE
设置为 0,如下所示,bash 将不会记住您键入的任何命令。
$ export HISTSIZE=0
$ history
$ [Note that 'history' did not display anything]
使用 HISTFILE
更改历史文件名
默认情况下,历史记录存储在~/.bash_history
文件中。 将以下行添加到.bash_profile
并重新登录到 bash shell,以将历史命令存储在.mycommands
文件而不是.bash_history
文件中。
当您想要使用不同的历史文件名跟踪从不同终端执行的命令时,这会很有帮助。
$ vi ~/.bash_profile
HISTFILE=/root/.mycommands
使用 HISTCONTROL
HISTCONTROL
支持以下几种设置
ignoredups
erasedups
ignorespace
ignoredups
消除连续重复的历史条目
在以下示例中,pwd
命令被执行了三次。 可以看到历史记录中连续出现3次pwd
命令:
$ pwd
$ pwd
$ pwd
$ history | tail -4
44 pwd
45 pwd
46 pwd
[Note that there are three 'pwd' commands in history, after executing 'pwd' 3 times as shown above]
47 history | tail -4
58 history | tail -4
要消除此类重复项,请将
HISTCONTROL
设置为 ignoredups
,如下所示。
在此示例中,即使在执行pwd
之后,历史记录中也只有一个pwd
命令。
$ export HISTCONTROL=ignoredups
$ pwd
$ pwd
$ pwd
$ history | tail -3
56 export HISTCONTROL=ignoredups
57 pwd
erasedups
删除整个历史记录中的重复项
上述的 ignoredups
控件仅当重复命令是连续命令时才会删除它们。
要消除整个历史记录中的重复项,请设置
HISTCONTROL
标志 erasedups
。
erasedups
用法示例:
$ export HISTCONTROL=erasedups
$ pwd
$ service httpd stop
$ history | tail -3
38 pwd
39 service httpd stop
40 history | tail -3
$ ls -ltr
$ service httpd stop
$ history | tail -6
35 export HISTCONTROL=erasedups
36 pwd
37 history | tail -3
38 ls -ltr
39 service httpd stop
[Note that the previous 'service httpd stop' after 'pwd' got erased]
40 history | tail -6
ignorespace
强制历史记录不记住命令
您可以通过设置
HISTCONTROL
标志 ignorespace
来指示历史记录忽略某些命令。
然后在您希望从历史记录中删除的任何命令前面键入一个空格,如下所示。
$ export HISTCONTROL=ignorespace
$ ls -ltr
$ pwd
$ service httpd stop [Note that there is a space at the beginning of 'service', to ignore this command from history]
$ history | tail -3
67 ls -ltr
68 pwd
69 history | tail -3
ignorespace
感到兴奋,因为他们可以从历史记录中隐藏命令。 了解忽 ignorespace
的工作原理是很好的,但作为最佳实践,不要故意向历史隐藏任何内容。
使用 HISTIGNORE
忽略历史记录中的特定命令
有时您可能不想使用pwd
和ls
等基本命令来混乱您的历史记录。
使用
HISTIGNORE
指定要从历史记录中忽略的所有命令。可以在
HISTIGNORE
中通过用冒号(:
)分隔来指定多个命令。
请注意,示例中ls
和ls –ltr
均添加到
HISTIGNORE
中。 您必须提供要忽略的确切命令行。
$ export HISTIGNORE="pwd:ls:ls -ltr:"
$ pwd
$ ls
$ ls -ltr
$ service httpd stop
$ history | tail -3
79 export HISTIGNORE="pwd:ls:ls -ltr:"
80 service httpd stop
81 history
[Note that history did not record 'pwd', 'ls' and 'ls -ltr']