Skip to content

Instantly share code, notes, and snippets.

@tuxerrante
Last active December 18, 2024 11:28
Show Gist options
  • Save tuxerrante/2f860ba9354a495abbb7a68e2b38350e to your computer and use it in GitHub Desktop.
Save tuxerrante/2f860ba9354a495abbb7a68e2b38350e to your computer and use it in GitHub Desktop.
This bash script is designed to help you free up disk space on an Ubuntu system by removing unnecessary packages, cleaning up the apt cache, pruning Docker resources, and identifying large user-installed packages.
#!/bin/bash
# Execute with sudo
echo "> Initial Disk space"
df -BM /
initial_size=$(df --block-size=M / | awk 'NR==2 {print $3}' | sed 's/M//')
apt-get autoremove --purge
# List kernels
echo "> Available kernels: "
dpkg -l | grep linux-image | awk '{print$2}' | wc -l
dpkg -l linux-{image,headers}-* | awk '/^ii/{print $2}' | egrep '[0-9]+\.[0-9]+\.[0-9]+' | grep -v $(uname -r | cut -d- -f-2) | xargs sudo apt-get -y purge
# Empty apt cache
apt-get clean
# Docker
# The docker system prune command removes unused images, containers, networks, and the build cache.
# Stop Docker-related services
echo "> Stopping Docker-related services"
if command -v kind &> /dev/null; then kind delete cluster; fi
if command -v minikube &> /dev/null; then minikube stop; fi
if command -v microk8s &> /dev/null; then microk8s stop; fi
docker --log-level warn system prune
# Clean Up /tmp
clean_temp_dir() {
local dir=$1
echo "> Cleaning: $dir"
# exclude system files and dirs
find "$dir" -mindepth 1 -maxdepth 1 ! -name '.ICE-unix' \
! -name '.X11-unix' \
! -name '.XIM-unix' \
! -name '.font-unix' \
! -name 'systemd-private-*' \
! -name 'snap-private-tmp' \
! -name 'VMwareDnD' \
! -name '.iprt-localipc-*' \
! -name 'vboxguest-Module.symvers' \
! -name '.X*-lock' \
-exec rm -rf {} +
}
clean_temp_dir /tmp
clean_temp_dir /var/tmp
# Get the final size of root in MB
final_size=$(df --block-size=M / | awk 'NR==2 {print $3}' | sed 's/M//')
size_difference=$((final_size - initial_size))
echo "Disk space used: $size_difference MB"
echo "> Searching for a list of big packages that seems not to be system related. Double check before removing them. "
installed_packages=$(dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -nr)
user_installed_packages=$(echo "$installed_packages" | grep -P -v '\t(lib|linux-headers|linux-)')
echo "$user_installed_packages" | awk '{print $1/1024" MB "$2}' | head -n 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment