Wednesday, April 27, 2016

Shell script to scan folders and delete all but the most recent ones

root@server1 [~]# cat rm-releases.sh

#!/bin/bash

DIRECTORY="releases"

for i in $(ls -l /home | grep - | awk '{print $8}'| sed 's|[/]||g'); do
#  echo ${i%%/};

  if [ -d "/home/${i%%/}/$DIRECTORY" ]; then
    TARGETDIR=$(ls -t /home/${i%%/}/$DIRECTORY | head -1)
#    echo $TARGETDIR;
    for j in $(ls -l "/home/$i/$DIRECTORY" | grep - | awk '{print $8}' | sed 's|[/]||g'); do
      if [ "$j" != "$TARGETDIR" ]; then
        echo "rm /home/$i/$DIRECTORY/${j}"
        rm -rf "/home/$i/$DIRECTORY/${j}"
      fi
    done
#    break;
  fi
done

No comments: