Creating Log Rotation and Cleanup Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
17 min read ·Lesson 165 of 205

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:

  1. When to rotate? On a schedule (daily, weekly), when the log reaches a size, or both.
  2. How to name old copies? The common convention numbers them: app.log is the current log, app.log.1 the most recent old copy, app.log.2.gz the one before, and so on. Another convention uses dates, such as app.log-20261124.gz.
  3. How many to keep? A fixed number of copies, a maximum age, or both.
  4. 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_APPEND in 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
}
DirectiveMeaning
daily / weekly / monthlyhow often to rotate
size 100Mrotate when the log is larger than this, instead of on a schedule
rotate 7keep seven old copies
compressgzip old copies
delaycompressleave the newest old copy (.1) uncompressed until the next rotation
missingokdo not report an error if the log is missing
notifemptydo not rotate an empty log
copytruncateuse copy-truncate instead of moving the file
postrotate ... endscriptcommands 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 1 keeps it out of subfolders unless you want them.
  • -type f never selects folders, links or devices.
  • -name limits it to the files this job owns.
  • -print first, -delete only 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 with 10#. KEEP must be at least 1. The log folder must be a real folder, not a symbolic link.
  • The run helper. Every command that changes a file goes through run. In a dry run it prints the command, quoted with %q so that unusual file names are visible, instead of executing it. Because run takes a command and its arguments, the script uses truncate -s 0 rather than the redirection : > file, which run could not print.
  • Locking. exec 9> opens a lock file on file descriptor 9, and flock -n 9 takes 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"/*.log with nullglob matches only current logs, never the numbered copies. Symbolic links are skipped, so a link named something.log cannot make the script rotate a file elsewhere. rotate_one skips 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 for loop renames .gz copies from KEEP-1 down to 2, so each move goes into a slot that has already been emptied, and the move into .KEEP.gz replaces the oldest copy. Then the uncompressed .1 is compressed with gzip (which keeps the original modification time) and renamed to .2.gz. The newest copy stays uncompressed for one cycle, like logrotate's delaycompress.
  • Starting a new log. Without -p, the log is copied with cp -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_pid checks 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, find selects only regular files named like rotated copies (*.log.[0-9]*) directly in the folder, older than MAX_DAYS full days, and the NUL-separated list is deleted one file at a time (through run, 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Creating Log Rotation and Cleanup Scripts and get answers drawn from it.

Signed-in readers only.