Iurie
Iurie

Reputation: 2248

Bash - why the "0" is not recognized as a number?

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

Upvotes: 0

Views: 452

Answers (2)

glenn jackman
glenn jackman

Reputation: 246837

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])) ]]

Upvotes: 1

CharlesB
CharlesB

Reputation: 90336

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.

Upvotes: 4

Related Questions