2016-10-08 125 views
0

我在BASH .sh腳本中有一個while-do循環,它執行簡單的命令行參數分析。 當我傳遞某些參數時,它們被解析沒有問題(即-w,-s,-d參數)。 但是,如果我傳遞任何其他參數,看起來像循環什麼都不做,並且腳本在while循環結束後繼續執行代碼。Linux bash代碼不能在執行while循環中執行

「echo」命令都不會打印任何內容。 示例-h,--help,-c,--complete,-e。 我甚至嘗試使用非識別參數,如-a -f等。

請幫忙嗎? while循環是:

while [[ $# -gt 1 ]] 
do 
key="$1" 
src_not_valid=false 
dst_not_valid=false 
site_not_valid=false 
complete_bucket_copy=false 
exclude_worker=false 

echo key $key 

case $key in 
    -w|--website) 
    SITE="$2" 
    shift # past argument 
    ;; 
    -s|--source) 
    SRC_ENV="$2" 
    shift # past argument 
    ;; 
    -d|--dest) 
    DST_ENV="$2" 
    shift # past argument 
    ;; 
    -c|--complete) 
    echo "Complete bucket copy option ON" 
    complete_bucket_copy=true 
    ;; 
    -e|--exlude-worker) 
    echo "Exclude worker option ON" 
    exclude_worker=true 
    ;; 
    -h|--help) 
    echo $str_help 
    exit 
    ;; 
    *) 
      # unknown option 
    echo "$2 option not recognized\r\n$usage" 
    exit 
    ;; 
esac 
shift # past argument or value 
done 

更新:我忘了提,這一工作接受參數的所有參數,例如「script-name.sh -w富-s酒吧-d約翰」 但參數不起作用,沒有參數,示例-h或--help

+0

抱歉後,我加入了,但即使這樣的「退出」不如果我傳遞的參數不是-w,-s或-d,則會生效。 – Pixel

+1

你正在使用的測試是(用算術語法編寫的):'(($#> 1))'(是的,'-gt'是_greater than_),但是你的意思是'(($#> = 1)) ':所以使用'[[$#-ge 1]]'('-ge'是_greater than或equal_);或者更好,只是使用算術上下文(因爲這就是你在做什麼:算術):'while(($#> = 1)); then';甚至是'while(($#)); then'。 –

+0

@gniourf_gniourf謝謝,它的工作原理!我現在不能添加+1投票:( – Pixel

回答

0

當只有一個參數時,甚至不會輸入循環。

你必須while [[ $# -ge 1 ]]

改變while [[ $# -gt 1 ]] BTW您的聯機幫助字符串是空的,這不利於調試太:)

+0

謝謝,它的工作! – Pixel