
次のように動作する "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
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シェルでは、大文字と小文字の一致を使用する必要があります。
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)
、その後に行の終わり()が続く$
すべての行と一致します。