2015-12-21 123 views
0

我需要將參數傳遞給shell腳本,該腳本經過驗證後需要以相同或修改後的形式傳遞給腳本中的函數。shell函數和參數傳遞問題

#!/bin/sh 
func1(){ 
echo "called func1 with $1" ; 
exit 0 ; 
} 

func2(){ 
echo "called func2 with $1" ; 
exit 0 ; 
} 

if [ $# -eq 0 ] 
then 
    echo "Usage:" ; 
    echo "script.sh arg1 arg2" ; 
    exit -1 ; 
fi 

if [ "$1" -eq "txt1" ] 
then 
    func1 $2 ; 
    exit 0 ; 
fi 

if ["$1" -eq "txt2" ] 
then 
    func2 $2 ; 
    exit 0; 
fi 

我得到的迴應是

sh script.sh txt1 
sh: txt1: bad number 
sh: txt1: bad number 
+1

而不是大量的級聯'if's,您可能需要使用'case'語句。 –

+0

順便說一下,它不僅僅是需要引號的測試,以確保內容不加修改地通過;你也希望'func1'$ 2「'和'func2」$ 2「' –

回答

1

您正在使用字符串比較錯誤的操作。你想使用=,而不是-eq(這是比較整數)。

請注意,[只是shell的一個內部命令,所以您需要將其與參數中的空格分開。 (在腳本中進行第三次測試。)

+1

可能還需要提供空格(在第二次調用中丟失)。 –

+0

感謝您的快速幫助。我對STCK OVFL和linux shell都很陌生。 此外,我認爲迴應會幫助像我這樣的新手尋找答案,而不是問題列表? – Ananth