Bash
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
與使用多個“或”測試相比,這顯然是一個更短的語句。
你可以使用
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
,您還可以使用擴展的 glob 模式:bash -O extglob``zsh -o kshglob
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
orzsh
,您還可以使用正則表達式比較: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