2017-02-03 195 views
2

我試圖將參數傳遞給我編寫的腳本,但無法正確理解。Bash腳本參數

我要的是一個沒有標誌一個強制的說法,並與國旗兩個可選參數,因此它可以被稱爲是這樣的:

./myscript mandatory_arg -b opt_arg -a opt_arg 

./myscript mandatory_arg -a opt_arg 
./myscript mandatory_arg -b opt_arg 

我看着getopts的和得到這個:

while getopts b:a: option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

if "$1" = ""; then 
    exit 
fi 

echo "$1" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

但它根本不起作用。

回答

3

假設你強制性參數出現最後,那麼你應該嘗試下面的代碼:[評論在線]

OPTIND=1 
while getopts "b:a:" option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

# reset positional arguments to include only those that have not 
# been parsed by getopts 

shift $((OPTIND-1)) 
[ "$1" = "--" ] && shift 

# test: there is at least one more argument left 

((1 <= ${#})) || { echo "missing mandatory argument" 2>&1 ; exit 1; }; 

echo "$1" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

結果:

~$ ./test.sh -b B -a A test 
test 
B 
A 
~$ ./tes.sh -b B -a A 
missing mandatory argument 

如果你真的想要mandato RY參數出現第一,那麼你可以做以下的事情:

MANDATORY="${1}" 
[[ "${MANDATORY}" =~ -.* ]] && { echo "missing or invalid mandatory argument" 2>&1; exit 1; }; 

shift # or, instead of using `shift`, you can set OPTIND=2 in the next line 
OPTIND=1 
while getopts "b:a:" option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

# reset positional arguments to include only those that have not 
# been parsed by getopts 

shift $((OPTIND-1)) 
[ "$1" = "--" ] && shift 

echo "$MANDATORY" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

結果如下:

~$ ./test.sh test -b B -a A 
test 
B 
A 
~$ ./tes.sh -b B -a A 
missing or invalid mandatory argument 
+0

當試圖運行這個它打印出的強制性參數,然後「 「對於可選項,如果我沒有強制性地運行,它會回答」缺少強制性參數「 –

+0

不推薦先強制性參數的原因是什麼?並且我認爲上次編輯時丟失了一些東西 –

+0

@ A.Jac這只是*約定*和*個人品味的問題* –