
我正在尋找一個“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 extglob
或zsh -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
,ksh93
或zsh
,您也可以使用正規表示式比較:
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
您也可以使用關聯數組。檢查某個鍵是否存在是in
Bash 提供的最接近運算子的事情。雖然文法有點難看:
declare -A arr
arr[cat]=1
arr[dog]=1
arr[mouse]=1
if [ "${arr[$1]+x}" ]; then
echo "$1 is in the array"
fi
答案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)
) 且後面跟著行尾 ($
)的任何行