Skip to content

Instantly share code, notes, and snippets.

@Iman
Last active Sep 13, 2022
Embed
What would you like to do?
Free up disk space on Ubuntu - clean log, cache, archive packages/apt archives, orphaned packages, old kernel and remove the trash
#!/bin/sh
#Check the Drive Space Used by Cached Files
du -sh /var/cache/apt/archives
#Clean all the log file
#for logs in `find /var/log -type f`; do > $logs; done
logs=`find /var/log -type f`
for i in $logs
do
> $i
done
#Getting rid of partial packages
apt-get clean && apt-get autoclean
apt-get remove --purge -y software-properties-common
#Getting rid of no longer required packages
apt-get autoremove -y
#Getting rid of orphaned packages
deborphan | xargs sudo apt-get -y remove --purge
#Free up space by clean out the cached packages
apt-get clean
# Remove the Trash
rm -rf /home/*/.local/share/Trash/*/**
rm -rf /root/.local/share/Trash/*/**
# Remove Man
rm -rf /usr/share/man/??
rm -rf /usr/share/man/??_*
#Delete all .gz and rotated file
find /var/log -type f -regex ".*\.gz$" | xargs rm -Rf
find /var/log -type f -regex ".*\.[0-9]$" | xargs rm -Rf
#Cleaning the old kernels
dpkg-query -l|grep linux-im*
#dpkg-query -l |grep linux-im*|awk '{print $2}'
apt-get purge $(dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | head -n -1) --assume-yes
apt-get install linux-headers-`uname -r|cut -d'-' -f3`-`uname -r|cut -d'-' -f4`
#Cleaning is completed
echo "Cleaning is completed"
@JinnaBalu
Copy link

JinnaBalu commented Feb 11, 2021

Nice work

@Wedz0ff
Copy link

Wedz0ff commented Mar 13, 2021

It worked on Ubuntu 18.04 on DigitalOcean, ty.

@lahirusamith
Copy link

lahirusamith commented Mar 29, 2021

nice!

@1ur11
Copy link

1ur11 commented Apr 12, 2021

Ubuntu 18.04.4 works fine

@PthDE
Copy link

PthDE commented May 2, 2021

Brilliant!!
Running with 18.04 LTS. I have apps like KiCAD and PyCharm on a 34GB root file-system. Down to 6GB left clean.sh found another 5GB to clean out to give me 11GB space left.
Thanks Iman!

@chakradharchokkaku
Copy link

chakradharchokkaku commented May 8, 2021

It worked on Ubuntu 20.04. Nearly 20GB cleaned.

@neilyoung
Copy link

neilyoung commented Jun 8, 2021

thumbs up

@avinashxw
Copy link

avinashxw commented Jun 20, 2021

Great work @Iman!
Never thought the cleanup is super easy with this script.
All happened in a jiffy!

@gushauptfleisch
Copy link

gushauptfleisch commented Sep 20, 2021

Skip the step
apt-get remove --purge -y software-properties-common
Otherwise some handy steps and commands for tidying out excessive logs thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment