Bash

bash/bourne 中是否有“in”運算符?

  • June 6, 2018

我正在尋找一個像這樣工作的“in”運算符:

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

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

你可以使用caseesac

$ 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, ksh93or 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

引用自:https://unix.stackexchange.com/questions/447430