입력이 정수인지 확인하려고하는데 100 번 이상 입력했지만 오류가 표시되지 않습니다. 아아, 그것은 작동하지 않습니다, 그것은 모든 입력 (숫자 / 문자)에 대해 if 문을 트리거합니다
read scale
if ! [[ "$scale" =~ "^[0-9]+$" ]]
then
echo "Sorry integers only"
fi
나는 따옴표로 놀았지만 놓쳤거나 아무것도하지 않았다. 내가 뭘 잘못 했니? 입력이 단지 INTEGER인지 테스트하는 더 쉬운 방법이 있습니까?
답변
따옴표 제거
if ! [[ "$scale" =~ ^[0-9]+$ ]]
then
echo "Sorry integers only"
fi
답변
테스트 명령의 -eq
연산자를 사용하십시오 .
read scale
if ! [ "$scale" -eq "$scale" ] 2> /dev/null
then
echo "Sorry integers only"
fi
bash
POSIX 셸뿐만 아니라 작동합니다 . POSIX 테스트 문서에서 :
n1 -eq n2
True if the integers n1 and n2 are algebraically equal; otherwise, false.
답변
부호없는 정수의 경우 다음을 사용합니다.
read -r scale
[ -z "${scale//[0-9]}" ] && [ -n "$scale" ] || echo "Sorry integers only"
테스트 :
$ ./test.sh
7
$ ./test.sh
777
$ ./test.sh
a
Sorry integers only
$ ./test.sh
""
Sorry integers only
$ ./test.sh
Sorry integers only
답변
OP는 양의 정수 만 원하는 것처럼 보입니다.
[ "$1" -ge 0 ] 2>/dev/null
예 :
$ is_positive_int(){ [ "$1" -ge 0 ] 2>/dev/null && echo YES || echo no; }
$ is_positive_int word
no
$ is_positive_int 2.1
no
$ is_positive_int -3
no
$ is_positive_int 42
YES
단일 [
테스트가 필요합니다.
$ [[ "word" -eq 0 ]] && echo word equals zero || echo nope
word equals zero
$ [ "word" -eq 0 ] && echo word equals zero || echo nope
-bash: [: word: integer expression expected
nope
다음과 [[
같이 역 참조가 발생하기 때문입니다 .
$ word=other
$ other=3
$ [[ $word -eq 3 ]] && echo word equals other equals 3
word equals other equals 3
답변
( scale=${scale##*[!0-9]*}
: ${scale:?input must be an integer}
) || exit
확인하고 오류를 출력합니다.