henrydenhengst

Add Hostname on Linux

Nov 16th, 2015
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.04 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. # PATH TO YOUR HOSTS FILE
  4. ETC_HOSTS=/etc/hosts
  5.  
  6. # DEFAULT IP FOR HOSTNAME
  7. IP="127.0.0.1"
  8.  
  9. # Hostname to add/remove.
  10. HOSTNAME=$1
  11.  
  12. function removehost() {
  13.     if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
  14.     then
  15.         echo "$HOSTNAME Found in your $ETC_HOSTS, Removing now...";
  16.         sudo sed -i".bak" "/$HOSTNAME/d" $ETC_HOSTS
  17.     else
  18.         echo "$HOSTNAME was not found in your $ETC_HOSTS";
  19.     fi
  20. }
  21.  
  22. function addhost() {
  23.     HOSTNAME=$1
  24.     HOSTS_LINE="$IP\t$HOSTNAME"
  25.     if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
  26.         then
  27.             echo "$HOSTNAME already exists : $(grep $HOSTNAME $ETC_HOSTS)"
  28.         else
  29.             echo "Adding $HOSTNAME to your $ETC_HOSTS";
  30.             sudo -- sh -c -e "echo '$HOSTS_LINE' >> /etc/hosts";
  31.  
  32.             if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
  33.                 then
  34.                     echo "$HOSTNAME was added succesfully \n $(grep $HOSTNAME /etc/hosts)";
  35.                 else
  36.                     echo "Failed to Add $HOSTNAME, Try again!";
  37.             fi
  38.     fi
  39. }
Advertisement
Add Comment
Please, Sign In to add comment