Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refresh /etc/hosts file with unpublished IPv4 aliases.
#!/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