Использование двух для l oop
#!/bin/bash
shopt -s nullglob ##: This might not be needed but just in case
##: If there are no files the glob will not expand
latest=
allfiles=()
unwantedfiles=()
for file in *_????-??-??_*.sql.gz; do
if [[ $file =~ _([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2})_ ]]; then
allfiles+=("$file")
[[ $file > $latest ]] && latest=$file ##: The > is magical inside [[
fi
done
n=${#allfiles[@]}
if ((n <= 1)); then ##: No files or only one file don't remove it!!
printf '%s\n' "Found ${n:-0} ${allfiles[@]:-*sql.gz} file, bye!"
exit 0 ##: Exit gracefully instead
fi
for f in "${allfiles[@]}"; do
[[ $latest == $f ]] && continue ##: Skip the latest file in the loop.
unwantedfiles+=("$f") ##: Save all files in an array without the latest.
done
printf 'Deleting the following files: %s\n' "${unwantedfiles[*]}"
echo rm -rf "${unwantedfiles[@]}"
В значительной степени зависит от оператора >
внутри [[
Вы можете создать новый файл с более низкими датами будь хорошим.
Эхо есть только для того, чтобы увидеть, что произойдет. Удалите его, если вы удовлетворены выводом.
Сейчас я на самом деле использую этот скрипт через cron, за исключением части *.sql.gz
, так как у меня есть только каталоги для сопоставления, но тот же формат даты, поэтому у меня есть , ????-??-??/
и только ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2})
в качестве шаблона регулярного выражения.