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.

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
Loading