Writing CGI scripts in Raspberry Pi

this blog shows a small & simple procedure about Writing CGI scripts in Raspberry Pi.  This tutorial assumes that you have installed Apache2. You can do this by opening a terminal and typing

sudo apt-get install apache2

Serving static HTML files is limited, and not interactive. Scripting makes web sites dynamic and opens up possibilities like building interactive web sites and sites that can remotely control devices.

CGI scripts are usually stored in /usr/lib/cgi-bin, and they must have executable permission. Scripts execute when they are requested by a browser. Anything printed to stdout will be displayed in a browser, so many scripts are used to generate HTML.

CGI scripting in bash

Start Leafpad by opening a terminal and typing

sudo leafpad /usr/lib/cgi-bin/hello.cgi &

Type this code into leafpad:

#!/bin/bash echo -e “Content-type: text/html\n\n” echo “<h1>Hello World</h1>”

Save it, and make the file executable with this command:

sudo chmod +x /usr/lib/cgi-bin/hello.cgi

Open a browser and go to the address of the script. For example, if your Pi’s IP address is, the URL of the script is You should see the words “Hello World” in large letters in your browser.

The first line of the script indicates that this file should be interpreted by bash. This line won’t be sent to the browser that requested the page.

The next line is an HTTP header. The header is printed to stdout, so it will be sent to the browser. In this example the header just tells the browser that the following text should be interpreted as HTML. HTTP headers can contain other information such as the length of time that a page should be stored in cache. Cookies can also be set by printing set cookie commands in the header.

Note the double ‘\n’ at the end of the header. This is important because there must be an empty line after the header. This empty line tells the browser that the header has finished, and any following text is HTML. Don’t forget the quotes at the beginning and end of each line of HTML that’s echoed.

I’m using the echo command to print HTML to stdout. It’s also possible to store snippets of HTML in files, and then print the contents of those file to stdout using the cat command.


Leave a comment

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