无法在cgi-Bash脚本中调用函数

时间:2014-07-09 16:40:02

标签: bash shell cgi

我有一个奇怪的问题。当我直接从命令行运行脚本时,它工作正常。但是当我从Java Script执行它时,不会执行 remoteCall 功能。任何帮助表示赞赏。

#!/bin/bash
echo "Content-type: text/html"
echo ""

SERVER="SERVER";
USERNAME="username";
THRESHOLD="70";     #   % Space occupied on disk. 
DF_COMMAND="df -Pkh";

function remoteCall() {
    echo "remote call "
    local RESULT;
    RESULT=$(ssh $USERNAME@$SERVER $1);
    echo "$RESULT";
}

# Starting point for the script
function main() {
    echo "main function"
    local DF_Result=$(remoteCall "$DF_COMMAND");    # This function doesn't get called.
    echo "$DF_Result"
}

main

调用脚本的Java脚本代码是:

cgiUrl="cgi-bin/scanner.cgi";
function diskCheckingScript() {
    $.post(cgiUrl, function(result) {
    console.log("Result is",result);
    });
}

1 个答案:

答案 0 :(得分:0)

即使标头明确声明bash,您的脚本也可能无法与#!/bin/bash一起执行。您的CGI服务器中的配置可能会解决此问题,或者可能使您的脚本更加保守并且与原始sh(不仅仅是POSIX)shell兼容会有所帮助:

#!/bin/sh
echo "Content-type: text/html"
echo ""

SERVER="SERVER"
USERNAME="username"
THRESHOLD="70"     #   % Space occupied on disk.
DF_COMMAND="df -Pkh"

remoteCall() {
    echo "remote call"
    RESULT=`ssh "$USERNAME@$SERVER" "$1"`   # Perhaps we need to specify the full path of ssh. e.g. /usr/bin/ssh
    echo "$RESULT"
}

# Starting point for the script
main() {
    echo "main function"
    DF_Result=`remoteCall "$DF_COMMAND"`    # This function doesn't get called.
    echo "$DF_Result"
}

main

注意:我们可能不需要限制性。 POSIX也可能足够,尽管我不赞成完全基于它。

    RESULT=$(ssh "$USERNAME@$SERVER" "$1")   # Perhaps we need to specify the full path of ssh. e.g. /usr/bin/ssh

    DF_Result=$(remoteCall "$DF_COMMAND")    # This function doesn't get called.

您也可以考虑不使用子shell调用该函数来获得结果(非常糟糕的做法)。只需使用分配的变量:

remoteCall() {
    echo "remote call"
    RC_RESULT=`ssh "$USERNAME@$SERVER" "$1"`
}

# Starting point for the script
main() {
    echo "main function"
    remoteCall "$DF_COMMAND"    # This function doesn't get called.
    echo "$RC_RESULT"
}