Last active
August 29, 2015 14:02
-
-
Save paulsmith/c93be2cc3a303b86f4c4 to your computer and use it in GitHub Desktop.
start a file-serving web server in a directory on an OS-assigned port and opens browser to the root
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Copyright 2014 Paul Smith | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
# | |
# Starts a file-serving HTTP server on an OS-assigned port and opens the default | |
# web browser to the root URL (i.e., the directory it was started in). | |
# | |
# Uses `open(1)` which is OS X-only. | |
f1=/tmp/.$(basename $0).$$.1 | |
f2=/tmp/.$(basename $0).$$.2 | |
mkfifo $f1 $f2 | |
trap "rm -f $f1 $f2" EXIT | |
grep --line-buffered -E '^Serving HTTP on .* port .* \.\.\.$' < $f1 | \ | |
sed -l -E -e 's|Serving HTTP on (.+) port (.+) \.\.\.|http://\1:\2/|' > $f2 & | |
{ | |
read addr <$f2 | |
echo $addr | |
open $addr | |
} & | |
python -u -m SimpleHTTPServer 0 | tee $f1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Everyone knows
python -m SimpleHTTPServer
to start a quick webserver in a directory, it's pretty awesome. It either mounts on port 8000 by default or you can give it an alternate port as an command line argument. But if you're like me, you have lots of server processes running at once, you often get conflicts where the port is already in use, or you have to hunt and peck for a free one.It's much better to just let the OS assign an unused port to this quick webserver process, since you don't really care where it goes. You can do this by passing 0 as the port argument, and that totally works: Python prints out the port it started the HTTP server on. There's just one problem that trips me up: it prints out this new port number in such a way that you have to either mouse over, select, copy, open a new tab, paste, after typing in "localhost" or "0.0.0.0", or you have to eyeball it and type it in with the new tab:
See what I mean, you have to snag that 61200 somehow. I just want to start a webserver and have it immediately open to that address in my browser! That output should be clickable or hook into OS X's
open
.So this shell script does that.