Skip to content

Instantly share code, notes, and snippets.

@brandon-rhodes
Created August 10, 2012 01:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandon-rhodes/3310173 to your computer and use it in GitHub Desktop.
Save brandon-rhodes/3310173 to your computer and use it in GitHub Desktop.
Shell script that finds a free TCP port, runs the Python built-in HTTP file server on that port, and then opens a new Google Chrome tab displaying the site's root directory
#!/bin/bash
#
# To use: cd to a directory you want to browse, and run this script.
#
# This lets you skip finding a free TCP port on your system and
# running SimpleHTTPServer on that port and pointing your browser there.
# Instead, we ask the SimpleHTTPServer to run at whichever free port the
# operating system would like to assign, we watch its output to see what
# port was in fact assigned, and then we open a new tab in the browser
# (in this case, Google Chrome) automatically.
ANY_PORT=0
exec /usr/bin/python -u -m SimpleHTTPServer $ANY_PORT |
while read -r line
do
if echo $line | grep -q '^Serving'
then
PORT=$(echo $line | awk '{print$6}')
google-chrome http://localhost:$PORT/
fi
done
@benjaminws
Copy link

This is handy!

You could make this more generic (for folks that might not be using chrome, god love them) by using xdg-open instead of explicitly executing google-chrome. Just a thought!

@benjaminws
Copy link

Oh, one more thing. Consider /usr/bin/env python over the explicit path to python.

OMG, I suggested implied things over explicit things, twice. The ruby is rubbing off on me :(

@edcrypt
Copy link

edcrypt commented Aug 10, 2012

/usr/bin/env python whould break on a sys with Python 3 by default.

@edcrypt
Copy link

edcrypt commented Aug 10, 2012

Argh, *would. I can't spell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment