Checking if an input number is an integer
Remove quotes
if ! [[ "$scale" =~ ^[0-9]+$ ]]
then
echo "Sorry integers only"
fi
Use -eq
operator of test command:
read scale
if ! [ "$scale" -eq "$scale" ] 2> /dev/null
then
echo "Sorry integers only"
fi
It not only works in bash
but also any POSIX shell. From POSIX test documentation:
n1 -eq n2
True if the integers n1 and n2 are algebraically equal; otherwise, false.
As the OP seems to want only positive integers:
[ "$1" -ge 0 ] 2>/dev/null
Examples:
$ 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
Note that a single [
test is required:
$ [[ "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
This is because dereferencing occurs with [[
:
$ word=other
$ other=3
$ [[ $word -eq 3 ]] && echo word equals other equals 3
word equals other equals 3