bash/bourne 中有「in」運算符嗎?

bash/bourne 中有「in」運算符嗎?

我正在尋找一個“in”運算符,其工作原理如下:

if [ "$1" in ("cat","dog","mouse") ]; then
    echo "dollar 1 is either a cat or a dog or a mouse"
fi

與使用多個“或”測試相比,這顯然是一個簡短得多的語句。

答案1

您可以使用case...esac

$ cat in.sh 
#!/bin/bash

case "$1" in 
  "cat"|"dog"|"mouse")
    echo "dollar 1 is either a cat or a dog or a mouse"
  ;;
  *)
    echo "none of the above"
  ;;
esac

前任。

$ ./in.sh dog
dollar 1 is either a cat or a dog or a mouse
$ ./in.sh hamster
none of the above

通過ksh,bash -O extglobzsh -o kshglob,您也可以使用擴充的 glob 模式:

if [[ "$1" = @(cat|dog|mouse) ]]; then
  echo "dollar 1 is either a cat or a dog or a mouse"
else
  echo "none of the above"
fi

使用bash,ksh93zsh,您也可以使用正規表示式比較:

if [[ "$1" =~ ^(cat|dog|mouse)$ ]]; then
  echo "dollar 1 is either a cat or a dog or a mouse"
else
  echo "none of the above"
fi

答案2

bash 中沒有「in」測試,但有正規表示式測試(bourne 中沒有):

if [[ $1 =~ ^(cat|dog|mouse)$ ]]; then
    echo "dollar 1 is either a cat or a dog or a mouse"
fi

通常使用變數編寫(引用問題較少):

regex='^(cat|dog|mouse)$'

if [[ $1 =~ $regex ]]; then
    echo "dollar 1 is either a cat or a dog or a mouse"
fi

對於較舊的 Bourne shell,您需要使用大小寫匹配:

case $1 in
    cat|dog|mouse)   echo "dollar 1 is either a cat or a dog or a mouse";;
esac

答案3

case如果您想要匹配一組固定的寵物,那麼使用 a就很好。但如果您需要在運行時建立模式,它就不起作用,因為它case不會解釋擴展參數內的交替。

這將僅匹配文字字串cat|dog|mouse

patt='cat|dog|mouse'
case $1 in 
        $patt) echo "$1 matches the case" ;; 
esac

但是,您可以將變數與正規表示式匹配一起使用。只要變數沒有被引用,其中的任何正規表示式運算子都有其特殊意義。

patt='cat|dog|mouse'
if [[ "$1" =~ ^($patt)$ ]]; then
        echo "$1 matches the pattern"
fi

您也可以使用關聯數組。檢查某個鍵是否存在是inBash 提供的最接近運算子的事情。雖然文法有點難看:

declare -A arr
arr[cat]=1
arr[dog]=1
arr[mouse]=1

if [ "${arr[$1]+x}" ]; then
        echo "$1 is in the array"
fi

${arr[$1]+x}x如果已設置,則擴展為空arr[$1],否則為空。

答案4

grep方法。

if echo $1 | grep -qE "^(cat|dog|mouse)$"; then 
    echo "dollar 1 is either a cat or a dog or a mouse"
fi
  • -q以避免任何輸出到螢幕(比鍵入更快>/dev/null)。
  • -E對於擴展正則表達式(cat|dog|mouse)方面需要這個。
  • ^(cat|dog|mouse)$符合^以 cat、dog 或 mouse ( )開頭 ( (cat|dog|mouse)) 且後面跟著行尾 ( $)的任何行

相關內容