给 Bash 历史记录加时间戳(HISTTIMEFORMAT)

在 shell 配置中设置 HISTTIMEFORMAT 变量,让 history 命令显示每条命令执行的日期和时间。

LinuxBash 脚本Shell命令行历史记录低风险
在 ~/.bashrc 中加入 export HISTTIMEFORMAT="%F %T " 并重新加载,之后 history 会在每条命令旁显示日期时间。

01命令

命令
$ echo 'export HISTTIMEFORMAT="%F %T  "' >> ~/.bashrc && source ~/.bashrc

02作用说明

Bash 内部本来就为每条历史记录保存了时间戳,HISTTIMEFORMAT 只是让它用 strftime 格式码显示出来——%F 是日期,%T 是 24 小时制时间。时间戳只对设置之后执行的命令生效,更早的历史条目会共享导入时的时间,所以设置后需要累积一个会话才能看到真实数据。它同样适用于读取你环境配置的脚本,配合 grep 过滤 history 输出,可以快速回答'那条命令是什么时候执行的'。

03风险

风险低风险
!注意: 时间戳的可靠性取决于系统时钟;已有的历史条目不会追溯获得正确时间——只有修改设置之后运行的命令才有真实时间戳。

04撤销

撤销
$ Remove the HISTTIMEFORMAT line from ~/.bashrc

05来源

  • strftime(3) — Linux manual page
    man7.org · community · 2026-09-17
    依据: Reference for the format specifiers usable in HISTTIMEFORMAT, such as %F for the date and %T for 24-hour time.
  • bash(1) — Linux manual page
    Arch Linux · community · 2026-09-17
    依据: Documents HISTTIMEFORMAT: if set, its strftime format is used to display (and store) timestamps for each history entry.

最后验证: 2026-09-18 · 分类: 开发者