Shell环境下如何判断一个变量是否为整数呢?
这个问题看似简单确也有很多种方法。
思路:整数的单个数字是0-9,用正则表达式可以表示为[0-9]或[:digit:],判断是否为整数也就是判断变量中字符全为0到9之间的数字。
*以下方法没有考虑01234,001234或123.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