Skip to content

Instantly share code, notes, and snippets.

@itxx00
Created January 9, 2015 03:57
Show Gist options
  • Save itxx00/45dcedbf01de4c070fec to your computer and use it in GitHub Desktop.
Save itxx00/45dcedbf01de4c070fec to your computer and use it in GitHub Desktop.
manage /etc/hosts file
#!/bin/bash
# manage /etc/hosts
isIp() {
# test variable is an ip address or not
# true: return 0
# false: return 1
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
if [[ -n "$1" ]] && [[ -n "$2" ]]; then
a="$1"
b="$2"
if isIp "$a"; then
ip="$a"
name="$b"
elif isIp "$b"; then
ip="$b"
name="$a"
else
exit 2
fi
if grep -wq "$name$" /etc/hosts; then
sed -i "/ $name$/d" /etc/hosts
fi
echo "$ip $name" >> /etc/hosts
elif [[ -n "$1" ]]; then
name="$1"
sed -i "/ $name$/d" /etc/hosts
else
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment