温馨提示×

centos如何对比时间戳

小樊
52
2026-09-05 21:33:23
栏目: 智能运维

在 CentOS(或一般 Linux 系统)中,“对比时间戳”通常有几种常见场景。下面按常见用法给你说明:


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

1. 查看文件时间戳

ls -l filename
  • 显示的是 修改时间(mtime)

更详细:

stat filename

会显示:

  • Access time (atime)
  • Modify time (mtime)
  • Change time (ctime)

2. 比较两个文件哪个更新

if [ file1 -nt file2 ]; then
    echo "file1 比 file2 新"
else
    echo "file1 不比 file2 新"
fi
  • -nt:newer than
  • -ot:older than

二、对比时间戳字符串(如日志时间)

1. 将时间转为时间戳后比较

date -d "2024-01-01 12:00:00" +%s

示例:

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

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

三、对比当前时间与某个时间戳

now=$(date +%s)
target=$(date -d "2024-12-31 23:59:59" +%s)

if [ $now -lt $target ]; then
    echo "还没到目标时间"
fi

四、查找比某时间更新的文件

find /path -type f -newermt "2024-01-01"

或比某个文件新:

find /path -type f -newer oldfile

五、脚本中常见写法示例

#!/bin/bash

file1=m1.txt
file2=m2.txt

if [ "$file1" -nt "$file2" ]; then
    echo "$file1 更新"
else
    echo "$file2 更新"
fi

如果你指的是:

  • ✅ 对比 日志里的时间
  • ✅ 对比 数据库时间戳
  • ✅ 对比 容器内时间
  • ✅ 用 Python / Shell 对比

可以告诉我具体场景,我可以给你更精确的示例。

0 踩