0

I need to check that the input consists only of numeric characters. I have the code below, but it didn't work properly.

if [[ $1 =~ [0-9] ]]; then
echo "Invalid input"
fi

It should give true only for 678686 not for yy66666.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
jcrshankar
  • 865
  • 8
  • 20
  • 38
  • possible duplicate of [BASH: Test whether string is valid as an integer?](http://stackoverflow.com/questions/2210349/bash-test-whether-string-is-valid-as-an-integer) – tripleee Sep 04 '13 at 17:35
  • The reverse test is often more concise: `[[ $1 =~ [^[:digit:]] ]] && echo Invalid` -- if you find one non-digit, it's invalid – glenn jackman Jun 13 '14 at 11:18

2 Answers2

2

How about this:-

re='^[0-9]+$'
if ! [[ $Number =~ $re ]] ; then
   echo "error: Invalid input" >&2; exit 1
fi

or

case $Number in
    ''|*[!0-9]*) echo nonnumeric;;
    *) echo numeric;;
esac
glenn jackman
  • 223,850
  • 36
  • 205
  • 328
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
1

Try using start/end anchors with your pattern. If you don't, the match succeeds with a part of a test string. Don't forget that you have to use a pattern matching the complete test string if you follow this suggestion.

if [[ $1 =~ ^[0-9]+$ ]]; then
echo "Invalid input"
fi

Check out this SO post for more details.

Community
  • 1
  • 1
collapsar
  • 16,200
  • 4
  • 33
  • 60