Skip to content

Instantly share code, notes, and snippets.

@o0-o
Created May 7, 2024 02:25
Show Gist options
  • Save o0-o/922b3ee317b7e1c823d7abd7de443292 to your computer and use it in GitHub Desktop.
Save o0-o/922b3ee317b7e1c823d7abd7de443292 to your computer and use it in GitHub Desktop.
idempotent hosts file configuration with sed
ip4="$( dig +short "$( hostname -f )" | tail -n 1 )"
sed -nEi \
-e '/^[[:space:]]*'"$ip4"'[[:space:]].*|[[:space:]0-9.]*('"$(hostname -s)|$(hostname -f | sed 's/\./\\./g')"')([[:space:]#]|$).*/ {' \
-e ' s/.*/'"${ip4} $(hostname -f) $(hostname -s)/" \
-e ' p' \
-e ' :noappend' \
-e ' n' \
-e ' /[[:space:]]*'"$ip4"'[[:space:]].*$/n' \
-e ' p' \
-e ' b noappend' \
-e '}' \
-e 'p' \
-e '$a\
'"${ip4} $( hostname -f ) $( hostname -s )" \
/etc/hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment