2010-06-25 23 views
6

我有一個魚殼腳本,其默認行爲是在完成時發送電子郵件。我想修改它以響應命令行中的nomail參數。因此,例如,正常運行的腳本會產生一個電子郵件:使用可選參數編​​寫魚殼腳本

michaelmichael: ~/bin/myscript

但是,如果與nomail開關運行,也不會發送確認郵件:

michaelmichael: ~/bin/myscript nomail

如果我用nomail參數運行腳本,它運行良好。沒有nomail,是未定義的,它會引發錯誤。我搜查了魚殼文檔,但似乎找不到任何可行的工具。這裏是我到目前爲止

switch $argv 
    case nomail 
    ## Perform normal script functions 
    case ??? 
    ## Perform normal script functions 
    mailx -s "Script Done!" 
end 

運行,這將引發以下錯誤:

switch: Expected exactly one argument, got 0

顯然,期待一個說法,我只是不知道該語法告訴它不接受任何參數,或者如果存在的話。

我猜這是非常基本的,但我只是不明白shell腳本。

+0

如果您發佈的特定錯誤消息這是更有幫助。添加了 – 2010-06-25 14:29:37

+0

。對於那個很抱歉。 – michaelmichael 2010-06-25 14:34:25

回答

7

包裝你switch聲明是這樣的:

if set -q argv 
    ... 
end 

另外,我覺得你默認情況下應該是case '*'

+0

這工作(雖然'nomail'必須是默認情況下,而不是'*')。以下是我將它改爲:'if set -q argv;開關$ argv;案件nomail;回聲不發送郵件。案件 '*';回聲未指定的開關。結束;其他;回聲發送郵件。結束' – michaelmichael 2010-06-25 17:30:49

+0

@michaelmichael:默認情況下,我的意思是'switch'語句的缺省值,如果沒有指定的情況匹配,則執行該語句。您的評論中的代碼完全如何。對不起,我誤解了您的原始代碼並誤認爲「???」就好像它打算成爲'switch'默認值一樣。 – 2010-06-25 18:48:20

5

如果您更喜歡使用switch語句它也可以:

switch (echo $argv) 
    case nomail 
    ## Perform normal script functions 
    case '*' 
    ## Perform normal script functions 
    mailx -s "Script Done!" 
end