Automatically delete files older than 3 hours macOS
Here is an example find
command that you can modify to suit your needs:
find '/path/to/files/' -type f -name '*.jpg' -mmin +180 -delete
I'd use launchd
to run it every 3 hours.
Here is an example .plist
file that will run the find
command every 3 hours using launchd
:
<?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>com.my.delete.every.three.hours</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/find</string>
<string>/path/to/files/</string>
<string>-type</string>
<string>f</string>
<string>-name</string>
<string>*.jpg</string>
<string>-mmin</string>
<string>+180</string>
<string>-delete</string>
</array>
<key>RunAtLoad</key>
<false/>
<key>StartInterval</key>
<integer>10800</integer>
</dict>
</plist>
It would be saved in: $HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist
From Terminal:
touch "$HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist"
open -e "$HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist"
- Copy and paste example XML code into the opened TextEdit document:
- Modify as needed:
- E.g. Change
/path/to/files/
to the actual path. - E.g. Change
*.jpg
to the proper extension if not:jpg
- E.g. Change
- Save and close the document.
Continue in Terminal, to load the plist
file:
launchctl load "$HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist"
To stop
and unload
the "$HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist"
file use:
launchctl stop "$HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist"
launchctl unload "$HOME/Library/LaunchAgents/com.my.delete.every.three.hours.plist"