Write a script to rotate a log file manually: compress the current one and truncate it without restarting the app.
IntermediateHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
LOG=/var/log/app/app.log
TS=$(date +%F-%H%M)
cp "$LOG" "$LOG.$TS"
: > "$LOG" # truncate in place, same inode
gzip "$LOG.$TS"
find /var/log/app -name 'app.log.*.gz' -mtime +30 -delete
Key trick → mv would leave the app writing to the old inode. Copy-then-truncate (logrotate's copytruncate) keeps the same file handle valid, at the cost of possibly losing a few lines written between the copy and the truncate.
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