Skip to content

Instantly share code, notes, and snippets.

@ab
Created October 20, 2014 23:49
Show Gist options
  • Save ab/959d2bd1052e50b25331 to your computer and use it in GitHub Desktop.
Save ab/959d2bd1052e50b25331 to your computer and use it in GitHub Desktop.
Modify /etc/hosts by adding or removing comments from lines by IP address.
#!/bin/sh
# 1.0
set -eu
HOSTS=/etc/hosts
usage() {
cat <<EOM
usage: $(basename "$0") OPTION...
Modify /etc/hosts by adding or removing comments from lines by IP address.
Options:
-c IP Comment IP.
-u IP Uncomment IP.
-f Don't interactively confirm changes.
This script modifies /etc/hosts atomically. It will diff changes and prompt for
confirmation unless -f is given.
EOM
}
if [ $# -eq 0 ]; then
usage
exit 1
fi
tmpf="$(mktemp /etc/hosts.new-XXXXXX)" || { echo>&2 "Are you root?"; exit 2; }
trap "rm -f '$tmpf'" EXIT
cp -a "$HOSTS" "$tmpf"
comment_ip() {
ip="$1"
echo>&2 "Commenting: $ip"
sed -ri "s/^$ip /# $ip /" "$tmpf"
}
uncomment_ip() {
ip="$1"
echo>&2 "Uncommenting: $ip"
sed -ri "s/^# ?$ip /$ip /" "$tmpf"
}
check_ip() {
if ! echo "$*" | grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' > /dev/null; then
echo >&2 "Invalid IP: '$*'"
return 1
fi
}
force=
while getopts hc:u:f OPT; do
case $OPT in
h)
usage
exit 0
;;
c)
check_ip "$OPTARG"
comment_ip "$OPTARG"
;;
u)
check_ip "$OPTARG"
uncomment_ip "$OPTARG"
;;
f)
force=1
;;
\?)
usage
exit 1
;;
esac
done
if diff -u "$HOSTS" "$tmpf"; then
# no changes
echo >&2 "Nothing to do."
exit
fi
if [ -n "$force" ]; then
ans=y
else
read -p "Commit change to $HOSTS ? [y/N] " ans
fi
if [ "$ans" = "y" ]; then
mv -v "$tmpf" "$HOSTS"
trap - EXIT
else
echo >&2 "Made no changes."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment