Last active
February 2, 2023 07:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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