List old, new directories

Examples

Remove old directories which are stored more than 20 days

Using find tool

cd /opt/mydir

FILE_SERVER=/opt/my_file_server
# Need at least 17GB x 2
NEED_FREE=$((17224314*2))
FREE_SPACE=$(df -k --output=avail $FILE_SERVER | tail -1 | awk '{print $1}')

echo "INFO: Check if free space can not store more than 2 x 17GB"
if (( $FREE_SPACE < $NEED_FREE )); then
    echo "INFO: Free sapce is not enough"
        # CHANGE HERE
    echo "INFO: Finding old directories which are stored more than 20 days"
        for some_dir in $( find $FILE_SERVER -maxdepth 1 -type d -name 'DIR_NAME*' -mtime +20 | sort ); do
            echo "Removing $some_dir"
            rm -rf $some_dir
        done
        # CHANGE END
  else
    echo "INFO: Free sapce is enough"
fi

Using ls tool

But beware: parsing ls command can be dangerous when the filenames contain funny characters like newlines or spaces.

Read more: http://mywiki.wooledge.org/ParsingLs

Remove 3 oldest directories

        for some_dir in $( ls $FILE_SERVER -td | tail -n 3 ); do
        # for some_dir in $( find $FILE_SERVER -maxdepth 1 -type d | sort | head -3 ); do
            echo "Removing $some_dir"
            rm -rf $some_dir
        done

Remove 3 newest directories

        for some_dir not in $( ls $FILE_SERVER -td | head -3 ); do
        # for some_dir not in $( find $FILE_SERVER -maxdepth 1 -type d | sort -r | head -3 ); do
            echo "Removing $some_dir"
            rm -rf $some_dir
        done

Keep 3 newest directories, remove all the rest
Note: it's +4, instead of 3

    ls -t | tail -n +4 | xargs rm --

or

Note: it's +5, instead of 3. We have to add 2 into number of directories to be kept.

find . -maxdepth 1 -type d -printf '%T@t%p' |
sort -z -nrk1 |
tail -z -n +5 |
cut -z -f2- |
xargs -0 rm -f --

REF: https://stackoverflow.com/questions/26765163/delete-all-files-except-the-newest-3-in-bash-script

Loading