andreafrancia / trash-cli

Command line interface to the freedesktop.org trashcan.
GNU General Public License v2.0
3.62k stars 177 forks source link

Add option to preserve folders containing recently modified files #337

Open 8ullyMaguire opened 6 months ago

8ullyMaguire commented 6 months ago

It would be helpful to have an option to preserve folders that contain files or subfolders modified within the specified number of days.

This feature would allow users to automatically remove old trash while keeping folders that contain recently modified content. It could be implemented as an additional flag or option to the trash-empty command.

This is what I'm doing currently:

I want to automatically and permanently remove files and folders from the trash in Manjaro Linux that have not been modified for a specified number of days, while preserving folders containing recently modified subfolders or files.

Based on this Unix StackExchange answer I've thought of using a combination of the find command on a script and a cron job.

Here's a script that I've wrote as the file $HOME/bin/clean_trash.sh and made it executable with chmod +x clean_trash.sh:

#!/bin/bash

# Set the trash directory
TRASH_DIR="$HOME/.local/share/Trash"

# Set the number of days after which files/folders should be deleted
DAYS_TO_KEEP=30

# Find and delete files/folders older than DAYS_TO_KEEP, excluding directories with recently modified content
find "$TRASH_DIR" -mindepth 1 -maxdepth 1 -type d -mtime +$DAYS_TO_KEEP -exec bash -c '
  for entry; do
    if ! find "$entry" -mindepth 2 -mtime -'"$DAYS_TO_KEEP"' -print -quit | grep -q .; then
      rm -rf "$entry"
    fi
  done
' _ {} +

I can then run the script manually from anywhere if the bin directory is in the $PATH or set up a cron job to run it automatically at a specified interval.

To set up a cron job, I've opened the crontab editor with crontab -e and added a line like the following:

@daily $HOME/bin/clean_trash.sh

This will run the clean_trash.sh script daily.