I would like to test if my variable $var
is actually an integer or not. How can I please do that?
The standard solution to check if a given variable is an integer or not is using the isinstance() function. It returns True if the first argument is an instance of the second argument.
To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.
Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.
As long as you're using bash version >=3 you can use a regular expression:
[[ $a =~ ^-?[0-9]+$ ]] && echo integer
While this bash FAQ mentions inconsistencies in the bash regex implementation in various bash 3.x (should the regex be quoted or not), I think in this case, there are no characters that need quoting in any version, so we are safe. At least it works for me in:
$ a="" $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer $ a=" " $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer $ a="a" $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer $ a='hello world!' $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer $ a='hello world 42!' $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer $ a="42" $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer integer $ a="42.1" $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer $ a="-42" $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer integer $ a="two" $ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
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