Home > Net >  Run a Bash Shell Script from HTML Hyperlink?
Run a Bash Shell Script from HTML Hyperlink?

Time:03-26

I'm a Java Developer who is trying to learn HTML in painful baby steps. I'd like my nacent website to run a simple bash shell script (or better yet, a PHP script) when the user clicks a button or hyperlink. It is surprisingly hard to find a simple example of this!

I found this example on StackOverflow. The post's second answer lays out a step-by-step example, where the HTML code calls a PHP script; the PHP script calls a bash shell script. I've tried to replicate the example on my own web server. (FYI, I'm developing on an Ubuntu machine running Apache2.)

Here's my index.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <form action="/testexec.php">
        <input type="submit" value="Run My Script">
    </form>
  </body>
</html>

Keeping it simple, this creates a button to call testexec.php, which is in the Apache home directory (/var/www/html/) There's not much to that script, either:

<?php
shell_exec("/var/www/html/myBashScript.sh");
header('Location: http://10.10.10.10/myBashScript.sh?success=true');
?>

I'm not sure about those file pathnames. Strictly speaking, myBashScript.sh is in directory /var/www/html/ (although I suppose I could move it later). When I troubleshoot, I can't tell if the pathnames are screwing up anything. Also, I really hate that I have to refer to the server by its IP Address (here, 10.10.10.10.) There's gotta be a way to just say localhost, right?

Here's myBashScript.sh:

#!/bin/bash
echo "HELLO WORLD"

...and that should do it. So I thought. Both scripts are set properly with chmod and chown and chgrp, and I can manually run them without errors from the command line.

But when I surf to my webpage and click "Run My Script", I see this in my web browser:

#!/bin/bash
echo "HELLO WORLD"

In other words, the text of the script is printed to the screen. But I want the script to run and the output of the script to appear on screen. Gah! FWIW, I see no errors entered into the Apache2 error log (/var/log/apache2/error.log), either.

Soooooo... anyone spot my error? Thank you in advance.

CodePudding user response:

I think that could enable CGI scripts in your webserver, send the script to /cgi-bin/ folder, rename it to myscript.cgi (remember to put the appropiate Shebang), set 0755 permissions, correct owner/group and put in the very beginning of the script:

#!/bin/bash
echo "Content-Type: text/html"
... more code... 

The first echo line tells browser that the output of CGI script must be rendered as HTML (you could modify MIME type to your specific needs). There's a functional example:

#!/bin/bash
echo -e "Content-type: text/html\r\n\r\n"
echo "<html>"
echo "<head>"
echo "<title>TEST</title>"
echo "</head>"
echo "<body>"
echo "<h1>It Works!, Bash script running as CGI</h1>"
echo "</body>"
echo "</html>"
  • Related