带有日期和时间的 Linux 命令历史记录

问题描述 投票:0回答:8

我想检查我的 Linux 系统何时触发了哪个命令 - 在哪个日期和时间。

我发出了这样的命令:

history 50 

它向我显示了最近 50 个命令的历史记录,但不显示它被触发的日期和时间。有谁知道怎么做吗?

linux history
8个回答
84
投票

关于此链接,您可以通过执行以下命令使krzyk提供的第一个解决方案永久化:

echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile
source ~/.bash_profile

54
投票

试试这个:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

当然,您可以根据自己的喜好调整格式。


41
投票

如果您使用 zsh,您可以使用

-E
-i
开关:

history -E

如果您执行

man zshoptions
man zshbuiltins
,您可以找到有关这些开关的更多信息以及与历史相关的其他信息:

Also when listing,
 -d     prints timestamps for each event
 -f     prints full time-date stamps in the US `MM/DD/YY hh:mm' format
 -E     prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
 -i     prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
 -t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions  described  for  the  %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1).  The resulting formatted string must be no more than 256 characters or will not be printed
 -D     prints elapsed times; may be combined with one of the options above

6
投票

这取决于标准 bash 中的 shell(及其配置),仅存储命令而不存储日期和时间(检查

.bash_history
是否有任何时间戳)。

要让 bash 存储时间戳,您需要在执行命令之前设置

HISTTIMEFORMAT
,例如在 .bashrc
.bash_profile
。这将导致 bash 将时间戳存储在 
.bash_history
 中(请参阅以 
#
 开头的条目)。


5
投票
HISTTIMEFORMAT="%d/%m/%y %H:%M "

对于在此之前键入的任何命令,这都没有帮助,因为它们只会获得您打开历史记录的默认时间,但它将记录此后任何其他命令的时间。

如果您希望它永久记录历史记录,您应该输入以下内容 在你的

~/.bashrc

 中划线

export HISTTIMEFORMAT="%d/%m/%y %H:%M "
    

3
投票
这取决于您使用的外壳。对于 GNU Bash,更改 HISTTIMEFORMAT 变量会有帮助。

这篇 nixCraft 文章 解释了如何永久设置该变量,但使用了不明确的日期格式。对于 ISO 8601,请使用:

HISTTIMEFORMAT="%G-%m-%dT%T "
结果:

$ history [...] 13 2022-11-07T13:32:01 pwd 14 2022-11-07T13:32:05 cd 15 2022-11-07T13:32:10 ls -l
    

1
投票
在 macOS 上,无需编辑任何

rc

 文件:

history -t"%F %T"
    

0
投票
用两个简单的命令解决:

export HISTTIMEFORMAT='%F %T' history
与每个历史记录条目相关的日期和时间可以写入历史文件,通过设置 HISTTIMEFORMAT 变量用历史注释字符进行标记。

© www.soinside.com 2019 - 2024. All rights reserved.