I am new to shell scripting, so I need some help here. I have a directory that fills up with backups. If I have more than 10 backup files, I would like to remove the oldest fi
On a very limited chroot environment, we had only a couple of programs available to achieve what was initially asked. We solved it that way:
MIN_FILES=5
FILE_COUNT=$(ls -l | grep -c ^d )
if [ $MIN_FILES -lt $FILE_COUNT ]; then
while [ $MIN_FILES -lt $FILE_COUNT ]; do
FILE_COUNT=$[$FILE_COUNT-1]
FILE_TO_DEL=$(ls -t | tail -n1)
# be careful with this one
rm -rf "$FILE_TO_DEL"
done
fi
Explanation:
FILE_COUNT=$(ls -l | grep -c ^d )
counts all files in the current folder. Instead of grep we could use also wc -l
but wc was not installed on that host.FILE_COUNT=$[$FILE_COUNT-1]
update the current $FILE_COUNT
FILE_TO_DEL=$(ls -t | tail -n1)
Save the oldest file name in the $FILE_TO_DEL
variable. tail -n1
returns the last element in the list.