Let's suppose we have a variable named
myvar
. How do you decide (in a safe way!) in a standard POSIX shell (or in the almost equivalent
/bin/sh
of the Debian distros) whether it contains a number or not? Sounds pretty much trivial, not? Here's what I came up with:
mynumber=_
mynumber=$(($myvar)) 2> /dev/null
{ [ "$mynumber" = "_" ] && echo "Myvar is not a number."; } || echo "Myvar is a number."
Or you could rely on the exit value of the
$(( ))
expression, like this:
mynumber=$(($myvar)) 2> /dev/null
{ [ $? -ne 0 ] && echo "Myvar is not a number."; } || echo "Myvar is a number."
Recent comments
2 years 34 weeks ago
4 years 3 weeks ago
4 years 3 weeks ago
4 years 5 weeks ago
4 years 6 weeks ago
4 years 13 weeks ago
4 years 13 weeks ago
4 years 13 weeks ago
4 years 13 weeks ago
4 years 14 weeks ago