Automation to delete files from folder older than x days

I have been having issues with this ever sense I switched to HASS OS from a raspbian based install.
Here is what I did to get it to work.
Add this to your configration.yaml

shell_command:
  erase_video: find /path/to/media -mtime +6 -exec rm -fr {} +

The above shell command will search in which ever folder/directory you specify for any files which have a created date more than 6 days in the past…ie, 7 days, then it will execute remove (rm) command on those files returned by the find command.

Restart HASS
create an automation with time as the trigger. I did 12:00 am.

for the action, choose call service.
The service will be shell_command.erase_video (assuming you kept it the same name).

Now every 12:00am, the automation runs and the files older than 7 days are deleted.

While HASS OS does have crontab abilities, it isn’t the easiest thing to add too…at least for me…I tried and found this a little easier to implement.

8 Likes

Does it also search in subfolders or just in the main one?

I believe it will also search in subfolders.
I took this from a Linux command that at one point had a maxdepth option appended, but it wouldn’t work with that on there.
Maybe a little tweaking is needed to define how deep in your folder structure it will go if you don’t want it to go into subfolders. It may actually delete folders that are older than the specified time period.

if you want to limit the subfolders you can add -maxdepth 1 to you command