#!/bin/sh # TODO: # add a --uploads option to specify the number of latest files to uploads. Good # in case we missed some. # add options to wait before starting, similar to mirror.tcl # add option to sleep and restart automatically #set -x # All (good?) defaults VERBOSE=0 KEEP= PATHS= # Dynamic vars cmdname=$(basename $(readlink -f $0)) appname=${cmdname%.*} # Print usage on stderr and exit usage() { exitcode="$1" cat << USAGE >&2 Description: $cmdname will find the latest files matching a pattern and only keep a finite amount of the youngest files Usage: $cmdname [-option arg --long-option(=)arg] ([--] command) where all dash-led options are as follows (long options can be followed by an equal sign): -v | --verbose Be more verbose -k | --keep Number of files to keep, defaults to empty, meaning all -f | --files List of files to select from for removal USAGE exit "$exitcode" } # Parse options while [ $# -gt 0 ]; do case "$1" in -k | --keep) KEEP=$2; shift 2;; --keep=*) KEEP="${1#*=}"; shift 1;; -f | --files) PATHS=$2; shift 2;; --files=*) PATHS="${1#*=}"; shift 1;; -v | --verbose) VERBOSE=1; shift;; -h | --help) usage 0;; --) shift; break;; -*) echo "Unknown option: $1 !" >&2 ; usage 1;; *) break;; esac done if [ -z "$PATHS" ]; then echo "You need to specify files to select from for removal" >& 2 usage 1 fi # Conditional logging log() { if [ "$VERBOSE" = "1" ]; then echo "$1" fi } if [ -n "${KEEP}" -a "${KEEP}" -gt "0" ]; then log "Keeping only ${KEEP} youngest file(s) of $PATHS" while [ "$(ls $PATHS -1 -t | wc -l)" -gt "$KEEP" ]; do DELETE=$(ls $PATHS -1 -t | sort -r | tail -n 1) log "Removing old copy $DELETE" rm -rf $DELETE done fi if [ $# -ne "0" ]; then log "Executing $*" exec "$@" fi