Running a shell script from a web page could give an added value to your applications.

Imagine you have developed an application running on your Raspberry Pi, and you want to give to a user the capability to interact with the system trough a simple user interface…
You can draw your GUI in HTML and then you can use some scripts to interact with Raspbian OS.

For example you could want to retrive the current temperature… Take a look to the related posts to see how Raspbian handles Temperature sensor.

In order to run a shell script from a web page you must have installed Apache and you must have configured Apache with cgi access.

The CGI (Common Gateway Interface) defines a way for a web server to interact with external content-generating programs, which are often referred to as CGI programs or CGI scripts. It is the simplest, and most common, way to put dynamic content on your web site. 

Apache CGI allows files in cgi-bin directory treated as application and run by server when requested rather than as documents sent to the client.. It means if you put shell script in cgi-bin directory then you are able to execute them from a web page. 

apache1

A CGI script has two rules:
1. all output from your CGI program must be preceded by a MIME-type header. This is HTTP header that tells the client what sort of content it is receiving. Most of the time, this will look like:

Content-type: text/html


2. your output needs to be in HTML, or some other format that a browser will be able to display. Most of the time, this will be HTML, but occasionally you might write a CGI program that outputs a gif image, or other non-HTML content.

 

So if you want to show the temperature of your Raspberry Pi you have to write a script like the following:

#!/bin/bash
$(cat /sys/class/thermal/thermal_zone0/temp > aux)
TEMP=$(awk '{print $1}' aux)
rm -f aux
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Raspberry Temperature</title></head><body>"
echo "Current temperature is $TEMP <br>"
echo "</body></html>"


now save the script naming it "temp.cgi", and change the execution permission issuing the following command:
~ $ chmod +x temp.cgi

Move the script into the cgi-bin directory (in Debian or derived distros you can find it in /etc/apache-perl/httpd.conf)
~ $ mv temp.cgi /path/to/cgi-bin/directory/


Now you can test the script pointing your browser to http://127.0.0.1/cgi-bin/temp.cgi

That's all,
gg1