1、时间新
在 Shell 脚本中, -nt
运算符用于比较两个文件的修改时间,判断哪个文件更新。它用于检查某个文件是否比另一个文件更新。
如果 -nt
运算符返回 true
,则表示第一个文件比第二个文件更新。如果返回 false
,则表示第一个文件不比第二个文件更新,或者两个文件的修改时间相同。
if [ "/data/file1" -nt "/data/file2" ]; then
echo "file1 is newer than file2"
else
echo "file1 is not newer than file2"
fi
在上述脚本中,使用了 -nt
运算符来比较 /data/file1
和 /data/file2
两个文件的修改时间。根据比较结果,脚本会打印相应的消息。
2、内容新
如果想判断文件是否以内容为基准更新,而不仅仅是判断修改时间,可以使用校验和或差异比较工具,例如 md5sum
或 diff
命令来比较文件内容。这些命令可以生成文件的校验和或比较文件之间的差异,从而判断哪个文件具有更新的内容。
# 使用 md5sum 比较两个文件的内容
if [ "$(md5sum /data/file1)" != "$(md5sum /data/file2)" ]; then
echo "file1 has different content than file2"
else
echo "file1 has the same content as file2"
fi
# 使用 diff 比较两个文件的内容
if ! diff -q /data/file1 /data/file2 >/dev/null; then
echo "file1 has different content than file2"
else
echo "file1 has the same content as file2"
fi
在上述示例中,使用了 md5sum
命令和 diff
命令来比较文件的内容。根据比较结果,脚本会打印相应的消息。请注意,这种方法比较的是文件内容,而不是修改时间。