Skip to content

Instantly share code, notes, and snippets.

@jpralves
Last active January 30, 2019 23:23
Show Gist options
  • Save jpralves/7741d6629a8f04c586aedab0a1980435 to your computer and use it in GitHub Desktop.
Save jpralves/7741d6629a8f04c586aedab0a1980435 to your computer and use it in GitHub Desktop.
Clean VM for compacting
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "Please run as root or sudo"
exit 1
fi
set -e
if [ -f /etc/os-release ]; then
source /etc/os-release
echo "Detected OS: $NAME $VERSION"
else
ID="Unkonwn"
fi
case "$ID" in
manjaro) CLEANCMD='yes | pacman -Scc'
;;
ubuntu|debian) CLEANCMD='apt clean all && rm -f /var/lib/apt/lists/* || true'
;;
fedora|centos|rhel) CLEANCMD="yum --enablerepo='*' clean all && rm -rf /var/cache/yum"
;;
*) echo "don't know how to clean: $ID"
CLEANCMD=''
;;
esac
if [ ! -z "$CLEANCMD" ]; then
echo "Remove Cached Packages..."
eval $CLEANCMD
fi
echo "Removing temporary files"
rm -rf /var/tmp/*
rm -rf /tmp/*
df -l --output=target,fstype | grep -v tmpfs | grep -v /run/media/ | sed '1d' | cut -f 1 -d' ' | while IFS= read -r line
do
preavail=$(df -k --output=avail "$line" | sed 1d)
echo "Zeroing $preavail Kbytes from $line"
dd if=/dev/zero of="${line}BIGFILE" bs=1M status=none 2>/dev/null || true
sync
rm -f "${line}BIGFILE"
done
cut -f 1 -d' ' </proc/swaps | sed 1d | while IFS= read -r line
do
echo "Clearing $line Swap"
swapoff "$line"
dd if=/dev/zero of="$line" bs=1M status=none 2>/dev/null || true
mkswap "$line"
swapon "$line"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment