可以编写一个BASH脚本,使用tail命令实时监测日志文件,并使用grep命令匹配关键字。脚本使用while循环持续监测日志文件,直到达到指定时间(30分钟)后退出。
以下是一个示例脚本:
#!/bin/bash
# Set the keyword you want to look for in the log file
keyword="error"
# Set the time in seconds to keep looking for the keyword in the log file
time_to_run=1800 # 30 minutes
# Set the log file you want to scan
logfile="/var/log/test.log"
# Start time
start_time=$(date +%s)
# Loop until the time to run has elapsed
while [ $(( $(date +%s) - $start_time )) -lt $time_to_run ]
do
# Use tail command to monitor the log file and grep for the keyword
tail -n0 -f $logfile | grep -q $keyword
# Check if the keyword has been found. If it has, exit the loop
if [ $? -eq 0 ]; then
echo "Keyword found. Stopping script."
break
fi
done
echo "Script has finished running."
使用方法:
chmod +x scan_log_file.sh
./scan_log_file.sh