With zsh
:
#! /usr/bin/env zsh
days=${1-30}
zmodload zsh/datetime || exit
strftime -s cutoff %Y%m%d $((EPOCHSECONDS - days * 24 * 60 * 60))
old_enough() {
year=$REPLY[5,6]
((year += 1900 + (year < 70) * 100))
[[ $year$REPLY[1,4] < $cutoff ]]
}
set -o extendedglob
echo rm -rf [0-9](#c6)(/+old_enough)
Remove the echo
or pipe to sh
if happy.
With ksh93
, an equivalent could be:
#! /usr/bin/env ksh
days=${1-30}
cutoff=$(printf '%(%Y%m%d)T' "$days days ago")
old_enough() {
year=${1:4}
((year += 1900 + (year < 70) * 100))
[[ $year${1:0:4} < $cutoff ]]
}
dirs=()
for f in {6}([0-9]); do
[ -d "$f" ] && [ ! -L "$f" ] && old_enough "$f" && dirs+=("$f")
done
if ((${#dirs[@]})); then
echo rm -rf "${dirs[@]}"
else
echo >&2 "No match"
exit 1
fi
With bash
, an equivalent could be:
#! /usr/bin/env bash
days=${1-30}
printf -v now '%(%s)T' -1
printf -v cutoff '%(%Y%m%d)T' "$((now - days * 24 * 60 * 60))"
old_enough() {
year=${1:4}
year=${year#0} # work around bug where bash complains about 08 and 09
((year += 1900 + (year < 70) * 100))
[[ $year${1:0:4} < $cutoff ]]
}
shopt -s nullglob
dirs=()
for f in [0-9][0-9][0-9][0-9][0-9][0-9]; do
[ -d "$f" ] && [ ! -L "$f" ] && old_enough "$f" && dirs+=("$f")
done
if ((${#dirs[@]})); then
echo rm -rf "${dirs[@]}"
else
echo >&2 "No match"
exit 1
fi
Years above 70 are assumed to be from the last century (123199
means 1999-12-31, 092217
means 2017-09-22).
If you have neither of those shells and are on a Unix (not GNU (UNG)) system, then your best bet may be to resort to perl
:
#! /usr/bin/env perl
use POSIX;
$cutoff = time - ($ARGV[0] // 30) * 24 * 60 * 60;
$, = " "; $\ = "\n";
if (@dirs = grep {
/^(\d\d)(\d\d)(\d\d)$/ && ! -l && -d &&
mktime(0,0,0,$2,$1-1,$3+100*($3<70)) < $cutoff} <*>) {
print "rm -rf", @dirs;
} else {
die "No match";
}