(Ubuntu Server)

I have a folder full of files in pairs (one is a log, another is a DB backup) They are basically create/modified at the same time.

I need a shell script that detects if the folder has more than 28 or 30 files (always will be a pair), it deletes the oldest two.

What is the quickest way to do this?

Dani AI

Generated

Following on the thread ( noted the links weren't enough and pointed to examples), here is a compact, practical Bash solution that checks a directory, and — if there are more than MAX files — removes the oldest two at a time until the count is at or below MAX. It assumes regular files (logs + DB files) live in the same folder and that pairs are created at nearly the same mtime. The script uses safe quoting and a dry‑run hint.

#!/usr/bin/env bash
set -euo pipefail

DIR='/path/to/dir'    # use an absolute path
MAX=28               # change to 30 if desired

while true; do
  count=$(find "$DIR" -maxdepth 1 -type f | wc -l)
  [ "$count" -le "$MAX" ] && break

  # get two oldest files (prints full path; preserves spaces)
  mapfile -t oldest < <(find "$DIR" -maxdepth 1 -type f -printf '%T@ %p\n' | sort -n | head -n 2 | cut -d' ' -f2-)

  [ "${#oldest[@]}" -eq 0 ] && break

  # dry-run: replace the echo with 'rm -f' after verification
  echo "Removing:" "${oldest[@]}"
  rm -- "${oldest[@]}"
done

Notes and cautions: use the full directory path, test with the echo/dry‑run first, and ensure running account has appropriate permissions. This approach preserves filename spaces but not newline-containing filenames (rare). If pairs share a common basename (for example both files use the same timestamped prefix), a safer variant is to detect and delete by basename so both members of a pair are removed together — useful if mtimes can differ slightly. Finally, schedule as a cron job or run after each backup, and add logging if required.

Recommended Answers

All 3 Replies

I think this is two searches and then combine these for your final script.

  1. https://www.google.com/search?q=count+number+of+files+in+directory+bash
  2. https://www.google.com/search?q=delete+oldest+file+in+directory+bash

Actually the second research seems to have something very close to what you were looking for.
Try http://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash with x set to 28.

None of these links really help out with the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.