I am looking for a way to delete folders that are older than 7 days, but always have 20 newest folders. similar named folders with _SAME_NAME_@tmp should be deleted as well.
I'm stuck with making sure it really will be 20 folders at the end, and it will not be deleted after a month has past. I am also struggling with the nested while loop syntax. Many thanks in advance.
#!/bin/bash folders=`ls -A /folder/folder1 | sort -n > /tmp/test.txt` NUMofFolders=`wc -l /tmp/test.txt | awk '{print $1}'` if [ $NUMofFolders -lt 20 ] ; then echo "Only 20 folders exist" exit 1 else echo "Runing with the script" fi input="/tmp/test.txt" FolderPATH="/folder/folder1" count=$(find $Folders -maxdepth 1 -type d -mtime +7 -printf '%Ts\t%P\n' -exec egrep -v "*@tmp" '{}' + | wc -l) while IFS= read -r line ; do while [ "$count" -gt "20" ] ; do find /folder/folder1/"$line" -maxdepth 1 -type d -mtime +7 -printf '%Ts\t%P\n' {} \; do find $FolderPATH -maxdepth 1 -type d -mtime +7 -print -delete -quit count=$((--count)) rm -rf $FolderPATH@tmp done done < "$input"
for d in {20180301..20180331} ; do mkdir "$d" && touch -d "$d" "$d"; done