概览
大多数 shell 在默认运行 history 时不会显示时间戳。排查问题、审计操作或弄清命令何时执行时,时间信息却很重要。本文介绍如何在不同平台和 shell 中启用并查看带完整日期和时间的命令历史。
Unix/Linux 与 macOS
Zsh(现代 macOS 的默认 shell)
快速查看当前会话
如果已经启用 EXTENDED_HISTORY,使用以下命令查看带时间戳的历史:
# Display history with ISO8601 timestamp format (yyyy-mm-dd hh:mm)
history -i 1
# Or use European format (dd.mm.yyyy hh:mm)
history -E 1
输出示例:
2025-12-22 10:23 ls -la
2025-12-22 10:24 cd ~/Documents
2025-12-22 10:25 git status
永久配置
要为以后的会话启用时间戳:
第一步:编辑 Zsh 配置文件
nano ~/.zshrc
第二步:添加下面这行
setopt EXTENDED_HISTORY
可选:其他历史记录设置
# Enable extended history with timestamps
setopt EXTENDED_HISTORY
# Share history across all terminal sessions
setopt SHARE_HISTORY
# Append to history file immediately, not on shell exit
setopt INC_APPEND_HISTORY
# Don't record duplicate commands
setopt HIST_IGNORE_DUPS
# Remove older duplicate entries from history
setopt HIST_IGNORE_ALL_DUPS
# Increase history size
HISTSIZE=10000
SAVEHIST=10000
HISTFILE=~/.zsh_history
第三步:应用改动
source ~/.zshrc
第四步:查看带时间戳的历史
# View all history with timestamps
history -i 1
# View last 20 commands with timestamps
history -i -20
# Search history with timestamps
history -i 1 | grep "git"
理解 Zsh 历史文件格式
启用 EXTENDED_HISTORY 后,~/.zsh_history 以 Unix 时间戳格式保存时间:
cat ~/.zsh_history
内容示例:
: 1703251415:0;ls -la
: 1703251430:0;cd ~/Documents
: 1703251445:0;git status
格式为 : <epoch_timestamp>:<duration>;<command>,分别表示时间戳、耗时和命令。
Bash(Linux 和较早版本的 macOS)
快速查看当前会话
# Set the timestamp format temporarily
export HISTTIMEFORMAT="%F %T "
# View history with timestamps
history
输出示例:
1 2025-12-22 10:23:15 ls -la
2 2025-12-22 10:24:30 cd ~/Documents
3 2025-12-22 10:25:45 git status
永久配置
第一步:编辑 Bash 配置文件
# For interactive non-login shells
nano ~/.bashrc
# For login shells (macOS typically uses this)
nano ~/.bash_profile
第二步:添加以下几行
# Set timestamp format: YYYY-MM-DD HH:MM:SS
export HISTTIMEFORMAT="%F %T "
# Increase history size
export HISTSIZE=10000
export HISTFILESIZE=20000
# Avoid duplicate entries
export HISTCONTROL=ignoredups:erasedups
# Append to history file, don't overwrite
shopt -s histappend
# Save multi-line commands as one entry
shopt -s cmdhist
第三步:应用改动
source ~/.bashrc
# Or: source ~/.bash_profile
第四步:查看历史
# View all history
history
# View last 20 commands
history 20
# Search history
history | grep "git"
理解 Bash 历史文件格式
设置 HISTTIMEFORMAT 后,~/.bash_history 会把时间戳单独存成一行:
cat ~/.bash_history
内容示例:
#1703251415
ls -la
#1703251430
cd ~/Documents
#1703251445
git status
格式是以 # 开头的一行,后面跟 Unix 时间戳,下一行是命令。
HISTTIMEFORMAT 格式代码
可以用以下代码自定义时间戳格式:
| 代码 | 说明 | 示例 |
|---|---|---|
%F | 完整日期 (YYYY-MM-DD) | 2025-12-22 |
%T | 完整时间 (HH:MM:SS) | 14:30:15 |
%D | 短日期 (MM/DD/YY) | 12/22/25 |
%Y | 年份(四位数字) | 2025 |
%m | 月 (01-12) | 12 |
%d | 月内第几天 (01-31) | 22 |
%H | 小时 (00-23) | 14 |
%M | 分钟 (00-59) | 30 |
%S | 秒 (00-59) | 15 |
%s | Unix 时间戳 | 1703251415 |
示例:
# US format: MM/DD/YY HH:MM:SS AM/PM
export HISTTIMEFORMAT="%m/%d/%y %I:%M:%S %p "
# European format: DD-MM-YYYY HH:MM
export HISTTIMEFORMAT="%d-%m-%Y %H:%M "
# ISO 8601 format: YYYY-MM-DDTHH:MM:SS
export HISTTIMEFORMAT="%FT%T "
# Simple: YYYY-MM-DD HH:MM
export HISTTIMEFORMAT="%F %R "
Windows
PowerShell
PowerShell 内置了带时间戳的命令历史,但默认视图不显示时间。
查看带时间戳的历史(仅当前会话)
PowerShell 的 Get-History cmdlet 包含时间信息:
# View history with execution time
Get-History
# View with custom format including timestamp
Get-History | Format-Table -Property Id,
@{Label="StartTime";Expression={$_.StartExecutionTime}},
CommandLine -AutoSize
# View last 10 commands with timestamps
Get-History -Count 10 | Format-Table Id, StartExecutionTime, CommandLine -AutoSize
输出示例:
Id StartExecutionTime CommandLine
-- ------------------ -----------
1 12/22/2025 2:30:15 PM ls
2 12/22/2025 2:31:42 PM cd Documents
3 12/22/2025 2:32:10 PM git status
增强版历史查询函数
把这个函数加入 PowerShell 配置文件,以便随时调用:
第一步:打开 PowerShell 配置文件
# Check if profile exists
Test-Path $PROFILE
# Create if it doesn't exist
if (!(Test-Path $PROFILE)) {
New-Item -Path $PROFILE -ItemType File -Force
}
# Edit the profile
notepad $PROFILE
第二步:添加函数
function Get-HistoryWithTime {
param(
[int]$Count = 50
)
Get-History -Count $Count | Format-Table -Property Id,
@{Label="Date";Expression={$_.StartExecutionTime.ToString("yyyy-MM-dd")}},
@{Label="Time";Expression={$_.StartExecutionTime.ToString("HH:mm:ss")}},
@{Label="Duration";Expression={$_.EndExecutionTime - $_.StartExecutionTime}},
CommandLine -AutoSize
}
# Create an alias
Set-Alias -Name hh -Value Get-HistoryWithTime
第三步:重新加载配置文件
. $PROFILE
第四步:使用函数
# View last 50 commands with timestamps
hh
# View last 20 commands
hh -Count 20
输出示例:
Id Date Time Duration CommandLine
-- ---- ---- -------- -----------
1 2025-12-22 14:30:15 00:00:00.1234567 ls
2 2025-12-22 14:31:42 00:00:00.0987654 cd Documents
3 2025-12-22 14:32:10 00:00:01.5432109 git status
使用 PSReadLine 跨会话保存历史
PowerShell 5.0 及更高版本包含 PSReadLine 模块,可以跨会话保存命令历史:
# View persistent history file location
(Get-PSReadLineOption).HistorySavePath
# Typical location:
# C:\Users\<username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
# View the content
Get-Content (Get-PSReadLineOption).HistorySavePath
# Search persistent history
Get-Content (Get-PSReadLineOption).HistorySavePath | Select-String "git"
注意: PSReadLine 的历史文件默认没有时间戳。Get-History 显示的是当前会话中的时间。
导出带时间戳的历史
# Export to CSV
Get-History | Select-Object Id,
@{Name="DateTime";Expression={$_.StartExecutionTime}},
CommandLine | Export-Csv -Path "~/history.csv" -NoTypeInformation
# Export to JSON
Get-History | Select-Object Id, StartExecutionTime, EndExecutionTime, CommandLine |
ConvertTo-Json | Out-File "~/history.json"
CMD(命令提示符)
传统 Windows 命令提示符(cmd.exe)原生不支持命令历史时间戳。可以使用 doskey 查看当前会话的命令历史:
doskey /history
限制:
- 没有时间戳。
- 不能跨会话保留历史。
- 仅限当前 cmd.exe 窗口。
替代方法: 需要更好地管理带时间戳的历史时,可以使用 PowerShell。
对照表
| Shell | 平台 | 时间戳支持 | 配置文件 | 查看命令 |
|---|---|---|---|---|
| Zsh | macOS, Linux | ✅ 支持(需 EXTENDED_HISTORY) | ~/.zshrc | history -i 1 |
| Bash | Linux, macOS, WSL | ✅ 支持(需 HISTTIMEFORMAT) | ~/.bashrc 或 ~/.bash_profile | history |
| PowerShell | Windows, macOS, Linux | ✅ 支持(内置) | $PROFILE | Get-History |
| CMD | Windows | ❌ 不支持 | 不适用 | doskey /history |
重要限制
⚠️ 启用时间戳以前执行的命令,不会因此获得准确的时间戳。
- Zsh:旧命令可能显示纪元日期(1970-01-01)。
- Bash:旧命令可能显示启用
HISTTIMEFORMAT时的时间。 - PowerShell:除非使用 PSReadLine,否则只跟踪当前会话。
只有配置更改之后输入的新命令才会有正确时间戳。
进阶技巧
按日期范围搜索历史(Bash)
# View history from a specific time range
history | awk '$2 >= "2025-12-22" && $2 <= "2025-12-23"'
导出带时间戳的 Bash 历史
# Export to file
HISTTIMEFORMAT="%F %T " history > ~/command_history.txt
# Export as CSV
echo "Timestamp,Command" > ~/history.csv
HISTTIMEFORMAT='"%F %T",' history | sed 's/^ *[0-9]* *//' >> ~/history.csv
跨平台历史查询脚本
团队成员使用不同平台时,可以考虑统一采用以下方式:
# Add to ~/.bashrc, ~/.zshrc, or $PROFILE
alias h='history_with_time'
# Bash/Zsh version
history_with_time() {
if [ -n "$ZSH_VERSION" ]; then
history -i 1 | tail -${1:-50}
else
HISTTIMEFORMAT="%F %T " history ${1:-50}
fi
}
安全注意事项
- 历史文件中可能有敏感信息,例如密码和 API 密钥。
- 切勿将历史文件提交到版本控制。
- Bash 中用
HISTCONTROL=ignorespace排除以空格开头的命令。 - 从历史中清除敏感命令:
# Bash: Remove specific line
history -d <line_number>
# Bash: Clear all history
history -c
# Zsh: Edit history file directly
nano ~/.zsh_history
# PowerShell: Clear current session
Clear-History
故障排查
不显示时间戳
问题: 配置后运行历史命令仍不显示时间戳。
解决方法:
-
重新加载配置:
# Bash source ~/.bashrc # Zsh source ~/.zshrc # PowerShell . $PROFILE -
打开新的终端窗口或标签页
-
确认配置已保存:
# Bash grep HISTTIMEFORMAT ~/.bashrc # Zsh grep EXTENDED_HISTORY ~/.zshrc -
检查是否已设置变量:
# Bash echo $HISTTIMEFORMAT # Zsh setopt | grep EXTENDED_HISTORY
历史未跨会话保存
问题: 关闭终端后历史丢失。
解决方法:
Bash:
# Ensure these settings are in ~/.bashrc
shopt -s histappend
export HISTSIZE=10000
export HISTFILESIZE=20000
Zsh:
# Ensure these settings are in ~/.zshrc
setopt APPEND_HISTORY
setopt INC_APPEND_HISTORY
SAVEHIST=10000
PowerShell:
# Install/update PSReadLine module
Install-Module PSReadLine -Force
相关阅读
参考资料
- Zsh Documentation. (2025). Options - 16.2.4 History. 检索于 2025 年 12 月 22 日,来源: https://zsh.sourceforge.io/Doc/Release/Options.html
- GNU Bash Manual. (2025). Bash History Facilities. 检索于 2025 年 12 月 22 日,来源: https://www.gnu.org/software/bash/manual/html_node/Bash-History-Facilities.html
- Microsoft PowerShell Documentation. (2025). about_History. 检索于 2025 年 12 月 22 日,来源: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_history
- PowerShell Gallery. (2025). PSReadLine Module. 检索于 2025 年 12 月 22 日,来源: https://www.powershellgallery.com/packages/PSReadLine