BASH

Start a Simple Local HTTP Server and Open in Browser

A Bash script to quickly start a local HTTP server using Python's http.server and automatically open the served directory in your default web browser.

#!/bin/bash

PORT=${1:-8000}
DOCROOT=${2:-.}

echo "Starting HTTP server on port $PORT from directory $DOCROOT..."
python3 -m http.server $PORT --directory "$DOCROOT" &
SERVER_PID=$!

# Wait a moment for the server to start
sleep 1

# Open in browser
URL="http://localhost:$PORT"
if command -v xdg-open &> /dev/null; then
  xdg-open "$URL"
elif command -v open &> /dev/null; then
  open "$URL"
elif command -v start &> /dev/null; then # For Windows Subsystem for Linux (WSL)
  start "$URL"
else
  echo "Could not open browser. Please navigate to $URL manually."
fi

echo "Server running. Press Ctrl+C to stop."
wait $SERVER_PID
echo "Server stopped."
How it works: This script starts a simple HTTP server using Python's `http.server` module, defaulting to port 8000 and the current directory. It runs the server in the background and then attempts to open the server URL in the default web browser using `xdg-open` (Linux), `open` (macOS), or `start` (WSL). This is incredibly convenient for quickly serving static files, testing frontend assets, or previewing HTML/CSS projects without needing a full-blown web server setup.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs