2014-10-11 32 views
2

我必須寫一個bash腳本:所需的選項getopts的linux的

schedsim.sh [-h] [-C#CPUs ] -i pathfile 

H和c是可選的選項。我是必需的,當運行腳本,如果它沒有我選擇 - >錯誤消息。

如何在getopts中設置必要的選項? 謝謝!

另一個問題:如何使選項參數的默認值?例如,如果c沒有提供參數 - > c的參數默認值是1.

回答

5

您不能創建一個參數,因爲「getopts builtin返回一個錯誤,如果該參數缺失」。

但它是微不足道的做,做一個函數自己:

#!/bin/bash 

function parseArguments() { 
    local b_hasA=0 
    local b_hasB=0 
    local b_hasC=0 

    while getopts 'a:b::c' opt "[email protected]"; do 
    case $opt in 
    'a') 
     b_hasA=1 
     ;; 
    'b') 
     b_hasB=1 
     ;; 
    'c') 
     b_hasC=1 
     ;; 
    esac 
    done 

    if [ $b_hasA -ne 0 ]; then 
    echo "A present" 
    fi 
    if [ $b_hasB -ne 0 ]; then 
    echo "B present" 
    fi 
    if [ $b_hasC -ne 0 ]; then 
    echo "C present" 
    else 
    echo "Error: C absent" 
    exit 1 
    fi 
} 

#Quotes required to avoid removing characters in $IFS from arguments 
parseArguments "[email protected]" 

測試:

$ ./test.bash -c 
C present 

$ ./test.bash -b 
./test.bash: option requires an argument -- b 
Error: C absent 

$ ./test.bash -b foo 
B present 
Error: C absent