基于Shell脚本的多时段定时文件检测需求实现咨询
Hey there! Let's tackle this scheduled file-checking task step by step. Here's how you can make it work perfectly with your existing script and the email notification snippet you provided:
1. Upgrade Your Check_File.sh Script
Your current script only checks once, so we need to modify it to loop every 5 minutes within the specified time window, stop as soon as the file is found, and send an email notification either way. Here's the updated version:
#!/bin/bash # Validate input arguments if [ $# -ne 3 ]; then echo "Usage: $0 <filename> <start_time> <end_time>" exit 1 fi FILENAME="/home/test/$1" START_WINDOW=$2 END_WINDOW=$3 SUBJECT="File Check Alert" RECIPIENT="somebody@somewhere.com" MESSAGE="" # Loop to check file existence until window ends or file is found while true; do CURRENT_TIME=$(date +"%H:%M") # Exit loop if we've passed the end of the time window if [[ "$CURRENT_TIME" > "$END_WINDOW" ]]; then MESSAGE="⚠️ File '$FILENAME' was NOT detected between $START_WINDOW and $END_WINDOW" break fi # Check if file exists if [ -f "$FILENAME" ]; then MESSAGE="✅ File '$FILENAME' was found at $CURRENT_TIME (within $START_WINDOW-$END_WINDOW)" break fi # Wait 5 minutes before next check sleep 300 done # Send notification email echo "$MESSAGE" | mail -s "$SUBJECT" "$RECIPIENT"
Don't forget to make the script executable:
chmod +x /path/to/Check_File.sh
2. Set Up Crontab Scheduled Tasks
We'll use crontab to trigger the script at the start of each time window. Each task will kick off the script, which handles the 5-minute checks and stops automatically when the window closes or the file is found.
Edit your crontab with crontab -e, then add these lines (replace /path/to/ with the actual path to your script):
# Check file1 between 9:00-9:30 (starts at 9:00) 0 9 * * * /path/to/Check_File.sh file1 "09:00" "09:30" # Check file3 between 10:00-10:30 (starts at 10:00) 0 10 * * * /path/to/Check_File.sh file3 "10:00" "10:30" # Check file2 between 11:00-11:30 (starts at 11:00) 0 11 * * * /path/to/Check_File.sh file2 "11:00" "11:30" # Check file4 between 16:00-16:30 (starts at 16:00) 0 16 * * * /path/to/Check_File.sh file4 "16:00" "16:30"
Key Notes to Keep in Mind
- Mail Command: Ensure the
mailutility is installed on your system. For Debian/Ubuntu-based systems, install it withsudo apt install mailutils. For RHEL/CentOS, usesudo yum install mailx. - Absolute Paths: Always use full absolute paths in crontab entries and script file references to avoid issues with missing environment variables.
- Testing: To test the script without waiting for the scheduled time, run it manually with a small time window (e.g.,
./Check_File.sh testfile "14:00" "14:05") and create/delete the test file to verify behavior.
内容的提问来源于stack exchange,提问作者LearningCpp




