← Back to all snippets
BASH

Monitor a Log File for Keywords and Trigger Action

Continuously monitor a specific log file for the occurrence of predefined keywords and execute an arbitrary command or script when detected.

#!/bin/bash

# --- Configuration ---
LOG_FILE="/var/log/nginx/error.log"
KEYWORDS="error|critical|fail"
ACTION_SCRIPT="/usr/local/bin/send_alert.sh" # Script to run when keywords are found

# --- Script Logic ---

if [ ! -f "$LOG_FILE" ]; then
  echo "Error: Log file '$LOG_FILE' not found." >&2
  exit 1
fi

echo "Monitoring $LOG_FILE for keywords: '$KEYWORDS' (Press Ctrl+C to stop)"

tail -F "$LOG_FILE" | while read -r line ;
do
  if echo "$line" | grep -qiE "$KEYWORDS"; then
    echo "$(date +"%Y-%m-%d %H:%M:%S") - Keyword found: $line"
    # Execute the action script (e.g., send email, restart service)
    if [ -x "$ACTION_SCRIPT" ]; then
      "$ACTION_SCRIPT" "$line" # Pass the matching log line as an argument
    else
      echo "Warning: Action script '$ACTION_SCRIPT' not found or not executable." >&2
    fi
  fi
done
How it works: This script provides real-time monitoring of a log file. It uses `tail -F` to continuously output new lines from the log and pipes them to a `while read` loop. Inside the loop, `grep -qiE` checks each line for any of the specified keywords (case-insensitive, extended regex). If a keyword is found, it logs the event and then executes a predefined 'action script', which could be anything from sending an email notification to restarting a service, making it invaluable for proactive system management.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs