2016-11-03 20 views
1

我只是寫在bash腳本中,這樣的工作期望多長選項:爲什麼我在使用bash中的getopt的多長選項時出錯?

#!/bin/bash 
OPTS=`getopt -q -o fdhl: -l free,df,help,log: -- "$*"` 
#Check if error with getopt 
if [ $? != 0 ] 
then 
     echo -e "error: parameter could not be found\n\nUsage:\n supervision [options]\n\n Try 'supervision --help'\n or 'supervision -h'\n for additional help text." ;  
    exit 1 
fi 
eval set -- "$OPTS" 
while true ; do 
    case "$1" in 
     -f|--free) 
      free -h ; 
      shift;; 
     -d|--df) 
      df -h ; #Run df system command 
      shift;; 
     -l|--log) 
      case "$2" in 
       "") echo "miss file" ; 
         shift 2;; #No file passed as parameter 
       *) 
       df -h >> "$2" ; 
       shift 2;; 
      esac ;; 
     -h|--help) #Display help 
       shift;; 
     --) #End of parsed parameters list 
      shift ; break ;; 
     *) 
      break ;; 
    esac 
done 

我不知道爲什麼我應該,當我用1個多長的選項,例如:

sh myscript --free --df 

當我使用--log:

sh myscript --log logfile 

兩種情況下退出的,如果[$? != 0],看起來像第一個long選項後面的元素不會被解析。

+2

你必須描述你得到的錯誤,並將腳本減少到仍然產生錯誤的最短版本。在減少腳本的同時可能會發現問題。另見[mcve]。 –

+0

除了本傑明的建議,如果它是相關的,它將有助於發佈輸出。 – artdanil

+0

感謝您的迴應,只需編輯並縮短代碼並添加示例輸入/輸出即可。 – Kamja

回答

1

好吧,我想通了,這都是由於在getopt調用中使用「$ *」而不是「$ @」。我不完全是爲什麼,我猜兩者都做同樣的事情,但事實證明是導致問題的原因。

+0

查看你的手冊頁面以獲得澄清。我明確指出使用'$ *'而不是'$ @':「你不應該使用'getopt abo:」$ @「',因爲這會解析參數與下面設置的命令不同」 – artdanil

相關問題