Created
February 28, 2017 17:09
-
-
Save dahse89/dd72f12154cdeaa33c563ad6b1e754d1 to your computer and use it in GitHub Desktop.
Checks all files and directories next to itself. If there "last modified date" is older then given days (file_live_time_in_days) it remove those data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# cleaner.sh by Philipp Dahse <[email protected]> | |
# ------------------------------------------------ | |
# checks all files and directories next to itself. | |
# If there "last modified date" is older then given days (file_live_time_in_days) | |
# it remove those data. | |
# I use this script in something like a personal tmp directory: | |
# | |
# /home/my/tmp/cleaner.sh | |
# | |
# When ever i fiddle about with some file or directories for temporary reasons i put it to /home/my/tmp | |
# On startup i run: /home/my/tmp/cleaner.sh >> /var/logs/cleaner.log 2>&1 | |
# This keeps the data for 30 days and removes them afterwards | |
script_name="`basename $0`" | |
file_live_time_in_days=30 | |
# Get path of this script for relative and absolute execution | |
script_path=$([[ "$0" != /* ]] && echo "$(cd $(pwd)/$(dirname $0);pwd)" || echo "$(dirname $0)") | |
function last_modified | |
{ | |
last_modified_full="$(stat -c %y $1)" | |
echo ${last_modified_full:0:19} | |
} | |
function date_diff | |
{ | |
# Get date diff (http://stackoverflow.com/a/25097776/4216245) | |
fullyear=$(date -d@$(( ( $(date -ud "$1" +'%s') - $(date -ud "$2" +'%s') ) )) +'%Y years %m months') | |
yearsubtraction=$(( $(echo $fullyear | sed -r 's/^([0-9]+).*/\1/') - 1970 )) | |
if [ $yearsubtraction -le '0' ]; then | |
echo $fullyear | sed -r "s/^([0-9]+) years //" | |
else | |
echo $fullyear | sed -r "s/^([0-9]+) /$(printf %02d $yearsubtraction) /" | |
fi | |
} | |
function log_removal | |
{ | |
type=$([[ -d $1 ]] && echo "DIR " || echo "FILE") | |
log_time=`date +"%Y-%m-%d %T"` | |
last_modified=$(last_modified "$1") | |
diff=$(date_diff "$last_modified" "$log_time") | |
echo "[$log_time] REMOVE $type [last_modified] $last_modified [age] $diff [expire age] $file_live_time_in_days days $1" | |
} | |
for x in `find "$script_path" -maxdepth 1 ! -name "$script_name" ! -name "." ! -name ".." -mtime +"$file_live_time_in_days"` | |
do | |
log_removal $x | |
rm -rf "$x" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment