0

I found an interesting Bash script that will test if a variable is numeric/integer. I like it, but I do not understand why the "0" is not recognized as a number? I can not ask the author, hi/shi is an anonymous.

#!/bin/bash

n="$1"

echo "Test numeric '$n' "
if ((n)) 2>/dev/null; then
n=$((n))
echo "Yes: $n"
else
echo "No: $n"
fi

Thank you!

UPDATE - Apr 27, 2012.

This is my final code (short version):

#!/bin/bash

ANSWER=0
DEFAULT=5
INDEX=86

read -p 'Not choosing / Wrong typing is equivalent to default (#5): ' ANSWER;

shopt -s extglob
if [[ $ANSWER == ?(-)+([0-9]) ]]
  then ANSWER=$((ANSWER));
  else ANSWER=$DEFAULT;
fi

if [ $ANSWER -lt 1 ] || [ $ANSWER -gt $INDEX ]
  then ANSWER=$DEFAULT;
fi
Yurié
  • 2,148
  • 3
  • 23
  • 40
  • 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) – Adrian Frühwirth Apr 24 '14 at 09:11

2 Answers2

4

It doesn't test if it is a numeric/integer. It tests if n evaluates to true or false, if 0 it is false, else (numeric or other character string) it is true.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
1

use pattern matching to test:

if [[ $n == *[^0-9]* ]]; then echo "not numeric"; else echo numeric; fi

That won't match a negative integer though, and it will falsely match an empty string as numeric. For a more precise pattern, enable the shell's extended globbing:

shopt -s extglob
if [[ $n == ?(-)+([0-9]) ]]; then echo numeric; else echo "not numeric"; fi

And to match a fractional number

[[ $n == @(?(-)+([0-9])?(.*(0-9))|?(-)*([0-9]).+([0-9])) ]]
glenn jackman
  • 238,783
  • 38
  • 220
  • 352