温馨提示×

centos如何比较时间戳

小樊
32
2026-09-17 22:14:09
栏目: 智能运维

在 CentOS(本质是 Linux)里,“比较时间戳”通常指比较文件的 mtime/ctime/atime,或者比较日期时间字符串 / 秒级时间戳。下面按常见场景说明。


一、比较文件时间戳(最常用)

1. 用 ls 看时间戳

ls -l file1 file2      # mtime
ls -lu file1 file2     # atime
ls -lc file1 file2     # ctime

2. 用 test / [ ] 比较文件新旧

if [ file1 -nt file2 ]; then
  echo "file1 比 file2 新"
fi

if [ file1 -ot file2 ]; then
  echo "file1 比 file2 旧"
fi

if [ file1 -ef file2 ]; then
  echo "是同一个文件"
fi
  • -nt:newer than
  • -ot:older than

3. 用 find 按时间戳筛选

# 修改时间在 1 天以内
find /path -mtime -1

# 修改时间在 1 天以前
find /path -mtime +1

# 30 分钟以内修改过
find /path -mmin -30

二、比较“秒级时间戳”(epoch)

1. 获取当前时间戳

date +%s

2. 获取文件时间戳(秒)

stat -c %Y file

3. 在脚本中比较

t1=$(stat -c %Y file1)
t2=$(stat -c %Y file2)

if [ "$t1" -gt "$t2" ]; then
  echo "file1 更新"
fi

三、比较日期时间字符串

1. 转成时间戳再比

t1=$(date -d "2024-01-01 10:00:00" +%s)
t2=$(date -d "2024-01-02 10:00:00" +%s)

if [ "$t1" -lt "$t2" ]; then
  echo "t1 更早"
fi

2. 直接字符串比较(仅限固定格式)

if [[ "2024-01-02" > "2024-01-01" ]]; then
  echo "前面更大"
fi

⚠️ 仅适用于 YYYY-MM-DD HH:MM:SS 这种字典序相等的格式。


四、实用示例:找出比某文件旧的文件

find /data -type f ! -newer reference.txt

如果你能说明:

  • 是比较 文件时间戳 还是 日志里的时间
  • Shell 脚本 还是 命令行临时用

我可以给你更精确的写法。

0