How to remove GUI Desktop from Ubuntu 16.04 or 18.04

I installed Ubuntu Server with Desktop support that I almost never use. Also using GUI is both resource damanding and can be a security issue. This is why I decided to completely remove it from my server.

This is how to do it.

sudo apt-get -y purge ubuntu-desktop
sudo apt-get -y purge unity gnome-shell lightdm
sudo apt-get -y remove ubuntu-desktop
sudo apt purge ubuntu-desktop -y && sudo apt autoremove -y && sudo apt autoclean
sudo apt-get -y clean
sudo apt-get -y autoremove
sudo apt-get -f install

However if you need to install it again just run the following command:

sudo apt-get install ubuntu-desktop