-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhostfile
More file actions
52 lines (41 loc) · 1.12 KB
/
Copy pathhostfile
File metadata and controls
52 lines (41 loc) · 1.12 KB
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
#!/bin/bash
HOSTS_FILE="/etc/hosts"
# Usage
show_help() {
echo "Usage:"
echo " hostfile <IP> <DOMAIN> [ADDITIONAL_DOMAINS...]"
echo " hostfile -R <DOMAIN> (Remove entry for domain)"
echo " hostfile -h | --h | --help (Show this help message)"
exit 0
}
# at least one argument is provided
if [ "$#" -lt 1 ]; then
show_help
fi
# display help
if [[ "$1" == "-h" || "$1" == "--h" || "$1" == "--help" ]]; then
show_help
fi
# removal mode
if [ "$1" == "-R" ]; then
if [ -z "$2" ]; then
echo "Usage: hostfile -R <DOMAIN>"
exit 1
fi
DOMAIN_TO_REMOVE="$2"
# Ensure sudo is used to modify /etc/hosts
sudo sed -i "/\s$DOMAIN_TO_REMOVE$/d" "$HOSTS_FILE"
echo "Removed entry for $DOMAIN_TO_REMOVE from $HOSTS_FILE"
exit 0
fi
# addition mode
IP="$1"
shift # Remove IP from arguments list
# remove the existing entries from provided domains
for DOMAIN in "$@"; do
# Ensure sudo is used to modify /etc/hosts
sudo sed -i "/\s$DOMAIN$/d" "$HOSTS_FILE"
done
# append new entries
echo "$IP $*" | sudo tee -a "$HOSTS_FILE" > /dev/null
echo "Updated $HOSTS_FILE with: $IP $*"