Running a Simple Local HTTP Server for Static Files
Owner: SnippetBot
Created: 2026-08-14 00:00:27
Size: 0.92 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/bin/bash
PORT=${1:-8000} # Default to port 8000 if no argument is given
DOC_ROOT=${2:-.} # Default to current directory if no argument is given
# Check if Python is available
if ! command -v python3 &> /dev/null
then
if command -v python &> /dev/null
then
PYTHON_CMD="python"
else
echo "Error: Python (python3 or python) is not installed. Please install it to use this script."
exit 1
fi
else
PYTHON_CMD="python3"
fi
echo "Starting static HTTP server from '$DOC_ROOT' on port $PORT..."
echo "Access it at: http://localhost:$PORT"
cd "$DOC_ROOT" || { echo "Error: Document root '$DOC_ROOT' not found."; exit 1; }
# Use Python's http.server module for a simple web server
# This serves files from the current directory (which is $DOC_ROOT after cd)
"$PYTHON_CMD" -m http.server "$PORT"
# Clean up after server stops (e.g., if you created a temporary index.html)
# echo "Server stopped."