First, let's make the script executable:
chmod +x block-etc-hosts.sh
To start blocking:
sudo block-etc-hosts.sh block
To stop blocking:
sudo block-etc-hosts.sh unblock
To stop blocking for a while (in minutes):
sudo block-etc-hosts.sh 10
There's also a couple launch daemons for macOS, to automatically block during workdays. Put them in /Library/LaunchDaemons, make sure you change /path/to/block-etc-hosts.sh
and the StartCalendarInterval
property to suit your preferences, then:
sudo chown root:wheel /Library/LaunchDaemons/*-etc-hosts.plist
sudo launchctl load /Library/LaunchDaemons/block-etc-hosts.plist
sudo launchctl load /Library/LaunchDaemons/unblock-etc-hosts.plist
The equivalent cronjobs would be:
30 8 * * MON-FRI /path/to/block-etc-hosts.sh block
30 18 * * MON-FRI /path/to/block-etc-hosts.sh unblock
Launch daemons have the advantage that they eventually run, even if the computer is off or suspended at the scheduled time.