帶參數的 shell 的輸入順序是問題

帶參數的 shell 的輸入順序是問題
     while (("$#"))
do
opt="$1";
    shift;
        case "$opt" in
           "-c" | "--create") create_flag=1 ;;
           "-up" | "--update") update_flag=1 ;;
           "-q" | "--query")  query_flag=1 ;;
           "-csr"| "--createabc") createsr_flag=1 ;; 
           "-g" | "--getconf") getconfig_flag=1 ;;
           "-catt" | "--createandattach") createattach_flag=1 ;;
           "-att" | "--attach") attach_flag=1 ;;
           "--val1" ) callerId="$1" ;;
           "--val2" ) title="$1" ;;
           "--val3" ) urgency="$1" ;;
           "--val4" ) environment="$1" ;;
           "--val5" ) failType="$1" ;;
           "--val6" ) jobName="$1" ;;
           "--val7" ) jobType="$1" ;;
              # usage();;
              # "*" )
              # OPTIONAL="${opt#*=}";;             #take argument
              # *) echo >&2 "Invalid option: $@"; exit 1;;
            esac

            shift 
    done     

跑步

 script.sh -c --val1 123456  

不起作用!

  script.sh --val1 123456  -c 

這有效!

你能解釋為什麼嗎?

答案1

shift每次迭代您都會無條件地呼叫兩次。這對於這種--valN情況是可取的,但對於不採用以下參數的選項則不然。您可以採用一般情況並將其嵌套在其中以減少重複:

case "$opt" in
    "-c" | "--create") create_flag=1 ;;
    "--val?" )
        case "$opt" in
            "--val1" ) callerId="$1" ;;
        esac
        shift
        ;;
esac

或撒入shift所有帶有參數的選項,例如:

case "$opt" in
    "-c" | "--create") create_flag=1 ;;
    "--val1" ) callerId="$1" ; shift ;;
esac

您可能還會發現獲取選擇對於解析 bash 中的選項很有用。

答案2

因為您的 while 迴圈無條件移位兩次,即使選項不帶參數也是如此。第二個命令行的順序只是運氣好。

相關內容