2014-07-09 48 views
0

我有一個奇怪的問題。當我直接從命令行運行腳本時,它工作正常。但是當我從Java Script執行它時,remoteCall函數未被執行。任何幫助表示讚賞。無法在cgi-BashScript中調用函數

#!/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 [email protected]$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); 
    }); 
} 
+0

並調用它的JavaScript代碼? – konsolebox

+0

在代碼中添加JavaScript代碼。 – Amber

+0

'$ DF_COMMAND','$ USERNAME'和'$ SERVER'從何處獲取它們的值? –

回答

0

您的腳本可能不會被用bash執行即使頭顯式聲明#!/bin/bash。在你的CGI服務器的配置可以解決這個問題,或者使你的腳本更加保守,併兼容原sh(不僅僅是POSIX)殼將幫助:

#!/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 "[email protected]$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,但POSIX也可能是足夠的。

RESULT=$(ssh "[email protected]$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. 

你也可以考慮不要用subshel​​l調用函數來得到結果(很糟糕的做法)。只需使用變量即可:

remoteCall() { 
    echo "remote call" 
    RC_RESULT=`ssh "[email protected]$SERVER" "$1"` 
} 

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

我嘗試過使用你的解決方案。但是我不能使用你用於函數調用的單引號。你有沒有想法如何處理它。 – Amber

+0

@Amber爲什麼不呢?你也可以考慮再次使用'$()'。只是不要使用'local'並用'function'聲明你的函數。 – konsolebox

+0

RESULT ='ssh「$ USERNAME @ $ SERVER」「$ 1」'沒有執行。否則一切工作正常。 – Amber