Hosts files are great

No votes yet.
Please wait...

If you have a computer, a hosts file is an absolute must. These handy files located where most system type files are kept can be used to prevent unwanted malware, ads, and other sites from attacking your computer.

The folks at have created a fine database source for maintaining and installing a hosts file for most operating systems. I strongly suggest checking it out.

On Linux, they created a python script for updating the hosts file. I in turn decided to create my own updating script using bash. Mainly as an exorcise in writing it. So here is my hosts file update script for Linux written in the bash shell.

# hosts file updating script
# writen by bynw anlarye
# November 2016

# function to merge new hosts file into the system
mergehosts ()
mv /etc/hosts /etc/hosts.backup.$(date +"%Y%m%d")
mv hosts /etc/hosts

# script needs root access
if [[ $EUID -ne 0 ]]; then
echo "This script needs to be ran by root or with sudo"
exit 1

# downloads latest version of main hosts file
while :
echo "  Menu Options  "
echo ""
echo "[A] - The master hosts file"
echo "[B] - The master hosts file + gambling sites"
echo "[C] - The master hosts file + porn sites"
echo "[D] - The master hosts file + social media sites"
echo "[E] - The master hosts file + gambling & porn sites"
echo "[F] - The master hosts file + gambling & social media sites"
echo "[G] - The master hosts file + porn & social media sites"
echo "[H] - All hosts file sites"
echo "[X] - Exit Script"
echo ""
read -p "Please choose one of the above options [A-H or X] and press [ENTER]: " whichhosts
case $whichhosts in
a|A) wget -q --no-clobber
break ;;
b|B) wget -q --no-clobber
break ;;
c|C) wget -q --no-clobber
break ;;
d|D) wget -q --no-clobber
break ;;
e|E) wget -q --no-clobber
break ;;
f|F) wget -q --no-clobber
break ;;
g|G) wget -q --no-clobber
break ;;
h|H) wget -q --no-clobber
break ;;
x|X) echo
echo "Host file will not be updated"
exit 1 ;;
*) sleep 1
echo "Invalid responce."
echo "Please choose from [A-H or X]"
sleep 1 ;;

# adds user defined custom hosts to file
sed -i '/Custom host records are listed here/r myhosts' hosts

# checks for existance of whitelist
if [ -f whitelist ]
grep -Fvxf whitelist hosts > hosts.tmp
mv hosts.tmp hosts

echo "Hosts file has been updated"

exit 1

Author: bynw

Chris aka "bynw" is the site owner and primary post author. A life-long conservative Constitutionalist when it comes to politics. A believer and follower of Jesus Christ. A Linux enthusiast. And a gamer.