Bash script for editing the hosts file

I just read a post about local development in apache by Jesper Rasmussen and thought one thing was missing. I usually test my sites and applications locally with the real domain – to ensure that functionality based on the url works as expected. However this means editing the hosts file several times a day. Now I have made a small shellscript that will add and remove lines from the hosts file.

#! /bin/bash
DEFAULT_IP=127.0.0.1
IP=${3:-$DEFAULT_IP}

case "$1" in
  add)
        echo "$IP $2"  >> /etc/hosts
        ;;
  remove)
        sed -ie "\|^$IP $2\$|d" /etc/hosts
        ;;

  *)
        echo "Usage: "
		echo "hosts.sh [add|remove] [hostname] [ip]"
		echo
		echo "Ip defaults to 127.0.0.1"
		echo "Examples:"
		echo "hosts.sh add testing.com"
		echo "hosts.sh remove testing.com 192.168.1.1"
        exit 1
        ;;
esac

exit 0

As you can see the script defaults the ip to 127.0.0.1 for easy creation of local domains. Next step is to create a quicksilver (and a gnome do) plugin for easy creation without ever touching the terminal. (Even though we all love the terminal, right?)

by Claus Witt

November 4, 2009  Tags: , , ,   Posted in: Web development

One Response

  1. Using Quicksilver to edit hosts file | clauswitt.com - November 4, 2009

    [...] is mostly just a follow up for my previous post on using a shell script to add and remove test domains in the hosts file. I have created two small applescripts for use in Quicksilver to execute that script. If you need [...]

Leave a Reply