Last active
June 5, 2019 21:57
-
-
Save efrecon/97cfbe9e8c836b2bf2f0d28d7d3e2212 to your computer and use it in GitHub Desktop.
Clean old files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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="" | |
THEN="" | |
# 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] pattern | |
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 | |
-t | --then Command to execute once done | |
USAGE | |
exit "$exitcode" | |
} | |
# Parse options | |
while [ $# -gt 0 ]; do | |
case "$1" in | |
-k | --keep) | |
KEEP=$2; shift 2;; | |
--keep=*) | |
KEEP="${1#*=}"; shift 1;; | |
-t | --then) | |
THEN=$2; shift 2;; | |
--then=*) | |
THEN="${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 [ $# -eq 0 ]; then | |
echo "You need to specify sources to copy for offline backup" >& 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 $@" | |
while [ "$(ls $@ -1 -t | wc -l)" -gt "$KEEP" ]; do | |
DELETE=$(ls $@ -1 -t | sort -r | tail -n 1) | |
log "Removing old copy $DELETE" | |
rm -rf $DELETE | |
done | |
fi | |
if [ -n "${THEN}" ]; then | |
log "Executing ${THEN}" | |
eval "${THEN}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment