测试变量是否为整数 [英] Testing if a variable is an integer
本文介绍了测试变量是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试变量$var
是否实际上是整数.我该怎么做?
I would like to test if my variable $var
is actually an integer or not. How can I please do that?
推荐答案
只要您使用的bash版本> = 3,就可以使用正则表达式:
As long as you're using bash version >=3 you can use a regular expression:
[[ $a =~ ^-?[0-9]+$ ]] && echo integer
此bash FAQ 提到了各种bash 3.x中bash regex实现中的不一致之处( 是否应使用正则表达式),在这种情况下,我认为在任何版本中都没有需要引用的字符,因此我们很安全.至少它对我有用:
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:
- 3.00.15(1)-发行版(x86_64-redhat-linux-gnu)
- 3.2.48(1)-发行版(x86_64-apple-darwin12)
- 4.2.25(1)-发行版(x86_64-pc-linux-gnu)
$ 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
这篇关于测试变量是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文