在Linux系统中,每个文件都有三种时间戳记录,了解这些时间戳对于系统管理、故障排查和文件恢复都非常重要。下面详细介绍Linux文件时间相关的查看技巧。
修改时间 (mtime, Modification Time)
ls -l
命令默认显示的就是这个时间访问时间 (atime, Access Time)
ls -lu
命令查看变更时间 (ctime, Change Time)
ls -lc
命令查看ls
命令# 查看修改时间(mtime)
ls -l filename
ls --time=mtime filename
# 查看访问时间(atime)
ls -lu filename
ls --time=atime filename
# 查看变更时间(ctime)
ls -lc filename
ls --time=ctime filename
stat
命令(最详细)stat filename
输出示例:
File: filename
Size: 4096 Blocks: 8 IO Block: 4096 regular file
Device: 802h/2050d Inode: 262145 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ user) Gid: ( 1000/ user)
Access: 2023-04-15 09:30:25.000000000 +0800 # atime
Modify: 2023-04-10 14:15:30.000000000 +0800 # mtime
Change: 2023-04-10 14:20:45.000000000 +0800 # ctime
Birth: 2023-04-01 10:00:00.000000000 +0800 # 有些系统支持创建时间(birth time)
find
命令查找特定时间的文件# 查找7天内修改过的文件
find /path -type f -mtime -7
# 查找30天前访问过的文件
find /path -type f -atime +30
# 查找24小时内变更过的文件
find /path -type f -ctime -1
如果需要将时间戳转换为可读格式,可以使用date
命令:
date -d @$(stat -c %Y filename) +"%Y-%m-%d %H:%M:%S"
ls
命令显示的时间格式受TIME_STYLE
环境变量影响:
# 设置为长格式(默认)
export TIME_STYLE=long-iso
# 设置为完整格式
export TIME_STYLE=full-iso
# 设置为locale格式
export TIME_STYLE=locale
查看目录的时间戳:
stat .
批量查看多个文件时间:
stat file1 file2 file3
只显示特定时间戳:
stat -c %y filename # 只显示mtime
stat -c %x filename # 只显示atime
stat -c %z filename # 只显示ctime
比较文件新旧:
[ file1 -nt file2 ] && echo "file1 is newer than file2"
[ file1 -ot file2 ] && echo "file1 is older than file2"
掌握这些文件时间查看技巧,可以帮助你更有效地管理系统文件、排查问题和进行数据分析。