CGI is a convention for linking executable files, that is programs or scripts, to an item on a web page. So, when clicking on that item in a web browser the server at the other end don't produce another html page, but instead runs the program specified and the send the output of the program to the browser for display. This means the output of that program must be in the format of an html page.
This mechanism makes it possible to have dynamic web pages, whose content may change based on any conditions that may hold at the time.
On a Linux system the html pages are typically stored in the directory /var/www/html and the executables are stored in /var/www/cgi-bin. Web servers, such as Apache or Nginx, can be configured to look for web pages and script in specified directories. Web servers typically use the filename extension of the specified executable to determine which program should take care of the execution. For example, a script with extension sh can be run the Bash shell or another shell specified at the top the file after the "hash bang" (#!). As file with extension cgi is typically interpreted as a Perl program.
Below is a simple Bash script that functions as dynamic html page when placed in a directory used by the web server for CGI scripts:
echo Content-type: text/plain
echo List of environment variables:
echo Print version of Bash used:
The Content-type line is important. It is similar to file type and tells the browser format of the data so that it knows how to display it to the user. For example, if the content is a spreadsheet or a multimedia file, the browser will invoke a suitable support application to display the information, images, or movies.
The following echo statements will display the values of the specified variables on the server when included in the script:
echo AUTH_TYPE = $AUTH_TYPE
echo CONTENT_TYPE = $CONTENT_TYPE
echo CONTENT_LENGTH = $CONTENT_LENGTH
echo QUERY_STRING = "$QUERY_STRING"
echo REMOTE_HOST = $REMOTE_HOST
echo REMOTE_ADDR = $REMOTE_ADDR
echo REMOTE_USER = $REMOTE_USER
echo SERVER_SOFTWARE = $SERVER_SOFTWARE
echo SERVER_NAME = $SERVER_NAME
echo GATEWAY_INTERFACE = $GATEWAY_INTERFACE
echo SERVER_PROTOCOL = $SERVER_PROTOCOL
echo SERVER_PORT = $SERVER_PORT
echo REQUEST_METHOD = $REQUEST_METHOD