Bash Script Hosts file Ad Blocker

Put in cron or run manually.


# If this is our first run, save a copy of the system's original hosts file and set to read-only for safety
if [ ! -f /etc/hosts.bak ]
 echo "Saving copy of system's original hosts file..."
 sudo cp /etc/hosts /etc/hosts.bak
 sudo chmod 444 /etc/hosts.bak

# Perform work in temporary files

# Obtain various hosts files and merge into one
echo "Downloading ad-blocking hosts files..."
wget -nv -O - > $temphosts1
wget -nv -O - >> $temphosts1
wget -nv -O - >> $temphosts1
wget -nv -O - "" >> $temphosts1

# Do some work on the file:
# 1. Remove MS-DOS carriage returns
# 2. Delete all lines that don't begin with
# 3. Delete any lines containing the word localhost because we'll obtain that from the original hosts file
# 4. Replace with because then we don't have to wait for the resolver to fail
# 5. Scrunch extraneous spaces separating address from name into a single tab
# 6. Delete any comments on lines
# 7. Clean up leftover trailing blanks
# Pass all this through sort with the unique flag to remove duplicates and save the result
echo "Parsing, cleaning, de-duplicating, sorting..."
sed -e 's/\r//' -e '/^!d' -e '/localhost/d' -e 's/' -e 's/ \+/\t/' -e 's/#.*$//' -e 's/[ \t]*$//' < $temphosts1 | sort -u > $temphosts2

# Combine system hosts with adblocks
echo Merging with original system hosts...
echo -e "\n# Ad blocking hosts generated "`date` > $temphosts4
cat /etc/hosts.bak $temphosts4 $temphosts2 > $temphosts3
sudo cp $temphosts3 /etc/hosts

# Clean up temp files and remind user to copy new file
echo "Cleaning up..."
rm $temphosts1 $temphosts2 $temphosts3 $temphosts4
echo "Done."
echo "You can always restore your original hosts file with this command:"
echo " sudo cp /etc/hosts.bak /etc/hosts"
echo "so don't delete that file! (It's saved read-only for your protection.)"

, , , ,

Comments are closed.

Powered by recycled bites and bytes.