How can I check if MyVar
contains only digits with an if
statement with BASH. By digits I am referring to 0-9.
ie:
if [[ $MyVar does contain digits ]] <-- How can I check if MyVar is just contains numbers
then
do some maths with $MyVar
else
do a different thing
fi
To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.
Here it is:
#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]
then
echo "ok"
else
echo "no"
fi
It prints ok
if the first argument contains only digits and no
otherwise. You could call it with: ./yourFileName.sh inputValue
[[ $myvar =~ [^[:digit:]] ]] || echo All Digits
Or, if you like the if-then
form:
if [[ $myvar =~ [^[:digit:]] ]]
then
echo Has some nondigits
else
echo all digits
fi
In olden times, we would have used [0-9]
. Such forms are not unicode safe. The modern unicode-safe replacement is [:digit:]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With