#!/bin/sh ETC_HOSTS="/etc/hosts" DHCP_HOSTS="/tmp/dhcp.hosts" MERGED_HOSTS="/tmp/merged.hosts" # Ensure both input files exist [ -f "$ETC_HOSTS" ] || { echo "Error: $ETC_HOSTS not found!"; exit 1; } [ -f "$DHCP_HOSTS" ] || { echo "Error: $DHCP_HOSTS not found!"; exit 1; } # Create a clean merged hosts file echo "# Merged hosts file - Static + DHCP" > "$MERGED_HOSTS" # Use associative arrays (requires BusyBox-compatible shell) awk ' BEGIN { # Declare maps to track used IPs and hostnames FS=" "; } # Process /etc/hosts first NR == FNR { if ($1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) { ip_map[$1] = 1; # Track IPs for (i = 2; i <= NF; i++) { if (!host_map[$i]) { host_map[$i] = $1; # Track hostnames } else { print "Conflict: hostname \"" $i "\" already exists in /etc/hosts (keeping existing entry)" > "/dev/stderr"; } } } print > "'$MERGED_HOSTS'"; next; } # Process dhcp.hosts { if ($1 in ip_map) { print "Conflict: IP " $1 " already exists in /etc/hosts (ignoring DHCP entry)" > "/dev/stderr"; next; } for (i = 2; i <= NF; i++) { if ($i in host_map) { print "Conflict: hostname \"" $i "\" already exists in /etc/hosts (ignoring DHCP entry)" > "/dev/stderr"; next; } } print >> "'$MERGED_HOSTS'"; } ' "$ETC_HOSTS" "$DHCP_HOSTS" echo "Merged hosts file created at $MERGED_HOSTS"