Ubuntu: Bash script - delete all files older than, but leave one for safety reasons



Question:

I've got written a script:

#!/bin/bash  dir=/opt/bla/myfiles  # Check disk usage usep=$(df -H | grep /dev/sda3 | awk '{print $5}' | cut -d '%' -f1)   if [ $usep -ge 90 ]; then      echo "$(date) Running out of space in /dev/sda3 with $usep percent - so deleting action is taking!" >> /var/log/messages &&          find $dir/releases/* -mtime +3 -exec rm {} \; else          echo "$(date) Disk space is $usep percent - no action required!" /var/log/messages   fi  

which works great. But I need more advanced method now. As you can see it deletes all the files in dir older than 3 days. I've got a lot of releases, for example: 1.31.1 1.31.2 1.31.3 ...... 1.31.150 1.32.1 1.32.2

and so one. I want to delete all releases except the last one from major build 1.31/1.32. How to? It can't be a static name, because one day it would be 2.32.150

ls -l  total 520  drwxr-xr-x 2 jenkins jenkins 4096 Jun 23 15:45 0.0.31-SNAPSHOT  drwxr-xr-x 2 jenkins jenkins 4096 Jun 23 15:45 1.33.0.100-RELEASE  drwxr-xr-x 2 jenkins jenkins 4096 Jun 23 15:45 1.33.0.101-RELEASE  drwxr-xr-x 2 jenkins jenkins 4096 Jun  8 11:00 1.33.0.58-RELEASE  drwxr-xr-x 2 jenkins jenkins 4096 Jun  8 11:00 1.33.0.59-RELEASE  drwxr-xr-x 2 jenkins jenkins 4096 Jun  8 11:00 1.33.0.64-RELEASE  drwxr-xr-x 2 jenkins jenkins 4096 Jun  8 11:00 1.33.0.66-RELEASE  

Any ideas, thanks!


Solution:1

Here's one way:

#!/bin/bash    targetDir=/opt/bla/myfiles;  ## declare 'releases' as an associative array  declare -A releases  cd "$targetDir"  ## Iterate over all directories in $targetDir.   for dir in */; do          ## remove the trailing slash          dir="${dir%/}"          ## Extract the version string          ver="${dir%%-*}"            ## Use the version as the key for the associative array           releases["$ver"]="$dir";  done  ## Get the newest version; sort -h understands version numbers  newestVersion=$( printf '%s\n' "${!releases[@]}" | sort -h | tail -n1)  ## This is probably not needed as extended globbing should be on by default  shopt -s extglob  ## Delete the rest. The '$targetDir/' isn't necessary but it's safer  ## just in case we're not actually where we think we are.   rm -rf  $targetDir/!("${releases[$newestVersion]}")  

Caveats:

  1. This assumes you only have directories in /opt/bla/myfiles.
  2. It will delete everything but the directory of the newest version.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »