bash function for launching a web server

I’m doing a lot of AJAX development lately so I have to serve my HTML via HTTP, because AJAX just won’t work with file: URLs. There’s a lot of ways to launch a simple HTTP server in your current directory, here’s a handy bash function to do it (using Python)

pws ()
{
    PORT="$1";
    IP=`ifconfig en0 | awk '/inet / { print $2 }'`;
    python -m SimpleHTTPServer "$PORT" >> /tmp/pws-"$PORT".log 2>&1 &
    echo "http://$IP:$PORT/"
}

There’s a bogus bit here, using “ifconfig en0” to try to guess the right IP address to show. On a Linux box that’d be “eth0”, and in general it’s hard to know which of a machine’s IP addresses you really should use.

Update: I’ve tinkered with this script a little bit. It’ll supply a random port number if one isn’t given. And it’s a bit smarter about figuring out a likely IP address.

function pws {
  PORT="$1"
  [ -z "$PORT" ] && PORT=$[RANDOM%1000 + 9000]
  IP=`ifconfig | awk '/inet / { if ($2 != "127.0.0.1") { print $2; exit 0; } }'`
  python -m CGIHTTPServer "$PORT" >> /tmp/pws-"$PORT".log 2>&1 &
  echo "http://$IP:$PORT/"
}