Reputation: 853
I'm working with shell scripting in Linux. I want to check if the value of MAX_ARCHIVE_AGE
is numeric or not. My code is like this:
MAX_ARCHIVE_AGE = "50"
expr="*[0-9]*"
if test -z "$MAX_ARCHIVE_AGE";
then
echo "MAX_ARCHIVE_AGE variable is missing or not initiated"
else
if [ "$MAX_ARCHIVE_AGE" != $expr ]
then
echo "$MAX_ARCHIVE_AGE is not a valid value"
fi
fi
I want to match the value of MAX_ARCHIVE_AGE
with my expr. Please help.
Upvotes: 1
Views: 124
Reputation: 189327
For POSIX compatibility, look at case
. I also find it more elegant than the corresponding if
construct, but the syntax may seem a bit odd when you first see it.
case $MAX_ARCHIVE_AGE in
'' ) echo "empty" >&2 ;;
*[!0-9]* ) echo "not a number" >&2 ;;
esac
By the way, notice the redirection of error messages to standard error with >&2
.
Upvotes: 4
Reputation: 183251
Your expr
will match anything that contains any digits; it's better to check if it contains only digits, or conversely, to check if it contains any non-digits. To do that, you can write:
if ! [[ "$MAX_ARCHIVE_AGE" ]] ; then
echo "MAX_ARCHIVE_AGE is blank or uninitialized" >&2
elif [[ "$MAX_ARCHIVE_AGE" == *[^0-9]* ]] ; then
echo "$MAX_ARCHIVE_AGE is not a valid value" >&2
fi
Also, note that you would initialize MAX_ARCHIVE_AGE
by writing e.g. MAX_ARCHIVE_AGE=50
(no spaces), not MAX_ARCHIVE_AGE = 50
. The latter tries to run a program called MAX_ARCHIVE_AGE
with the arguments =
and 50
.
Upvotes: 2