Skip to content

Instantly share code, notes, and snippets.

@yyogo
Created October 11, 2018 12:46
Show Gist options
  • Save yyogo/d472109840cc5e50ef942f411026712c to your computer and use it in GitHub Desktop.
Save yyogo/d472109840cc5e50ef942f411026712c to your computer and use it in GitHub Desktop.
Cleanup stuff
#!/bin/bash
# remove shit from downloads
shopt -s nullglob dotglob
current_time=`date +%s`
max_age_days=${1:-30}
max_age_days=$((max_age_days))
if [ $max_age_days -le 0 ]; then
>&2 echo "Usage: $0 [max age in days]"
>&2 echo "Delete old files from some user directories"
exit 255
fi
age_deadline=$((current_time - max_age_days * 24 * 60 * 60))
echo "Looking for files older than $max_age_days day(s)"
deletion_paths=~/Downloads
declare -a to_delete
for path in $deletion_paths; do
files=("$path/"*)
for f in "${files[@]}"; do
ftime=$((`stat -c %Z "$f" 2>/dev/null`))
if [ $ftime -lt $age_deadline ]; then to_delete+=("$f"); fi
done
done
if [ ${#to_delete[*]} -eq 0 ]; then
echo 'No old files found.'
exit 0
fi
shopt -s checkwinsize
lines=`tput lines`
if [ ${#to_delete[*]} -gt $((lines - 5)) ]; then
output_cmd=less
else
output_cmd=cat
fi
print_pending() {
echo "The following ${#to_delete[*]} file(s)/directories are old and will be deleted:"
for f in "${to_delete[@]}"; do
changed=`stat -c %Z "$f" 2>/dev/null`
age=$(((current_time - changed) / (24 * 60 * 60)))
fsize=`du -sh "$f" | awk '{ print $1 }'`
stat -c "%n [%F, $fsize], changed $age days ago" "$f" 2>/dev/null || echo "$f (??)"
done
total_size=`(du -csh "${to_delete[@]}" | tail -n 1 | cut -f1 ) 2> /dev/null`
echo "Total size: $total_size"
}
print_pending | $output_cmd
prompt='Remove all listed files? [yes/no; `list` to list again] '
while read -p "$prompt" answer; do
case ${answer,,} in
y|ye|yes)
rm -vrf "${to_delete[@]}"
exit $?
;;
n|no)
echo 'aborting.'
exit 1
;;
l|li|lis|list)
print_pending | $output_cmd
;;
*)
echo 'Invalid answer.'
;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment