-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblock-website
executable file
·55 lines (50 loc) · 1.4 KB
/
block-website
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/bash
# For easily blocking websites through /etc/hosts
# Example:
# block reddit.com old.reddit.com # Block old.reddit.com and www.reddit.com
# block -u reddit.com # Unblock both subdomains (based on suffix)
function block-host {
HOST="$1"
if grep -q "^#\?\s*0.0.0.0\s*[[:alnum:]]*\.\?$HOST" /etc/hosts; then
echo "Uncommenting \*$HOST in /etc/hosts..."
sudo sed -i "s/^#\s*\(0.0.0.0\s*[[:alnum:]]*\.\?$HOST\)\s*$/\1/g" /etc/hosts
else
NUMBER_OF_DOTS="$(echo "$HOST" | tr -d -c '.' | wc -m)"
if [ $NUMBER_OF_DOTS -eq 0 ]; then
echo "$HOST is not a domain"
HOST=""
else
if [ $NUMBER_OF_DOTS -eq 1 ]; then
HOST="www.$HOST"
fi
echo "Adding $HOST to /etc/hosts..."
sudo tee -a /etc/hosts <<< "0.0.0.0 $HOST"
fi
fi
}
function unblock-host {
HOST="$1"
echo "Commenting \*$HOST in /etc/hosts..."
sudo sed -i "s/^\s*\(0.0.0.0\s*[[:alnum:]]*\.\?$HOST\)\s*$/#\1/g" /etc/hosts
}
BLOCK=true
HOSTS=( )
for ARG in "$@"; do
case $ARG in
-u|--unblock)
BLOCK=false
;;
*)
HOSTS+=( "$ARG" )
;;
esac
done
for HOST in "${HOSTS[@]}"; do
if [ ! -z "$HOST" ]; then
if [ "$BLOCK" = true ]; then
block-host "$HOST"
else
unblock-host "$HOST"
fi
fi
done