簡體   English   中英

包括*選項時,case語句無法正確執行

[英]case statement not executing properly when the * option is included

我有一個案例腳本如下:

 for i in "$@"; do
arg=( $@ )
    case $i in
 --string)
          for ((i=0; i<${#arg[@]}; i++)) ; do
           if [ "${arg[$i]}" == "--string" ] ; then
                ((i++))
                 STRING=${arg[$i]}
           fi
          done
          ;;
*)
          print_help
          exit
          ;;
  esac
done

當我運行./test --some_command --string pattern; 它顯示幫助選項。 當我運行./test --some_command --string模式而在字符串中不帶*)選項時,它可以工作。

你能告訴我如何解決這個問題嗎?

另一個例子 :

#!/bin/bash

test(){

        echo i am testing this now
}

print_help()
{
  echo help
}

for i in "$@"; do
arg=( $@ )
    case $i in
 --string)
          for ((i=0; i<${#arg[@]}; i++)) ; do
           if [ "${arg[$i]}" == "--string" ] ; then
                ((i++))
                 STRING=${arg[$i]}
           fi
          done
                echo $STRING
          ;;
 --test)
        test
        ;;

 *)
          print_help
          exit
          ;;
  esac
done

當我運行./test --string pattern --test。 打印模式幫助

當for循環進入“模式”時,case分支不會覆蓋該循環,因此它將命中默認分支並輸出幫助。 您必須以一種更明智的方式遍歷參數。 用替換for循環

while (( $# > 0 )); do
    arg=$1
    shift
    case $arg in
        --string) STRING=$1; shift; echo "$STRING" ;;
        --some-command) : ;;
        --) break ;;
        *) print_help; exit ;;
    esac
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM