Bash/bourne에 "in" 연산자가 있나요?

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

예를 들어 여러 "또는" 테스트를 사용하는 것과 비교하면 분명히 훨씬 짧은 명령문입니다.

답변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

연관 배열을 사용할 수도 있습니다. 키가 존재하는지 확인하는 것은 inBash가 제공하는 연산자에 가장 가까운 것입니다. 구문이 약간 보기 흉하지만:

declare -A arr
arr[cat]=1
arr[dog]=1
arr[mouse]=1

if [ "${arr[$1]+x}" ]; then
        echo "$1 is in the array"
fi

(${arr[$1]+x}설정된 x경우 확장되고 그렇지 않으면 비어 있습니다.arr[$1])

답변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))로 시작하는( ) 줄과 줄 끝( $) 이 오는 모든 줄과 일치합니다.

관련 정보