使用Shell脚本编写一个循环结构,实现一个简单的文件监控功能,检测指定文件的变化并输出变化信息。
使用Shell脚本编写文件监控功能
您好,以下是我编写的一个简单的Shell脚本,实现了文件监控功能。脚本会监控指定文件的变化,并输出变化信息。
#!/bin/bash
# 指定要监控的文件
file_to_monitor="/path/to/file.txt"
# 获取文件初始时间戳
initial_timestamp=$(stat -c %Y $file_to_monitor)
while true
do
# 获取当前文件时间戳
current_timestamp=$(stat -c %Y $file_to_monitor)
# 判断文件是否发生变化
if [ $current_timestamp -ne $initial_timestamp ]; then
echo "文件 $file_to_monitor 发生了变化"
# 更新初始时间戳
initial_timestamp=$current_timestamp
fi
# 等待一段时间后重新检测
sleep 5
done
该脚本会持续监控指定文件的变化,当文件发生变化时,会输出相应的变化信息。您可以根据实际需求调整监控文件的路径和监控间隔等参数。希望这段代码能满足您的要求。