击:测试一个变量是一个整数 [英] Bash: Testing if a variable is an integer

查看:119
本文介绍了击:测试一个变量是一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试,如果我的变量 $ VAR 实际上是一个整数或没有。我怎么能麻烦你了?

I would like to test if my variable $var is actually an integer or not. How can I please do that?

推荐答案

只要你使用bash版本> = 3,你可以使用常规的前pression:

As long as you're using bash version >=3 you can use a regular expression:

[[ $a =~ ^-?[0-9]+$ ]] && echo integer

这个庆典FAQ 提到不一致的各种庆典3.X bash的正则表达式实现(的应该正则表达式来引用或不的),我想在这种情况下,有没有字符需要在任何版本的报价,所以我们是安全的。至少它为我的作品中:

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)-release下(x86_64-红帽Linux的GNU的)

  • 3.2.48(1) - 释放下(x86_64-苹果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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆