views:

70

answers:

5

Hello,

I have a bash scripting question please.

I would like to test if my variable $var is actually an integer or not.

How can I please do that?

Thank you very much,

Jary

A: 

echo your_variable_here | grep "^-\?[0-9]*$" will return the variable if it is an integer and return nothing otherwise.

Fraxtil
Actually it will also print out the variable to stdout if it's an integer. You really want `grep -q`, which doesn't print to stdout, it only exits with 0 or non-0 if there is a match.
Adam Rosenfield
+5  A: 

BASH FAQ entry #54

Ignacio Vazquez-Abrams
Perfect, thank you.
Jary
A: 
shopt -s extglob
case "$var" in
 +([0-9]) ) echo "integer";
esac
ghostdog74
A: 
function is_int() { return $(test "$@" -eq "$@" > /dev/null 2>&1); }

input=0.3
input="a b c"
input=" 3 "
if $(is_int "${input}");
   then
   echo "Integer: $[${input}]"
else
   echo "Not an integer: ${input}"
fi
yabt
A: 

I was needing something that would return true only for positive integers (and fail for the empty string). I settled on this:

test -n "$1" -a "$1" -ge 0 2>/dev/null

the 2>/dev/null is there because test prints an error (and returns 2) if an input (to -ge) doesn't parse as an integer

I wish it could be shorter, but "test" doesn't seem to have a "quiet" option and treats "" as a valid integer (zero).

JasonWoof