BASH
Add or Remove Local Host Entries for Development
Easily manage entries in your `/etc/hosts` file, allowing you to map custom domain names (e.g., `myapp.local`) to `127.0.0.1` for local web development.
#!/bin/bash
# Usage:
# ./manage_hosts.sh add myapp.local
# ./manage_hosts.sh remove myapp.local
ACTION="$1" # 'add' or 'remove'
HOSTNAME="$2"
HOSTS_FILE="/etc/hosts"
IP_ADDRESS="127.0.0.1"
HOST_ENTRY="$IP_ADDRESS\t$HOSTNAME"
if [ -z "$ACTION" ] || [ -z "$HOSTNAME" ]; then
echo "Usage: $0 <add|remove> <hostname>"
echo "Example: $0 add myapp.local"
exit 1
fi
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run with sudo: sudo $0 $@"
exit 1
fi
case "$ACTION" in
add)
if grep -q "$HOSTNAME" "$HOSTS_FILE"; then
echo "'$HOSTNAME' already exists in $HOSTS_FILE."
else
echo "Adding '$HOST_ENTRY' to $HOSTS_FILE..."
echo -e "$HOST_ENTRY" >> "$HOSTS_FILE"
echo "'$HOSTNAME' added successfully."
fi
;;
remove)
if grep -q "$HOSTNAME" "$HOSTS_FILE"; then
echo "Removing '$HOSTNAME' from $HOSTS_FILE..."
sed -i "/\s$HOSTNAME$/d" "$HOSTS_FILE"
echo "'$HOSTNAME' removed successfully."
else
echo "'$HOSTNAME' not found in $HOSTS_FILE."
fi
;;
*)
echo "Invalid action: '$ACTION'. Use 'add' or 'remove'."
exit 1
;;
esac
How it works: This script provides a convenient way to manage custom host entries in your `/etc/hosts` file. It allows you to `add` a mapping for a hostname (like `myapp.local`) to `127.0.0.1` or `remove` an existing entry. This is crucial for local web development, enabling you to test applications with custom domain names without needing to set up a full DNS server. The script requires `sudo` privileges to modify the hosts file.