Created
January 6, 2014 20:32
-
-
Save jamesharr/8289378 to your computer and use it in GitHub Desktop.
Script for managing ~/Downloads. Works relatively well, though it sometimes misses things.
This file contains 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
#!/bin/bash | |
# Keep Downloads folder clean on a mac using xattr to track age. | |
# Normally, stick something like this in your crontab. It's pretty quick | |
# and not I/O intentisve, so I run every hour on some random time. | |
# | |
# Example crontab: | |
# 37 * * * * LOGME=1 /Users/james/bin/tmpclean-mac.sh /Users/james/Downloads 7 | |
dir="$1" | |
age="$2" | |
if [ -z "$dir" ] || [ -z "$age" ]; then | |
exec 1>&2 | |
echo | |
echo "Usage: $0 DIR AGE" | |
echo | |
echo " Delete things in DIR that are older than AGE days, unless:" | |
echo " - They have been accessed AGE days ago [if they're a file]" | |
echo " - Files inside them have been accessed <AGE days ago [if they're a dir]" | |
echo | |
exit 1 | |
fi | |
if [ -n "$QUIET" ]; then | |
exec 1>/dev/null | |
exec 2>/dev/null | |
fi | |
if [ -n "$LOGME" ]; then | |
logfile="$dir/.clean-log.$(date +%Y%m%d.%H%M)" | |
exec 1>>$logfile | |
exec 2>>$logfile | |
fi | |
ATTR=org.grickle.tmpclean.first-seen | |
NOW=$(date +%s) | |
CUTOFF=$(( $NOW - $age * 3600 * 24 )) | |
set -e | |
cd "$dir" | |
ls -A | while read file; do | |
if xattr -l "$file" | grep -q "$ATTR"; then | |
first_seen=$(xattr -p "$ATTR" "$file") | |
recent=$(find "$file" -type f -atime +"$age"d) | |
if [ "$first_seen" -lt "$CUTOFF" -a -n "$recent" ]; then | |
echo "Deleting: $file" | |
rm -fr "$file" | |
else | |
reason="" | |
[ "$first_seen" -ge "$CUTOFF" ] && reason="xattr $reason" | |
[ -z "$recent" ] && reason="atime $reason" | |
echo "Not stale: $file. Reason $reason" | |
fi | |
else | |
echo "New file: $file" | |
xattr -w "$ATTR" "$NOW" "$file" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment