is it possible? if so, how?
i want to check a variable whether is it a number or letter in an if-else statement
is it possible? if so, how?
i want to check a variable whether is it a number or letter in an if-else statement
echo $var | grep "^[0-9][0-9]*$"
if [ $? -eq "0" ]
then
statement when number
else
statement when char
fi
can explain to me why you do two [0-9][0-9]?
is it possible to just directly compare regex in the if-else statement?
u can use typeset to set variable type as int. like:-
typeset -i var
it will give error while assigned non-int value to it
$ var=sdf
$ ksh: sdf: bad number
after assignment u can chk for command status
if [ $? -eq "0" ]
then
statement when number
else
statement when non -int
fi
The if command simply evaluates another command, and examines its exit code to decide whether to take the then branch or the else branch (if present). You can use the expr command to match a string against a regular expression, or echo | grep. I would recommend case for this, though, even if it actually uses glob expressions, not true regular expressions.
Some shells also have built-in regex operators with the [[ conditional ]] syntax.
if echo "$var" | grep '[^0-9]'; then
echo not a number
fi
if expr "$var" : '[^0-9]' >/dev/null; then
echo not a number
fi
case $var in
*[!0-9]*) echo not a number;; # not a regex proper
esac
if [[ "$var" =~ [^0-9] ]] ; then
echo not a number
fi
All of these are more or less functionally equivalent. (They will not reject an empty string as not a number; implementing that is left as an exercise.)