Skip to content

Instantly share code, notes, and snippets.

@rkuzsma
Last active February 2, 2023 07:12
Show Gist options
  • Save rkuzsma/201975e51dd26c1d1f4f083e3a325123 to your computer and use it in GitHub Desktop.
Save rkuzsma/201975e51dd26c1d1f4f083e3a325123 to your computer and use it in GitHub Desktop.
Bash function to add a hostname:ip entry into your /etc/hosts file
#!/bin/bash
# Usage:
# update_etc_hosts "some-host-name" "some-ip-addr"
update_etc_hosts () {
HOST_NAME=$1
HOST_IP=$2
NO_SUDO=$3
HOST_ENTRY="$HOST_IP $HOST_NAME"
HOSTS_FILE="/etc/hosts"
TMPFILE=$(mktemp)
echo "Adding '$HOST_IP $HOST_NAME' entry to '$HOSTS_FILE'"
if grep -q "^[^#]*$HOST_NAME" "$HOSTS_FILE" ; then
echo "Replacing existing '$HOST_NAME' entry."
awk "!/^[^#].*$HOST_NAME/ {print \$0}" "$HOSTS_FILE" > "$TMPFILE"
else
cp $HOSTS_FILE $TMPFILE
fi
echo -e "$HOST_ENTRY" >> "$TMPFILE"
if [[ $NO_SUDO = "NO_SUDO" ]]; then
cat "$TMPFILE" > "$HOSTS_FILE"
else
echo "Modifying $HOSTS_FILE requires sudo privileges, please enter your password."
sudo -k sh -c "cat \"$TMPFILE\" > \"$HOSTS_FILE\""
fi
rm "$TMPFILE"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment