1

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
  • 730,956
  • 141
  • 904
  • 1,278
jcrshankar
  • 1,165
  • 8
  • 25
  • 45
  • 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

3

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
  • 238,783
  • 38
  • 220
  • 352
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
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
  • 17,010
  • 4
  • 35
  • 61