≡ Menu

echo echo

Bash Iterate Array Examples

How do I iterate through an array under Bash scripting?
[click to continue…]

Run shell script from web page

Q. How do I run a shell script from a web server or a web page under Apache or Lighttpd websever?

A. In order to run a shell script from a web page you need Apache web server configured with cgi access. Apache CGI allows documents/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. However, you cannot simply run shell script from a web. You need to send or print the MIME type before outputting data to the web browser from shell script. You need to add following line to script before you get output back to browser:

echo "Content-type: text/html"
echo ""

Here is the script that can displays today's date and other information related to your shell script:

#!/bin/bash
# get today's date
OUTPUT="$(date)"
# You must add following two lines before
# outputting data to the web browser from shell
# script
 echo "Content-type: text/html"
 echo ""
 echo "<html><head><title>Demo</title></head><body>"
 echo "Today is $OUTPUT <br>"
 echo "Current directory is $(pwd) <br>"
 echo "Shell Script name is $0"
 echo "</body></html>"

Save the script in your cgi-bin directory and execute it from web page.

See also:

=> For more examples see how to: Run Linux / UNIX commands from a web page.

Q. How can I display or show today's UNIX computer date from a shell script using echo command? How do I store date command output to a variable?

A. Date command is use to print or set the system date and time under Linux/Unix like operating systems. However some time you need to include today's date in shell script. You need to use command substitution in your shell script to display today's date. Bash/sh shell performs the expansion by executing command and replacing the command substitution with the standard output
of the command, with any trailing newlines deleted. Command substitution allows the output of a command to replace the command name. You can use following syntax:

$(command)
OR
`command`
For example, type the following at shell prompt to display today's date:
$ echo "Today is $(date)"
Output:

Today is Sat Jan 28 15:48:11 IST 2006

Here is sample script, that stores today's date in TODAY and hostname in HOST variable:

#!/bin/bash
TODAY=$(date)
HOST=$(hostname)
echo "-----------------------------------------------------"
echo "Date: $TODAY                     Host:$HOST"
echo "-----------------------------------------------------"
# add rest code...

Save above script and execute it. See working shell script that notify admin user if Linux/FreeBSD system load crossed certain limit