Chill drop-in functions for your .zshrc
to make blocking sites quick and
easy.
Simply concats the host(s) you say to /etc/hosts
with a redirect to
127.0.0.1
-- shit ain't original.
Run with no args to see what's currently blocked, or n
args to block the specified sites. unblock does the obvious.
$ block facebook.com
$ block
facebook.com
$ block twitter.com reddit.com
$ block
facebook.com
twitter.com
reddit.com
$ unblock twitter.com
$ block
facebook.com
reddit.com
- Idea stolen from all over the interwebs, just couldn't find a drop-in anywhere so HERE IT IS.
block
isn't smart. If you add facebook.com twice, it will make two entries in/etc/hosts
unblock
is slightly smarter-- it will remove all duplicates and squash doubled-up empty lines
block () {
if [[ $# -eq 0 ]]; then
# no args == show list of already-blocked hosts
grep --color=never --ignore-case --extended-regexp "^##\s+block" /etc/hosts | cut -d" " -f 3-
else
# loop through hosts and block each one on ipv4 + ipv6
while (($#)); do
echo "echo \"\n## block $1\" >> /etc/hosts" | sudo sh
echo "echo \"127.0.0.1 $1 www.$1\" >> /etc/hosts" | sudo sh
echo "echo \"::1 $1 www.$1\" >> /etc/hosts" | sudo sh
echo "echo \"## /block $1\" >> /etc/hosts" | sudo sh
shift
done
fi
}
unblock () {
while (($#)); do
# remove specified hosts and squash multiple empty lines
newContents=$(sed "/## block $1/,/## \/block/d" /etc/hosts | sed '/./,/^$/!d')
echo "echo \"$newContents\" > /etc/hosts" | sudo sh
shift
done
}