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