Auto Archive And Delete Folders Inside A Watch Folder - Wiki wiki page

How to auto archive and delete folders inside a watch folder


The script attached to this page has the ability to delete folders, incorrect configuration may cause damage to your operating system.

This page describes watching a folder (watch folder), periodically compressing all folders within the watch folder, then deleting the folder after compression. Will also update (not replace) existing compressed files with new content if a folder is re-added.

Example:

before:

$ ls -lt .

drwxrwxrwx 0 johnsmith johnsmith 512 Feb  4 12:44 folder1
drwxrwxrwx 0 johnsmith johnsmith 512 Feb  4 12:44 folder2


after:

$ ls -lt .

-rwxrwxrwx 1 johnsmith johnsmith 59858 Feb  4 12:45 folder1.zip
-rwxrwxrwx 1 johnsmith johnsmith 59858 Feb  4 12:45 folder2.zip

Archive script

  1. Copy the following script to: ~/scripts/archive.sh:

    #!/bin/bash
    FOLDER=$1
    cd $FOLDER && find . ! -path . -type d -exec zip -r -u '{}'.zip '{}' \; && find . -maxdepth 1 ! -path . -type d -exec rm -r '{}' \; && cd -
    
  2. Allow the script to be executable: chmod +x ~/scripts/archive.sh

Adding job to crontab

  1. To use cron for tasks meant to run only for your user profile, add entries to your own user's crontab file. To edit the crontab file enter: crontab -e

  2. Add the following crontab line to the end of the file and save:

    */15 * * * * /home/hd_xx/your_user_name/scripts/archive.sh /home/hd_xx/your_user_name/path_to_watch_folder
    
  3. Replacing the following variables in crontab line above:

    hd_xx:                   replace with your hard drive                    e.g.: hd7
    your_user_name:          replace with your user name                     e.g.: johnsmith
    path_to_watch_folder:    replace with the path to the folder to watch    e.g.: media/Audiobooks
    

Examples, run:

  • every 15 minutes:

    */15 * * * * /home/hd7/johnsmith/scripts/archive.sh /home/hd7/johnsmith/media/Audiobooks
    
  • every 30 minutes:

    */30 * * * * /home/hd7/johnsmith/scripts/archive.sh /home/hd7/johnsmith/media/Audiobooks
    
  • every 2 hours:

    */2 * * * /home/hd7/johnsmith/scripts/archive.sh /home/hd7/johnsmith/media/Audiobooks
    
  • at midnight:

    0 0 * * * /home/hd7/johnsmith/scripts/archive.sh /home/hd7/johnsmith/media/Audiobooks
    

Last Author Contributors Versions Last update
speechless 2 Sun, 04 Feb 2018 17:48:11 +0100