Skip to content

Instantly share code, notes, and snippets.

@kccqzy
Last active September 12, 2023 06:01
Show Gist options
  • Save kccqzy/8dbead563afdcd6a491a to your computer and use it in GitHub Desktop.
Save kccqzy/8dbead563afdcd6a491a to your computer and use it in GitHub Desktop.
This gist cleans your OS X trash by permanently removing items trashed more than X days ago
#!/usr/bin/env osascript -l JavaScript
var numDaysToKeep = 20;
var now = $.NSDate.date;
console.log("Now:", now.description.js);
var deleteThreshold = now.dateByAddingTimeInterval(-86400 * numDaysToKeep);
console.log("Will delete items whose date added is earlier than", deleteThreshold.description.js);
var urlPath = $.NSURL.alloc.initFileURLWithPathIsDirectory($('~/.Trash').stringByExpandingTildeInPath, true);
var fm = $.NSFileManager.defaultManager;
var urlContents = fm.contentsOfDirectoryAtURLIncludingPropertiesForKeysOptionsError(urlPath, ["NSURLAddedToDirectoryDateKey"], $.NSDirectoryEnumerationSkipsHiddenFiles, null).js;
urlContents.forEach(function (url) {
var date = $();
url.getResourceValueForKeyError(date, "NSURLAddedToDirectoryDateKey", null);
console.log("Found file", url.fileSystemRepresentation, "with date added =", date.description.js);
if (date.compare(deleteThreshold) === $.NSOrderedAscending) {
console.log("Will delete", url.fileSystemRepresentation);
fm.removeItemAtURLError(url, null);
} else {
console.log("Will keep", url.fileSystemRepresentation);
}
});
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>st.qzy.cleantrash</string>
<key>ProcessType</key>
<string>Background</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/cleantrash</string>
</array>
<key>StandardErrorPath</key>
<string>/path/to/cleantrash/output</string>
<key>StandardOutPath</key>
<string>/path/to/cleantrash/output</string>
<key>RunAtLoad</key>
<true/>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>0</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment