Bash 脚本 - 删除所有旧的文件,但出于安全原因保留一个

Bash 脚本 - 删除所有旧的文件,但出于安全原因保留一个

我已经写了一个脚本:

#!/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

效果很好。但我现在需要更高级的方法。如您所见,它会删除目录中所有超过 3 天的文件。我有很多版本,例如:1.31.1 1.31.2 1.31.3 ...... 1.31.150 1.32.1 1.32.2

等等。我想删除主版本 1.31/1.32 中除最后一个版本之外的所有版本。怎么做?它不能是静态名称,因为有一天它会变成 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

有任何想法吗?谢谢!

答案1

以下是一种方法:

#!/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]}")

注意事项

  1. 这假设您只有 中的目录/opt/bla/myfiles
  2. 它将删除除最新版本目录之外的所有内容。

相关内容