Last active
November 8, 2019 21:55
-
-
Save rduplain/729f7f7deee776a7477ae71dddcfdcde to your computer and use it in GitHub Desktop.
Refresh /etc/hosts file with unpublished IPv4 aliases.
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
#!/usr/bin/env bash | |
# Refresh /etc/hosts file with unpublished IPv4 aliases. | |
# | |
# Set /etc/hosts.alias with domain/alias pairs, one pair per line: | |
# | |
# example.com server-alias | |
# example.net another | |
# | |
# https://github.com/rduplain/hosts | |
set -e | |
PROG=refresh-hosts | |
HOSTS_ALIAS="${HOSTS_ALIAS-/etc/hosts.alias}" | |
HOSTS_IN="${HOSTS_IN-/etc/hosts.base}" | |
HOSTS_OUT="${HOSTS_OUT-/etc/hosts}" | |
DELIMITER="${DELIMITER- }" # For use in newly created hosts entries. | |
ip_alias() { | |
# Generate IPv4/alias pairs for domain/alias pairs in $HOSTS_ALIAS. | |
set -- $(cat "$HOSTS_ALIAS") | |
while [ "$1" != "" ]; do | |
domain="$1" | |
alias="$2" | |
shift 2 | |
ip="$(dig "$domain" A +short | grep '^[.0-9]*$'; true)" | |
if [ -z "$ip" ]; then | |
echo "$PROG: error. unable to find IPv4 for '$domain'." >&2 | |
return 1 | |
fi | |
echo "$ip" "$alias" | |
done | |
} | |
main() { | |
# Refresh $HOSTS_OUT with DNS result of domain/alias pairs in $HOSTS_ALIAS. | |
args=(-f "$HOSTS_IN" -d "$DELIMITER") | |
set -- $(ip_alias) | |
while [ "$1" != "" ]; do | |
ip="$1" | |
alias="$2" | |
shift 2 | |
args+=(-s "$ip$DELIMITER$alias") | |
done | |
exec hosts "${args[@]}" > "$HOSTS_OUT" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment