Creating Log Rotation and Cleanup Scripts
Programs that run for a long time, such as web servers, background workers and scheduled scripts, write log files, and log files only grow. Left alone, a busy log can fill a disk in days, and a full disk stops databases, breaks uploads and prevents new logs from being written exactly when you need them. Log rotation keeps logs under control: at regular intervals, the current log is renamed and a new, empty log is started; older copies are compressed; and copies beyond a set number or age are deleted.
Most Linux systems rotate their own logs with a tool called logrotate, and it is usually the right choice for system services. Bash rotation and cleanup scripts are still common: for applications installed in a home folder or a project folder, on systems where you cannot change the logrotate configuration, for application-specific files such as reports and exports, and inside containers. Writing one also teaches how logging actually works at the file level, which explains logrotate's own options. This lesson covers both.
Understanding the Concept
A rotation scheme answers four questions:
- When to rotate? On a schedule (daily, weekly), when the log reaches a size, or both.
- How to name old copies? The common convention numbers them:
app.logis the current log,app.log.1the most recent old copy,app.log.2.gzthe one before, and so on. Another convention uses dates, such asapp.log-20261124.gz. - How many to keep? A fixed number of copies, a maximum age, or both.
- How does the program start writing to a new file? This is the subtle part, and it depends on how the program opened its log.
To understand question 4, you need to know what happens when a program writes to a file.
How Programs Hold Log Files Open
When a program opens a file, the kernel gives it a file descriptor: a reference to the file itself (its inode), not to its name. The program writes through that descriptor for as long as it runs. Renaming or deleting the file's name does not affect the descriptor.
Deleting a log that is still open
The following script starts a background writer that opens app.log once and writes a line every 0.1 seconds, then deletes the file while the writer is running:
cd /srv/t165
( exec 3>>app.log; for i in $(seq 1 20); do echo "line $i" >&3; sleep 0.1; done ) &
writer=$!
sleep 0.5
rm -- app.log
echo "after rm: $(ls app.log 2>&1)"
echo "writer's fd 3: $(readlink /proc/$writer/fd/3)"
wait "$writer"
after rm: ls: cannot access 'app.log': No such file or directory
writer's fd 3: /srv/t165/app.log (deleted)
The name is gone, but the writer keeps writing into the deleted file. Its disk space is not freed until the writer closes the file or exits, and its contents can no longer be read through any name. This is the classic "I deleted the 20 GB log but the disk is still full" problem. ls -l /proc/PID/fd (or lsof +L1, if installed) shows such deleted-but-open files. Never delete a log that a running program still has open.
Renaming has the same effect: after mv app.log app.log.1, the program keeps writing into app.log.1, because that is the same file. A rotation scheme therefore needs one of two strategies.
Strategy 1: move the log, then tell the program to reopen it
Rename the log, then ask the program to close its descriptor and open the log name again, which creates a new file. Many daemons reopen their logs when they receive the SIGHUP signal (lesson 140); others have a command such as nginx -s reopen. Lines written between the rename and the reopen go into the renamed file, so nothing is lost. This is the clean method whenever the program supports it.
Strategy 2: copy the log, then truncate it
If the program cannot be told to reopen its log, copy the log to the rotated name and then truncate the original to zero length in place. The program keeps its descriptor to the same, now empty, file. This is called copy-truncate. It has two drawbacks:
- Lines written between the copy and the truncate are lost.
- It only works properly if the program opened the log in append mode (
>>in the shell,O_APPENDin C). A program that opened the file with plain>keeps its own write position, and after the truncate it continues writing at that old position, leaving a gap of zero bytes at the start of the file.
The difference is easy to show. Two writers each print a line every 0.2 seconds, one appending (>>) and one not (>). After about three lines, both logs are copied and truncated with : > file:
( for i in 1 2 3 4 5 6; do printf 'appending writer line %d\n' "$i"; sleep 0.2; done ) >> a.log &
( for i in 1 2 3 4 5 6; do printf 'plain writer line %d\n' "$i"; sleep 0.2; done ) > b.log &
sleep 0.7
cp a.log a.log.1; : > a.log
cp b.log b.log.1; : > b.log
wait
echo "a.log: $(stat -c %s a.log) bytes"; cat a.log
echo "b.log: $(stat -c %s b.log) bytes"; od -c b.log | head -3
a.log: 48 bytes
appending writer line 5
appending writer line 6
b.log: 120 bytes
0000000 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
*
0000120 p l a i n w r i t e r l i n
The appending writer continued at the start of the empty file. The plain writer continued at byte 120, where it had stopped, and the first 120 bytes of b.log are now NUL bytes (\0). On most file systems these bytes do not use disk space (the file is sparse), but tools such as grep may treat the file as binary. When you write scripts that log, always use >>; then copy-truncate rotation works for them.
logrotate in Brief
logrotate is normally run once a day by cron or a systemd timer and reads its configuration from /etc/logrotate.conf and the files in /etc/logrotate.d/. A typical entry for an application looks like this:
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
copytruncate
}
| Directive | Meaning |
|---|---|
daily / weekly / monthly | how often to rotate |
size 100M | rotate when the log is larger than this, instead of on a schedule |
rotate 7 | keep seven old copies |
compress | gzip old copies |
delaycompress | leave the newest old copy (.1) uncompressed until the next rotation |
missingok | do not report an error if the log is missing |
notifempty | do not rotate an empty log |
copytruncate | use copy-truncate instead of moving the file |
postrotate ... endscript | commands to run after rotation, typically sending SIGHUP |
To use the move-and-reopen strategy, replace copytruncate with a postrotate block, for example postrotate / kill -HUP "$(cat /run/myapp.pid)" / endscript, plus sharedscripts so the command runs once for all matched logs rather than once per log. logrotate -d /etc/logrotate.d/myapp runs in debug mode and shows what would happen without changing anything.
delaycompress exists because of the timing described above: with move-and-reopen, the program may still write to .1 for a moment after the rename, and compressing a file while it is still being written would lose those lines.
Rotation Step by Step
A numbered rotation with KEEP copies must rename the files from the oldest to the newest, so no copy overwrites one that has not been moved yet. For KEEP=3:
app.log.2.gz -> app.log.3.gz (replaces the oldest copy, which is dropped)
app.log.1 -> app.log.2.gz (compressed on the way)
app.log -> app.log.1 (moved, or copied and truncated)
If you started from the newest, mv app.log app.log.1 would destroy the previous app.log.1 before it had been moved.
Cleaning Up by Age with find
Logs and other generated files (reports, exports, temporary uploads) are often cleaned up by age rather than count. find selects files by modification time with -mtime (days) and -mmin (minutes):
touch -d '30 days ago' d30
touch -d '30 days ago 12 hours ago' d30h12
touch -d '31 days ago 1 hour ago' d31
touch -d '2 days ago' d2
echo "-mtime +30:" $(find . -type f -mtime +30 | sort)
echo "-mtime 30:" $(find . -type f -mtime 30 | sort)
echo "-mtime -3:" $(find . -type f -mtime -3 | sort)
-mtime +30: ./d31
-mtime 30: ./d30 ./d30h12
-mtime -3: ./d2
find divides a file's age by 24 hours and drops the fraction before comparing. A file that is 30.5 days old counts as 30 days, so -mtime +30 ("more than 30") matches only files that are at least 31 full days old. -mtime -3 means less than 3 days.
A safe cleanup command limits every dimension of the search:
find /srv/app/exports -maxdepth 1 -type f -name '*.csv' -mtime +30 -print # look first
find /srv/app/exports -maxdepth 1 -type f -name '*.csv' -mtime +30 -delete # then delete
-maxdepth 1keeps it out of subfolders unless you want them.-type fnever selects folders, links or devices.-namelimits it to the files this job owns.-printfirst,-deleteonly after checking, and tests always before-delete(lesson 160).
The modification time of a rotated log is the time of its last write, and mv, cp -p and gzip all keep it. An age rule on rotated copies therefore means "logs whose last entry is older than N days".
A Complete Example: A Log Rotation Script
rotate-logs.sh rotates every *.log file in one folder using numbered, compressed copies, supports both rotation strategies, can delete copies by age, has a dry-run mode and refuses to run twice at the same time.
#!/usr/bin/env bash
#
# rotate-logs.sh - rotate the *.log files in one folder and delete old copies
#
# Usage: rotate-logs.sh [-n] [-k KEEP] [-s MIN_KB] [-d MAX_DAYS] [-p PIDFILE] LOG_DIR
# -n dry run: print the commands instead of running them
# -k KEEP rotated copies to keep for each log (default: 5)
# -s MIN_KB rotate only logs of at least MIN_KB KiB (default: 0 = any non-empty log)
# -d MAX_DAYS also delete rotated copies not written to for more than MAX_DAYS days
# -p PIDFILE move each log away and send SIGHUP to the process in PIDFILE so it
# reopens its log; without -p, logs are copied and then truncated
#
# NAME.log becomes NAME.log.1 (kept uncompressed for one cycle), NAME.log.1
# becomes NAME.log.2.gz, and so on up to NAME.log.KEEP(.gz). Exit: 0 ok, 1 error, 2 usage.
set -euo pipefail
shopt -s nullglob
dry_run=0 keep=5 min_kb=0 max_days='' pidfile=''
die() { echo "${0##*/}: $*" >&2; exit 1; }
usage() { echo "usage: ${0##*/} [-n] [-k KEEP] [-s MIN_KB] [-d MAX_DAYS] [-p PIDFILE] LOG_DIR" >&2; exit 2; }
is_uint() { [[ $1 =~ ^[0-9]{1,6}$ ]]; }
# run CMD...: run a command, or only print it in a dry run
run() {
if (( dry_run )); then
printf 'would run:'; printf ' %q' "$@"; printf '\n'
else
"$@"
fi
}
parse_args() {
local opt
while getopts ':nk:s:d:p:' opt; do
case $opt in
n) dry_run=1 ;;
k) keep=$OPTARG ;;
s) min_kb=$OPTARG ;;
d) max_days=$OPTARG ;;
p) pidfile=$OPTARG ;;
*) usage ;;
esac
done
shift $((OPTIND - 1))
(( $# == 1 )) || usage
log_dir=$1
is_uint "$keep" && (( 10#$keep >= 1 )) || die "KEEP must be 1 or more: ${keep@Q}"
is_uint "$min_kb" || die "MIN_KB must be a whole number: ${min_kb@Q}"
[[ -z $max_days ]] || is_uint "$max_days" || die "MAX_DAYS must be a whole number: ${max_days@Q}"
keep=$((10#$keep)) min_kb=$((10#$min_kb))
[[ -d $log_dir && ! -L $log_dir ]] || die "not a folder: $log_dir"
}
# read_pid: print the PID from PIDFILE if that process is running
read_pid() {
local pid
[[ -r $pidfile ]] || die "cannot read PID file: $pidfile"
read -r pid < "$pidfile" || true
[[ $pid =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null || die "no running process for PID file $pidfile"
echo "$pid"
}
# rotate_one LOG: shift the old copies of LOG up by one and start a new LOG
rotate_one() {
local log=$1 size_kb i
size_kb=$(( ($(stat -c %s -- "$log") + 1023) / 1024 ))
if [[ ! -s $log ]] || (( size_kb < min_kb )); then
echo "skip $log (${size_kb} KiB)"
return
fi
echo "rotate $log (${size_kb} KiB)"
# oldest first: LOG.(KEEP-1).gz -> LOG.KEEP.gz replaces the oldest copy
for (( i = keep - 1; i >= 2; i-- )); do
[[ -e $log.$i.gz ]] && run mv -f -- "$log.$i.gz" "$log.$((i + 1)).gz"
done
if [[ -e $log.1 ]] && (( keep >= 2 )); then
run gzip -f -- "$log.1" # LOG.1 -> LOG.1.gz, keeps its time stamp
run mv -f -- "$log.1.gz" "$log.2.gz"
fi
if [[ -n $pidfile ]]; then
run mv -f -- "$log" "$log.1" # the program keeps writing to LOG.1 until SIGHUP
else
run cp -p -- "$log" "$log.1" # lines written between cp and truncate are lost
run truncate -s 0 -- "$log"
fi
}
delete_old() {
[[ -n $max_days ]] || return 0
local -a old=()
local f
while IFS= read -r -d '' f; do old+=("$f"); done < <(
find "$log_dir" -maxdepth 1 -type f -name '*.log.[0-9]*' -mtime "+$max_days" -print0 | sort -z)
for f in "${old[@]}"; do
echo "delete $f (older than $max_days days)"
run rm -f -- "$f"
done
}
main() {
local log pid=''
parse_args "$@"
# only one rotation per folder at a time
exec 9> "$log_dir/.rotate-logs.lock"
flock -n 9 || die "another rotation is running in $log_dir"
[[ -z $pidfile ]] || pid=$(read_pid)
for log in "$log_dir"/*.log; do
[[ -f $log && ! -L $log ]] || continue
rotate_one "$log"
done
if [[ -n $pid ]]; then
echo "signal PID $pid to reopen its logs"
run kill -HUP "$pid"
fi
delete_old
}
main "$@"
How It Works
- Options and validation. Every number is checked with
is_uint(one to six digits) and read as decimal with10#.KEEPmust be at least 1. The log folder must be a real folder, not a symbolic link. - The
runhelper. Every command that changes a file goes throughrun. In a dry run it prints the command, quoted with%qso that unusual file names are visible, instead of executing it. Becauseruntakes a command and its arguments, the script usestruncate -s 0rather than the redirection: > file, whichruncould not print. - Locking.
exec 9>opens a lock file on file descriptor 9, andflock -n 9takes an exclusive lock or fails immediately if another run holds it. The lock is released automatically when the script exits. Lesson 171 covers lock files in detail. - Choosing logs. The glob
"$log_dir"/*.logwithnullglobmatches only current logs, never the numbered copies. Symbolic links are skipped, so a link namedsomething.logcannot make the script rotate a file elsewhere.rotate_oneskips empty logs and logs below the size limit; sizes are rounded up to whole KiB, so any non-empty log counts as at least 1 KiB. - Shifting copies. The
forloop renames.gzcopies fromKEEP-1down to 2, so each move goes into a slot that has already been emptied, and the move into.KEEP.gzreplaces the oldest copy. Then the uncompressed.1is compressed withgzip(which keeps the original modification time) and renamed to.2.gz. The newest copy stays uncompressed for one cycle, likelogrotate'sdelaycompress. - Starting a new log. Without
-p, the log is copied withcp -p(keeping its time stamp and permissions) and truncated in place. With-p, the log is moved to.1, and after all logs are rotated, one SIGHUP is sent to the process in the PID file.read_pidchecks that the PID file contains a number and that the process exists (kill -0) before any file is moved, so the script never moves logs for a program it cannot signal. - Age cleanup. With
-d,findselects only regular files named like rotated copies (*.log.[0-9]*) directly in the folder, older thanMAX_DAYSfull days, and the NUL-separated list is deleted one file at a time (throughrun, so a dry run shows what would be removed).
Running the Complete Example
The folder logs contains app.log, an empty empty.log and link.log, a symbolic link to /etc/hostname. Each of four runs first appends a line to app.log and then rotates with KEEP=3:
for run in 1 2 3 4; do
printf 'app run %d\n' "$run" >> logs/app.log
echo "=== run $run: rotate-logs.sh -k 3 logs"; rotate-logs.sh -k 3 logs; echo "status $?"
done
=== run 1: rotate-logs.sh -k 3 logs
rotate logs/app.log (1 KiB)
skip logs/empty.log (0 KiB)
status 0
=== run 2: rotate-logs.sh -k 3 logs
rotate logs/app.log (1 KiB)
skip logs/empty.log (0 KiB)
status 0
=== run 3: rotate-logs.sh -k 3 logs
rotate logs/app.log (1 KiB)
skip logs/empty.log (0 KiB)
status 0
=== run 4: rotate-logs.sh -k 3 logs
rotate logs/app.log (1 KiB)
skip logs/empty.log (0 KiB)
status 0
Checking the contents of each copy shows that every run's line moved one slot further, and the line from run 1 was dropped because only three copies are kept:
logs/app.log:
logs/app.log.1: app run 4
logs/app.log.2.gz: app run 3
logs/app.log.3.gz: app run 2
The symbolic link was never touched or listed, and the empty log was skipped.
Next, a 3000-byte web.log is added, and the two older copies of app.log are given old time stamps: app.log.3.gz 45 days, app.log.2.gz 10 days. A dry run with a 2 KiB minimum size and a 30-day age limit shows the plan:
rotate-logs.sh -n -k 3 -s 2 -d 30 logs; echo "status $?"
skip logs/app.log (0 KiB)
skip logs/empty.log (0 KiB)
rotate logs/web.log (3 KiB)
would run: cp -p -- logs/web.log logs/web.log.1
would run: truncate -s 0 -- logs/web.log
delete logs/app.log.3.gz (older than 30 days)
would run: rm -f -- logs/app.log.3.gz
status 0
Running the same command without -n carries it out:
rotate-logs.sh -k 3 -s 2 -d 30 logs; echo "status $?"
ls logs
skip logs/app.log (0 KiB)
skip logs/empty.log (0 KiB)
rotate logs/web.log (3 KiB)
delete logs/app.log.3.gz (older than 30 days)
status 0
app.log
app.log.1
app.log.2.gz
empty.log
link.log
web.log
web.log.1
The 45-day-old copy was deleted and the 10-day-old copy was kept.
To test the move-and-reopen strategy, demo-daemon.sh plays the part of a server. It writes its PID to a file, opens its log once, writes a line every 0.2 seconds, and reopens the log when it receives SIGHUP:
#!/usr/bin/env bash
# demo-daemon.sh LOG PIDFILE: write a line every 0.2 s; reopen LOG on SIGHUP
log=$1
echo "$$" > "$2"
exec 3>> "$log"
trap 'exec 3>&-; exec 3>> "$log"; echo "reopened $log" >&3' HUP
for (( n = 1; n <= 15; n++ )); do
echo "tick $n" >&3
sleep 0.2
done
The daemon is started in the background, and the logs are rotated about one second later:
bash demo-daemon.sh dlogs/daemon.log dlogs/daemon.pid &
sleep 1.1
rotate-logs.sh -p dlogs/daemon.pid dlogs; echo "status $?"
wait
echo "--- dlogs/daemon.log.1"; cat dlogs/daemon.log.1
echo "--- dlogs/daemon.log"; cat dlogs/daemon.log
rotate dlogs/daemon.log (1 KiB)
signal PID 1807 to reopen its logs
status 0
--- dlogs/daemon.log.1
tick 1
tick 2
tick 3
tick 4
tick 5
tick 6
--- dlogs/daemon.log
reopened dlogs/daemon.log
tick 7
tick 8
tick 9
tick 10
tick 11
tick 12
tick 13
tick 14
tick 15
Every line is in exactly one file: ticks 1 to 6 went to the old log, which was renamed while the daemon still had it open, and after the signal the daemon created a new daemon.log and continued there. No line was lost and no NUL bytes appeared.
Invalid input and a second run at the same time are refused:
$ rotate-logs.sh -k 0 logs
rotate-logs.sh: KEEP must be 1 or more: '0'
status 1
$ rotate-logs.sh -d abc logs
rotate-logs.sh: MAX_DAYS must be a whole number: 'abc'
status 1
$ rotate-logs.sh missing
rotate-logs.sh: not a folder: missing
status 1
$ rotate-logs.sh -p /nonexistent.pid logs
rotate-logs.sh: cannot read PID file: /nonexistent.pid
status 1
$ rotate-logs.sh logs (while another run holds the lock)
rotate-logs.sh: another rotation is running in logs
status 1
To rotate nightly, schedule the script with cron (lesson 170), for example 15 0 * * * /usr/local/bin/rotate-logs.sh -k 14 -d 60 /srv/app/logs.