-
Notifications
You must be signed in to change notification settings - Fork 0
/
modify-hosts.sh
executable file
·60 lines (52 loc) · 1.41 KB
/
modify-hosts.sh
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
56
57
58
59
#!/bin/bash
# modify-hosts.sh - Script to add or remove an IP-hostname pair from /etc/hosts
#
# This is used to map a service located somewhere on localhost to a normally non-
# routable domain name ({app_name}.alafia). This makes launching the service in
# the browser and keeping track of Caddy server configuration much easier.
# Function to add the IP-hostname pair
add_entry() {
if grep -q "$ENTRY" "$HOSTS_FILE"; then
echo "Entry '$ENTRY' already exists in $HOSTS_FILE"
else
echo "$ENTRY" >> "$HOSTS_FILE"
echo "Entry '$ENTRY' added to $HOSTS_FILE"
fi
}
# Function to remove the IP-hostname pair
remove_entry() {
if grep -q "$ENTRY" "$HOSTS_FILE"; then
sed -i "/$ENTRY/d" "$HOSTS_FILE"
echo "Entry '$ENTRY' removed from $HOSTS_FILE"
else
echo "Entry '$ENTRY' does not exist in $HOSTS_FILE"
fi
}
# Ensure the script is run with superuser privileges
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" 1>&2
exit 1
fi
# Ensure exactly three arguments are provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <ip-address> <hostname> <add|remove>" 1>&2
exit 1
fi
IP_ADDRESS=$1
HOSTNAME=$2
COMMAND=$3
HOSTS_FILE="/etc/hosts"
ENTRY="$IP_ADDRESS $HOSTNAME"
# Determine whether to add or remove the entry
case $COMMAND in
add)
add_entry
;;
remove)
remove_entry
;;
*)
echo "Invalid command: $COMMAND. Use 'add' or 'remove'." 1>&2
exit 1
;;
esac