Skip to content

Instantly share code, notes, and snippets.

@senko
Last active November 13, 2023 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save senko/0a64d853411e481dd5968cb5df8b2362 to your computer and use it in GitHub Desktop.
Save senko/0a64d853411e481dd5968cb5df8b2362 to your computer and use it in GitHub Desktop.
Clean ~/Downloads and ~/Pictures/Screenshots on Linux - remove old files and empty directories
#!/bin/bash
#
# Written by Senko Rasic <senko@senko.net> and released unto Public Domain.
#
# Save this to ~/.local/bin/clean-transient-folders. Then add it to
# your user crontab with a rule like this:
#
# # Run this every day at 5am
# 0 5 * * * /home/<user>/.local/bin/clean-transient-folders
#
# Alternatively, set up a systemd timer:
#
# First, create a service unit file called
# ~/.config/systemd/user/clean-transient-folders.service that looks
# like this:
#
# [Unit]
# Description=Clean Transient Folders
#
# [Service]
# ExecStart=%h/.local/bin/clean-transient-folders
#
# Then, create a timer file called
# ~/.config/systemd/user/clean-transient-folders.timer that looks
# like this:
#
# [Unit]
# Description=Clean Transient Folders Timer
#
# [Timer]
# OnCalendar=hourly
# Unit=clean-transient-folders.service
#
# [Install]
# WantedBy=default.target
#
# (Adjust paths and timer intervals as needed)
# Stop immediately if there are any errors
set -e
# Directories to clean up, space-separated
DIRS="$HOME/Downloads $HOME/Pictures/Screenshots"
# Files older than 6 days will be removed
TTL=6
for DIR in $DIRS; do
# This is used to prevent the directory from being completely
# empty and thus appearing in the empty directories list later.
touch "$DIR/.last-clean"
# Find and remove files older than 6 days
find "$DIR" -type f -mtime "+${TTL}" -delete
# Find and remove empty directories
find "$DIR" -type d -empty -delete
done
@senko
Copy link
Author

senko commented Nov 4, 2023

Updated so it can work on multiple directories (see $DIRS).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment