Web server in one line of bash

If you want to quickly save a file through http but you don’t want to install a web server, you can just use netcat.
You can run:
[code language=”bash”]
while true; do { echo -e ‘HTTP/1.1 200 OK\r\n’; cat index.html; } | nc -l 8080; done

index.html can be any file you want to serve it.

You can access it after that as: http://host_ip:8080/


  1. For that purpose I’m using:

    rm -f out ; mkfifo out ; while true ; do cat out | nc -l localhost 8080 | tr -ud ‘\r’ | awk ‘/^GET /{system(“cat “$2″>out”)}’ ; done

  2. Or you can use Python: python -m SimpleHTTPServer
    Or you can use Twisted: twistd -n web –path .

    There is a good chance that you have Twisted already installed as a dependency of something else. Otherwise the Python module will serve you well (the Twisted version can serve multiple requests concurrently).

  3. If your netcat is new enough, you can also use:
    h(){ nc -lp8080 -c’r=HTTP/1.0;f=`head -n1|cut -d\ -f2`;[ -f .$f ]&&echo “$r 200\nContent-Type: `file -bi .$f`\n”&&cat .$f||echo $r 404′;h;}

    which fits in a tweet 🙂

  4. Way fun, Turns out it can server an image too. Replace index.html with file.jpg (png gif) and you get the image displayed as well. Obvious, but neat to see the image. Great on razvan. I’ve used inet to do this with cat, first time in bash. cool.

  5. nc has “-k, –keep-open” option, to use instead of “while true”. This line below working with any web browser! Thank You. 🙂

    nc -kl 5432 -c ‘echo -e “HTTP/1.1 200 OK\r\n$(date)\r\n\r\n”;echo “How are you today?”‘

Leave a comment

Your email address will not be published. Required fields are marked *