#!/usr/bin/env bash # Path to your hosts file hostsFile="/etc/hosts" # Hostname to add/remove. hostname="$2" yell() { echo "$0: $*" >&2; } die() { yell "$*"; exit 111; } try() { "$@" || die "cannot $*"; } remove() { if grep -qP "[[:space:]]$hostname" "$hostsFile"; then echo "$hostname found in $hostsFile. Removing now..." try sudo sed -ie "/[[:space:]]$hostname/d" "$hostsFile" else yell "$hostname was not found in $hostsFile" fi } add() { if grep -qP "[[:space:]]$hostname" "$hostsFile"; then yell "$hostname already exists: $(grep "$hostname" $hostsFile)" else echo "Adding $hostname to $hostsFile..." try printf "%s\t%s\n" "127.0.0.1" "$hostname" | sudo tee -a "$hostsFile" > /dev/null if grep -q "$hostname" "$hostsFile"; then echo "$hostname was added succesfully:" grep "$hostname" "$hostsFile" else die "Failed to add $hostname" fi fi } "$@"