/bin/sh에서 여러 var 값을 사용하여 test -eq 표현식을 축소하는 방법

/bin/sh에서 여러 var 값을 사용하여 test -eq 표현식을 축소하는 방법
#!/bin/sh
if [ $num -eq 9 -o $num -eq 75 -o $num -eq 200 ]; then
    echo "do this"
elif [ $num -eq 40 -o $num -eq 53 -o $num -eq 63]; then
    echo "do something for this"
else
    echo "for other do this"
fi

문의 표현을 좁힐 수 있는 다른 방법이 있나요 if? 어쩌면 좋아

[ $num -eq (9,75,200) ]

그런데 이 OS에는 GNU 유틸리티가 없습니다.

답변1

때로는 다른 구조가 더 읽기 쉬울 수도 있습니다.

case $num in
9|75|200) echo "do this" ;;
40|53|63) echo "do something for this" ;;
*)        echo "for other do this" ;;
esac

답변2

주의하세요. posix는 4개 이상의 매개변수로 테스트를 정의하지 않으므로 테스트 구조는 다음과 같습니다.명확하지 않다. 보다여섯 번째 대히트 트랩

따라서 테스트를 사용하는 경우 더 자세히 설명해야 합니다.

if [ "$arg" = 9 ] || [ "$arg" = 75 ] || [ "$arg" = 200 ]

또는 대신 사용 사례

case "$arg" in
     9|75|200)  do something ; ;
     40|53|63)  do that ;;
      *)  else ... ;;
 esac

답변3

이것은 기능에 대한 작업처럼 들립니다.

test_num() {
  n=$1; shift
  for arg do
    [ "$arg" -eq "$n" ] && return 0
  done
} 2>/dev/null

if test_num "$num" 9 75 200; then
  echo "do this"
elif test_num "$num" 40 53 63; then
  echo "do something for this"
else
  echo "for other do this"
fi

답변4

또 다른 POSIX 솔루션:

if     printf '%s' "$num" | grep -xE '(9|75|200)' >/dev/null; then
       echo "do this"
elif   printf '%s' "$num" | grep -xE '(40|53|63)' >/dev/null; then
       echo "do something for this"
else
       echo "for other do this" 
fi

이 옵션은 매우 느립니다. case이 옵션보다 50배 느립니다.


다음은 더 짧은 스크립트이며, 케이스 옵션만 두 배 더 오래 걸리는 더 간단한 스크립트라고 생각합니다.

#!/bin/sh

num="$1"    a='9 75 200'    b='40 53 63'

tnum() {
    for    arg
    do     [ "$arg" = "$num" ] && return 0
    done   return 1
}

if     tnum $a; then
            echo "do this"
elif   tnum $b; then
            echo "do something for this"
else
            echo "for other do this"
fi

참고: [ "$arg" = "$num" ]모든 상황에서 유효한 테스트는 없습니다. 00 = 0예를 들어 이 테스트는 실패합니다.
그리고 수치 테스트는 [ "$arg" -eq "$num" ]null 값과 일치하지 않습니다 [ "" -eq "" ].

상황에 가장 적합한 방법을 선택할 수 있습니다.

관련 정보