shell中判断是否为整数的方法

跟風遠走 提交于 2020-03-11 16:51:00

方法一:使用字符串过滤出非0到9之间的字符。

[root@managevm1 ~]# a=123

[root@managevm1 ~]# echo $a | grep "[^0-9]" && echo "a isn't an integer" \    

|| echo "a is an integer"      

a is an integer      

[root@managevm1 ~]# a=123.4    

[root@managevm1 ~]# echo $a | grep "[^0-9]" && echo "a isn't an integer" \  

|| echo "a is an integer"    

a isn't an integer  

也可以写为

[root@managevm1 ~]# echo $a | grep -v "[0-9]*" && echo "a isn't an integer"\  

|| echo "a is an integer"

方法二:使用条件判断,$a中0到9出现一次以上,且不包含其他字符。


[root@managevm1 ~]# a=123

[root@managevm1 ~]# if [[ $a =~ ^[0-9]\{1,\}$ ]]; then echo "a is an integer;"\

else echo "a is not an integer"; fi    

a is an integer    

[root@managevm1 ~]# a=123.4    

[root@managevm1 ~]# if [[ $a =~ ^[0-9]\{1,\}$ ]]; then echo "a is an integer;"\  

else echo "a is not an integer"; fi    

a is not an integer    

这个命令也可以简单写成    

[root@managevm1 ~]# [[ $a =~ ^[0-9]*$ ]] && echo "a is an integer" || \  

echo "a is not an integer"  

方法三:awk过滤


[root@managevm1 ~]# echo $a|awk '/^[0-9]*$/{print "a is an integer"}'    

a is an integer  

或写成    

[root@managevm1 ~]# echo $a|awk '{if ($1~/^[0-9]*$/) print "a is an integer"}'    

a is an integer

方法四:使用命令bc来计算,因为shell不支持浮点预算,非整数a的值除1后会得到整数部分与原值不符合

注意这里使用 == 是做字符串的比较非数值比较。数值比较用 -eq , 不支持浮点。

[root@managevm1 ~]# a=123

[root@managevm1 ~]# [ $(echo $a/1|bc) == "$a" ] && echo "It's an integer" \  

|| echo "It's not an integer"  

It's an integer  

[root@managevm1 ~]# a=123.4  

[root@managevm1 ~]# [ $(echo $a/1|bc) == "$a" ] && echo "It's an integer" \  

|| echo "It's not an integer"  

It's not an integer

方法五:利用test下不支持浮点数比较的特性,通过命令的返回状态来判断。

[root@managevm1 ~]# a=123

[root@managevm1 ~]# [ $a -ge 0 ] 2>/dev/null && echo "A is an integer"|| \

echo "a is NOT an integer"

A is an integer

[root@managevm1 ~]# a=123.4

[root@managevm1 ~]# [ $a -ge 0 ] 2>/dev/null && echo "A is an integer"|| \

echo "a is NOT an integer"

a is NOT an integer
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!