Remove directories that start with a number

By | September 5, 2016

The linux shell script below comes in quite handy when you need to delete all folders that start with a number in a path that contains other folders you don’t want to remove.

The script contains some logic to only run as root and stop/start a service if needed. Also, I’ve included a sample crontab line to run the script automatically every Sunday at 5am.

The tricky part for me was the actual “rm” command, going from Ubuntu 11 to Ubuntu 14.04 I found that I had to tweak it to get it to run in a cron job. The new version below seems to be compatible on most linux systems.

#!/bin/ksh
#######################################################
# Cron Sample:
# 0 5 * * sun /home/user/scripts/cleanup.sh > /home/user/scripts/cleanup.log
#######################################################
export PATH=$PATH:/sbin

# Log date
echo "** Starting Cleanup **"
date

## Uncomment the following if needed
## If must be run as root
#uid=$(id -u)
#[ $uid -ne 0 ] && { echo "This script should be run as root. Exiting..."; exit 1; }
## Stop a service
#/etc/init.d/my.server stop

# REMOVE ALL FOLDERS THAT START WITH A NUMBER 0-9
# Modify the path with your own
echo "** Removing folders... **"
rm -Rfv "/home/user/stuff/"[0-9]*

# DONE
echo "** Folder cleanup completed **"

## Restart service or reboot if needed
#/etc/init.d/my.server start
#reboot

Setup:

  1. Create the actual file: vi cleanup.sh
  2. Enable insert in vi by typing letter “i” on your keyboard
  3. Copy/Paste script above and save/quit (vi command :wq)
  4. Make sure it is executable: chmod 751 cleanup.sh
  5. Run using ./cleanup.sh
  6. Optional: Run on a schedule by adding to crontab.
    crontab -e