List old, new directories

Example

Remove old directories which are stored more than 20 days

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

But beware: parsing ls 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

Remove all but except 3 newest directories

Note: tail 4 instead of 3

        for some_dir not in $( ls $FILE_SERVER -td | tail -n +4 ); do
            echo "Removing $some_dir"
            rm -rf $some_dir
        done
Loading