[LinuxSIG] bash_httpd.sh

Ron / BCLUG admin at bclug.ca
Sat Mar 2 12:23:33 PST 2024


I asked ChatGPT to write an http server in bash.

The chat is posted below - it's quite a nice bit of code, including 
comments, `mkfifo`, bash functions, `trap` statement, `awk`, `nc`, 
syntax highlighting, sub-shells, default listening port is 8080 - so no 
root privileges required,...


There are a couple issues:
* it doesn't pipe the output to the fifo, so output goes to the shell, 
not the browser / network
* at the end, the fifo is left behind, so that needs manual deletion

All in all, pretty nice. Would've taken me ages to come up with 
something that works (would've taken forever, 'cause I'd never attempt it).

Wait, "pretty nice" is a bit of an understatement - this is absolutely 
amazing.




 > Write a simple web server in bash


> Writing a simple web server in Bash can be a fun exercise, but keep 
> in mind that it might not be suitable for production use due to 
> limitations and potential security risks. Below is a very basic 
> example of a web server implemented in Bash:


> #!/bin/bash
> 
> # Define the port on which the server will listen PORT=8080
> 
> # Function to handle incoming requests handle_request() { # Read the
> HTTP request from the client read -r request
> 
> # Extract the request method and path method=$(echo "$request" | awk
> '{print $1}') path=$(echo "$request" | awk '{print $2}')
> 
> # Serve a simple response if [ "$method" = "GET" ]; then if [ "$path"
> = "/" ]; then echo -e "HTTP/1.1 200 OK\r\nContent-Type:
> text/html\r\n\r\n<html><body><h1>Hello, World!</h1></body></html>" 
> else echo -e "HTTP/1.1 404 Not Found\r\nContent-Type:
> text/plain\r\n\r\n404 Not Found" fi else echo -e "HTTP/1.1 501 Not
> Implemented\r\nContent-Type: text/plain\r\n\r\n501 Not Implemented" 
> fi }
> 
> # Main loop to listen for incoming connections main() { echo
> "Starting server on port $PORT..." mkfifo fifo trap "rm -f fifo"
> EXIT
> 
> # Continuously listen for connections while true; do # Wait for a
> client to connect cat fifo | nc -l -p "$PORT" > >(handle_request) 
> done }
> 
> main


> Save the above code into a file, for example bash_web_server.sh, and
> make it executable with chmod +x bash_web_server.sh. Then you can run
> it with ./bash_web_server.sh.
> 
> This script creates a basic HTTP server that listens on port 8080. It
> can handle GET requests for the root path ("/") and returns a simple
> "Hello, World!" HTML page. All other paths will result in a "404 Not
> Found" response. Additionally, it returns a "501 Not Implemented"
> response for any request method other than GET.
> 
> Please note that this is a very basic implementation and lacks many
> features found in real-world web servers, such as concurrency
> handling, error checking, security measures, etc. It's more of a
> proof of concept rather than something suitable for production use.




More information about the LinuxSIG mailing list