< BACK

Bash tips, tricks and code snippets

Create a netcat http server in a few lines of code

In as little as 3 lines of code, a http server can be created, either taking a port number on the command line as first argument or defaulting to port 8080:

#!/usr/bin/env bash
RESPONSE="HTTP/1.1 200 OK\r\nConnection: keep-alive\r\n\r\n${2:-"OK"}\r\n"
while { echo -en "$RESPONSE"; } | nc -l "${1:-8080}"; do
  echo "================================================"
done

See also

This bashhttpd server here referenced from stackoverflow.

Note: this uses parameter expansion

${1:-8080} is expanded to the default value 8080 if $1 is undefined or null/empty. Similarly for $2 in the response.