Bash / bourneに "in"演算子がありますか?

Bash / bourneに

次のように動作する "in"演算子を探しています。

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

これは明らかに複数の「or」テストを使用するよりもはるかに短いステートメントです。

ベストアンサー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

kshbash -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

bashksh93またはを使用すると、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

おすすめ記事