Skip to content

Instantly share code, notes, and snippets.

@victor141516
Last active January 31, 2018 10:49
Show Gist options
  • Save victor141516/0c0c4a18fce51626d8fbfb1af872f4a6 to your computer and use it in GitHub Desktop.
Save victor141516/0c0c4a18fce51626d8fbfb1af872f4a6 to your computer and use it in GitHub Desktop.
Add entries /etc/hosts temporally
#! /bin/sh
if [ "$1" == "-e" ]; then
"${EDITOR:-vi}" hosts
exit;
fi
if [ "$1" == "-r" ]; then
if [ -e hosts ]; then
read -p "Remove temporal hosts (Y/n)? " choice
case "$choice" in
n|N ) echo "Not deleted";;
* ) rm hosts;;
esac
else
echo "Temporal hosts doesn't exists";
fi
exit;
fi
sudo -v
# Keep-alive sudo
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
exit_script() {
echo "\n\nRestoring old hosts file\n"
sudo cp -f /etc/hosts.bak /etc/hosts
read -p "Remove temporal hosts (Y/n)? " choice
case "$choice" in
n|N ) echo "Not deleted";;
* ) rm hosts;;
esac
trap - SIGINT SIGTERM
kill -- -$$
}
trap exit_script SIGINT SIGTERM
sudo cp -f /etc/hosts /etc/hosts.bak;
if [ -z "$1" ]; then
empty=1;
else
empty=0;
org=$1;
fi
if [ -z "$2" ]; then
dst="127.0.0.1";
else
dst=$2;
fi
if [ -e hosts ]; then
diff hosts /etc/hosts.bak |
tail +2 |
awk '{$1=""}1' |
awk '{$1=$1}1' |
awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }' |
sed -r 's/ / --> /g' |
sed -e 's/^/Adding (old) /';
else
cat /etc/hosts > hosts;
if [ $empty -eq 1 ]; then
echo "Nothing added :(";
rm hosts;
sudo cp -f /etc/hosts.bak /etc/hosts;
exit;
fi
fi
if [ $empty -eq 0 ]; then
echo "Adding $org --> $dst";
echo $dst $org >> hosts;
fi
sudo cp -f hosts /etc/hosts;
while true; do sleep 600; done;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment