Write a script that monitors a log file in real time and sends a Slack message on "ERROR".
IntermediateHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
WEBHOOK="${SLACK_WEBHOOK:?}"
tail -Fn0 /var/log/app/app.log | grep --line-buffered 'ERROR' | while read -r line; do
payload=$(jq -n --arg t "$(hostname): $line" '{text: $t}')
curl -s -X POST -H 'Content-Type: application/json' -d "$payload" "$WEBHOOK" >/dev/null
done
Key trick → tail -F follows the file across rotation (by name, not inode), and --line-buffered stops grep from holding output in a 4 KB buffer. jq -n --arg escapes quotes in the log line safely.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate