Search code examples
bashshellbatch-processingrm

Batch removal (rm -rf) just for existing directories in a subdirectory


Background: I have written a very simple backup removal script which should delete backups that are older than three version updates. This works by always adding the newly installed version of my software (Ghost CMS) to a txt file and all versions are located in the same directory ($GHOSTDIR/versions/3.x.y).

            nol=$(grep -c . ghostupgradehistory.txt)
            rl=$(echo "$(($nol-3))")
            lc=$(head -$rl ghostupgradehistory.txt)
            kv=$(tail -3 ghostupgradehistory.txt)
            dir=$(ls $GHOSTDIR/versions -d $lc 2> /dev/null)
            if [[ ${dir[@]} ]]; then echo "Delete old versions" && echo $dir && echo "Keep last three versions" && echo $kv
            cd $GHOSTDIR/versions && rm -rf $dir
            fi

ghostupgradehistory.txt looks like this

3.37.1
3.38.0
3.38.1
3.38.2

The problem I have is the last command for the removal of the identified outdated versions. Instead of just deleting those it deletes the whole $GHOSTDIR/versions folder which includes even the latest version. How to fix this?


Solution

  • There can be simple workaround, if you are sure having only directories with version names in the your GHOSTDIR.

    First you list all directories reversed to have the newest versions on the top, then you tail the output starting on line 4. It means the 3 newest remain hidden. Finally remove them.

    ls you can modify to sort by time -t, if it's more relevant or kept alphabetical sort.

    cd $GHOSTDIR
    ls -1rd */ | tail +4 | xargs rm -rf
    

    or (on some builds)

    cd $GHOSTDIR
    ls -1rd */ | tail -n +4 | xargs rm -rf
    

    That's it. Max 3 directories remain.