Skip to content

Instantly share code, notes, and snippets.

@gchristofferson
Last active January 2, 2019 21:14
Show Gist options
  • Save gchristofferson/b546f855688c5ca026701f415cc5e578 to your computer and use it in GitHub Desktop.
Save gchristofferson/b546f855688c5ca026701f415cc5e578 to your computer and use it in GitHub Desktop.
This bash script takes two command line arguments which is the name of the directory and number of files to keep. It will count the number of files and delete any extra. Ideal for tracking and deleting extra backup files made automatically in a directory
#!/bin/sh
# this script takes two command line arguments which is the name of the directory to count files in and number of files to keep in directory
# must use full path to directory (i.e. /home/path_to_directory) as first argument
# the script counts the number of files in the directory and if more than number to keep, extra files will be deleted
# it will delete the oldest database files over the number to keep
# ideal for deleting old copies of backup files.
dir="$1"
num_to_keep="$2"
cd $dir
shopt -s nullglob
numfiles=(*)
numfiles=${#numfiles[@]}
echo "Number of files is $numfiles"
unset -v oldest
if [[ $numfiles -gt $num_to_keep ]]
then
echo "$numfiles is greater than $num_to_keep"
while [[ $numfiles -gt $num_to_keep ]]
do
for file in "$dir"/*; do
[[ -z $oldest || $file -ot $oldest ]] && oldest=$file
done
echo "The oldest file in the directory is $oldest"
if [[ $oldest == *".sql" ]]
then
echo "The oldest file is an sql database file"
rm $oldest
unset -v oldest
let "numfiles=$numfiles - 1"
echo "Number of files is now $numfiles"
else
echo "The oldest file is not a database file"
let "numfiles=$numfiles"
touch $oldest
fi
done
else
echo "$numfiles is equal to or less than $num_to_keep"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment