Blocking advert sites using /etc/hosts

Using the approach to blocking adverts is nothing new, but sometimes in the course of testing something, I do actually need to see if adverts and ad pop-ups are working correctly. So I do this…

Download the hosts file and unzip it somewhere suitable
Copy the current /etc/hosts file
Use a script to flip between the two

sudo chown root:root Hosts
sudo chmod 644 Hosts
sudo mv Hosts /usr/local/etc/hosts.block
sudo cp /etc/hosts /usr/local/etc/hosts.base

sudo vi /usr/local/bin/hosts
# Simple script to replace /etc/hosts with either a list of blocked
# hosts, or a simple list

case $1 in
    sudo rm /etc/hosts
    sudo cp /usr/local/etc/hosts.base /etc/hosts
    sudo sh -c 'cat /usr/local/etc/hosts.block >> /etc/hosts'
    sudo rm /etc/hosts
    sudo cp /usr/local/etc/hosts.base /etc/hosts
    echo "Usage: hosts block|noblock"

sudo chmod +x /usr/local/bin/hosts

If those permissions work as intended, you should be able to switch between blocking and non-blocking mode with ‘sudo hosts block’ and ‘sudo hosts noblock’.

The only issue seems to be that you have to copy /etc/hosts over /usr/local/etc/hosts.base if you make any changes to it. But for most people that doesn’t happen very regularly. Probably just regularly enough to forget to copy it over to the base file and lose the new entries…

Hope it helps someone, with its flaws.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>