Skip to content

Instantly share code, notes, and snippets.

@dicksontsai
Created December 7, 2020 09:14
Show Gist options
  • Select an option

  • Save dicksontsai/cce96aeebe7c909ee794e42b88ca2c74 to your computer and use it in GitHub Desktop.

Select an option

Save dicksontsai/cce96aeebe7c909ee794e42b88ca2c74 to your computer and use it in GitHub Desktop.
Website-Blocking Timer on MacOS
# Programming Life Hacks #1: Website-Blocking Focus Timer
# Copyright (c) 2020 Dickson Tsai
# Follow along on my Youtube: https://youtu.be/kCo9DAuLGX4
# Disclaimer: This file is primarily for teaching purposes.
# 1. USE THIS SOLUTION AT YOUR OWN RISK. sudo is always risky to use.
# 2. Not the most idiomatic bash/zsh, but it works for me.
# General procedure
# 1. Setup website blocking
# - We will edit /etc/hosts to route websites back to our computer.
# - Provide your copy in ./unprod_hosts.
# 2. Count 30 minutes
# 3. Tear down website blocking
# 4. Notify the user
# Key insight:
# /etc/hosts is a file. You can manipulate it as with any other file (cp, mv, etc.).
# Make sure this file does not exist. Use `ls -a` to view hidden files (files
# that start with ".", like ".real_hosts").
REAL_HOSTS_TEMP=./.real_hosts
# Make sure you have a file unprod_hosts in the same directory as this script.
UNPROD_HOSTS=./unprod_hosts
# Use a variable for /etc/hosts so all code references use the same definition.
ETC_HOSTS=/etc/hosts
echo "Setting up focus timer"
if [ -f $REAL_HOSTS_TEMP ]; then
echo "Focus timer already active???"
exit 1
fi
if [ ! -f $UNPROD_HOSTS ]; then
echo "Please provide an $UNPROD_HOSTS file"
exit 1
fi
echo "Replacing $ETC_HOSTS file with $UNPROD_HOSTS"
# sudo not needed for reading /etc/hosts.
# root has read and write permissions. user (you) only have read permissions.
# -rw-r--r-- 1 root wheel 659B ... /etc/hosts
cp $ETC_HOSTS $REAL_HOSTS_TEMP
# sudo is needed for writing to /etc/hosts from your account.
sudo cp $UNPROD_HOSTS $ETC_HOSTS
# What happens if my new /etc/hosts doesn't do anything?
# 1. Try restarting your browser.
# 2. Not recommended: Try clearing your DNS cache:
# sudo dscacheutil -flushcache
echo "Starting focus timer"
for i in {30..1}
do
echo "$i minutes remaining"
sleep 60
done
echo "Reverting $ETC_HOSTS file back to the original"
# Send notification to MacOS
# You may need to type in your password again. Add that to the message body.
osascript -e 'display notification "Congratulations! Your focus timer is up. Visit the terminal to check your hosts file." with title "Focus Timer Complete" sound name "Glass"'
sudo cp $REAL_HOSTS_TEMP $ETC_HOSTS
rm $REAL_HOSTS_TEMP
# Further ideas
# 1. Interrupt handling, to end the timer early but safely.
# 2. Command line flags for adjusting the duration.
# 3. Notifications to encourage you to keep focusing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment