Skip to content

Instantly share code, notes, and snippets.

@dam2k
Last active February 18, 2021 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dam2k/5df0d8d3fdabc41e8ce2c799734f65d4 to your computer and use it in GitHub Desktop.
Save dam2k/5df0d8d3fdabc41e8ce2c799734f65d4 to your computer and use it in GitHub Desktop.
Bash CGI HTTP Status code example
#!/bin/bash
function sendcontentheader()
{
printf 'Content-Type: %s\n' "$1"
}
function sendstatuscode()
{
printf 'Status: %s\n' "$1"
}
function endheaders()
{
printf '\n'
}
function sendbody()
{
printf '<html>\n'
printf '<head><title>HI!</title></head>'
printf "<body><h2>Hi there, this is <b>$(basename $0)</b> speaking.<h2><h3>HTTP Status code: $1</h3</body>\n"
printf '</html>\n'
}
# ------- Main program body ----------
sendcontentheader 'text/html'
SC='410 Gone'
sendstatuscode "$SC"
endheaders
sendbody "$SC"
@dam2k
Copy link
Author

dam2k commented Feb 18, 2021

The code is super simple, does not require any dependency and is auto explicative.

There are 4 functions that are implemented at the beginning of the script: sendcontentheader() and sendstatuscode() send only a single header to stdout, endheaders() send newline character to end the response headers and begin the body section, sendbody() write some html to stdout.

The function that sends the HTTP Status code header is sendstatuscode().

Also, try to directly exec the script from command line to get the output, that is:

dino@a1:/tmp# chmod 755 test.cgi
dino@a1:/tmp# ./test.cgi
Content-Type: text/html
Status: 410 Gone

<html>
<head><title>HI!</title></head><body><h2>Hi there, this is <b>test.cgi</b> speaking.<h2><h3>HTTP Status code: 410 Gone</h3</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment