求助:编写脚本判断两个文件的新旧关系
没问题!我来帮你搞定这个脚本需求~不管是用bash还是Python,我都给你写好带注释的版本,逻辑清晰,你直接就能用。
Bash脚本实现文件新旧比较
这是最适合Linux/Unix环境的脚本,轻量且无需额外依赖:
#!/bin/bash # 提示用户输入两个文件名 read -p "请输入第一个文件名: " file1 read -p "请输入第二个文件名: " file2 # 定义复用的文件验证函数 validate_file() { local filename=$1 # 检查文件是否存在 if [ ! -e "$filename" ]; then echo "错误:文件 '$filename' 不存在!" return 1 # 检查是否为常规文件(排除目录、设备文件等) elif [ ! -f "$filename" ]; then echo "错误:'$filename' 不是常规文件!" return 1 fi return 0 } # 先验证第一个文件,不通过就退出 if ! validate_file "$file1"; then exit 1 fi # 再验证第二个文件 if ! validate_file "$file2"; then exit 1 fi # 获取文件的修改时间戳(秒数,便于数值比较) mtime1=$(stat -c "%Y" "$file1") mtime2=$(stat -c "%Y" "$file2") # 比较时间戳,判断文件新旧 if [ "$mtime1" -lt "$mtime2" ]; then echo "文件 '$file1' 比 '$file2' 更旧。" elif [ "$mtime1" -gt "$mtime2" ]; then echo "文件 '$file2' 比 '$file1' 更旧。" else echo "两个文件的修改时间一致,$file1 和 $file2 一样旧。" fi
使用说明:
- 把上面的代码保存为
compare_files.sh - 给脚本添加执行权限:
chmod +x compare_files.sh - 运行脚本:
./compare_files.sh
可选:Python版本脚本
如果你更熟悉Python,这个跨平台版本也能完美实现需求:
import os import time def validate_file(filename): # 检查文件是否存在 if not os.path.exists(filename): print(f"错误:文件 '{filename}' 不存在!") return False # 检查是否为常规文件 if not os.path.isfile(filename): print(f"错误:'{filename}' 不是常规文件!") return False return True # 获取用户输入的两个文件名 file1 = input("请输入第一个文件名: ") file2 = input("请输入第二个文件名: ") # 验证文件合法性,不通过则退出程序 if not validate_file(file1): exit(1) if not validate_file(file2): exit(1) # 获取文件的修改时间(秒级时间戳) mtime1 = os.path.getmtime(file1) mtime2 = os.path.getmtime(file2) # 比较并输出结果 if mtime1 < mtime2: print(f"文件 '{file1}' 比 '{file2}' 更旧。") elif mtime1 > mtime2: print(f"文件 '{file2}' 比 '{file1}' 更旧。") else: print(f"两个文件的修改时间一致,{file1} 和 {file2} 一样旧。")
使用说明:
- 保存为
compare_files.py - 直接运行:
python3 compare_files.py
内容的提问来源于stack exchange,提问作者andrew16
相关产品推荐
相关产品推荐

