BASH
Automate Local Domain Management in /etc/hosts
Streamline your web development workflow by automating the addition and removal of custom local domain entries in your `/etc/hosts` file using a simple bash script.
#!/bin/bash
HOSTS_FILE="/etc/hosts"
IP_ADDRESS="127.0.0.1"
DOMAIN="mylocalapp.test"
# Function to add a host entry
add_host_entry() {
if ! grep -q "$IP_ADDRESS\s*$DOMAIN" "$HOSTS_FILE"; then
echo "Adding $DOMAIN to $HOSTS_FILE..."
echo "$IP_ADDRESS $DOMAIN" | sudo tee -a "$HOSTS_FILE" > /dev/null
echo "$DOMAIN added successfully."
else
echo "$DOMAIN already exists in $HOSTS_FILE."
fi
}
# Function to remove a host entry
remove_host_entry() {
if grep -q "$IP_ADDRESS\s*$DOMAIN" "$HOSTS_FILE"; then
echo "Removing $DOMAIN from $HOSTS_FILE..."
sudo sed -i.bak "/$IP_ADDRESS\s*$DOMAIN/d" "$HOSTS_FILE"
echo "$DOMAIN removed successfully. (Original file backed up as $HOSTS_FILE.bak)"
else
echo "$DOMAIN not found in $HOSTS_FILE."
fi
}
# Main script logic
case "$1" in
"add")
add_host_entry
;;
"remove")
remove_host_entry
;;
*)
echo "Usage: $0 {add|remove}"
exit 1
;;
esac
How it works: This script provides functions to add or remove a specific `IP_ADDRESS` to `DOMAIN` mapping in the `/etc/hosts` file. It checks for existing entries before adding and uses `sudo` for necessary permissions, ensuring proper management of local development domains without manual file editing.