Linux History

2020-03-13

我们经常在日常工作中使用 history 命令来检查命令的历史或获取用户执行的命令的信息。 在这篇文章中,我们将看到如何有效地使用history命令来提取用户在Bash shell中执行的命令。 这对于审计目的或找出在什么日期和时间执行什么命令可能是有用的。

默认情况下执行历史命令时不会看到日期和时间戳。 但是,bash shell 提供了用于编辑用户命令历史记录的CLI工具。 让我们看看 history 命令的一些方便的技巧。


在Linux中列出最近 / 所有执行的命令

在终端执行简单的history命令会显示一个最近执行的命令列表和行号。

[narad@tecmint ~]$ history
1  PS1='\e[1;35m[\u@\h \w]\$ \e[m '
2  PS1="\e[0;32m[\u@\h \W]\$ \e[m "
3  PS1="\u@\h:\w [\j]\$ "
4  ping google.com
5  echo $PS1
6   tail -f /var/log/messages
7  tail -f /var/log/messages
8  exit
9  clear
10  history
11  clear
12  history

列出所有最近执行的命令并带日期和时间戳

如何查找命令的日期和时间戳? 使用export命令将在命令执行时显示具有相应时间戳的历史命令。

[narad@tecmint ~]$ export HISTTIMEFORMAT='%F %T  '
1  2013-06-09 10:40:12   cat /etc/issue
2  2013-06-09 10:40:12   clear
3  2013-06-09 10:40:12   find /etc -name *.conf
4  2013-06-09 10:40:12   clear
5  2013-06-09 10:40:12   history
6  2013-06-09 10:40:12   PS1='\e[1;35m[\u@\h \w]\$ \e[m '
7  2013-06-09 10:40:12   PS1="\e[0;32m[\u@\h \W]\$ \e[m "
8  2013-06-09 10:40:12   PS1="\u@\h:\w [\j]\$ "
9  2013-06-09 10:40:12   ping google.com
10  2013-06-09 10:40:12   echo $PS1

HISTTIMEFORMAT 变量的含义

%F Equivalent to %Y - %m - %d
%T Replaced by the time ( %H : %M : %S 

History 中的筛选机制

正如我们在上面的输出中可以看到相同的命令正在重复多次。 如何筛选历史中的简单或非破坏性命令? 通过在HISTIGNORE ='ls -l:pwd:date:'中指定命令,使用以下export命令不会被系统保存,也不会显示在历史命令中。

[narad@tecmint ~]$ export HISTIGNORE='ls -l:pwd:date:

忽略 History 记录中的重复命令

使用下面的命令将帮助我们忽略用户所做的重复命令输入。 如果用户在Bash提示中多次执行相同的命令,则只有单个条目才会显示在历史记录中。

[narad@tecmint ~]$ export HISTCONTROL=ignoredups

使用 unset 取消环境变量设置

取消环境变量设置。 通过export命令设置的环境变量,可以通 ubset 逐个取消。

[narad@tecmint ~]$ unset export HISTCONTROL

让 export 设置的环境变量持久化

[narad@tecmint ~]$ vi .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
export HISTCONTROL=ignoredups
PATH=$PATH:$HOME/bin
export PATH