Skip to content

Instantly share code, notes, and snippets.

@RonanKER
Created February 14, 2018 23:30
Show Gist options
  • Save RonanKER/7682fb4a6d70877f646569c8c6b018ee to your computer and use it in GitHub Desktop.
Save RonanKER/7682fb4a6d70877f646569c8c6b018ee to your computer and use it in GitHub Desktop.
remove_old_files.sh by Seb Dangerfield
#!/bin/bash
# http://www.sebdangerfield.me.uk/2011/02/old_file_removal_bash-script/
# ex: ./remove_old_files.sh 30 /home/myuser/large_file_count_dir
if [ $# -ne 2 ] ; then
echo "Not enough arguments.
Please pass the number of files to keep followed by the path"
exit 1
fi
# First argument is the number of files to keep!
KEEP_NUM=$1
# Second argument is the directory to look under:
DIR=$2
if [ $KEEP_NUM -gt 0 ] ; then
FILES=(`ls -t1 $DIR`)
NUM_FILES=${#FILES[@]}
echo Number of files found: $NUM_FILES
# Remove all the old files from the array after the required
# number have been kept!
FILES_REMOVED=0
for ((i=KEEP_NUM;i< $NUM_FILES;i++)); do
echo Removing: $DIR/${FILES[$i]}
`rm -f $DIR/${FILES[$i]}`
let FILES_REMOVED++
done
echo $FILES_REMOVED 'File(s) removed'
else
echo 'please specify the number of files to keep: 1 or more'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment