linux 中如何判断变量是否为数值

 

linux 中如何判断变量是否为数值

001、 利用正则表达式判断

a、

复制代码
[root@pc1 test1]# str1="abcd"    ## 字母字符串
[root@pc1 test1]# str2="100"     ## 数字字符串
[root@pc1 test1]# re="^[-+]?[0-9]+([.][0-9]+)?$"  ## ^表示开头;[-+]?表示正负号中没有或者一个;[0-9]+0到9的数字至少1个;.表示小数点;
[root@pc1 test1]# [[ $str1 =~ $re ]]            ## ([.][0-9]+)?表示.+数字 0个或者1个
[root@pc1 test1]# echo $?             ## 没有匹配数字,返回1
1
[root@pc1 test1]# [[ $str2 =~ $re ]]
[root@pc1 test1]# echo $?             ## 匹配数字,返回0
0
复制代码

 

b、测试小数

[root@pc1 test1]# str3="23.3240324"
[root@pc1 test1]# [[ $str3 =~ $re ]]       ## 测试小数
[root@pc1 test1]# echo $?                  ## 返回0
0

 

c、写成函数形式

复制代码
[root@pc1 test1]# cat test.sh              ## 函数脚本
#!/bin/bash
function is_num()                          ## 定义函数is_num
{
        re="^[-+]?[0-9]+([.][0-9]+)?$"
        if [[ $1 =~ $re ]]
        then
                return 0
        else
                return 1
        fi
}

if is_num $1        ## 函数调用, 函数调用的第一个参数 $1应当给与双引号,比避免通配符扩展和单词分割,我这里写的不规范
then
        echo "the first var is an number"
else
        echo "need an number"
fi
[root@pc1 test1]# bash test.sh abcd      ## 函数的第一个参数时abcd,非数字
need an number
[root@pc1 test1]# bash test.sh 388       ## 第一个参数时数值 388
the first var is an number
复制代码

 

  

reference:

01、https://mp.weixin.qq.com/s?__biz=Mzg4ODA5NDEwNw==&mid=2247484506&idx=1&sn=93cbf8a5b7ce7ef7c8505adc96f152eb&chksm=cf8128aef8f6a1b8e63cb448089b50e4e8c4cffe8e0c7c5e971f2b860274b95daa47e58d707c#rd

 

posted @   小鲨鱼2018  阅读(237)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-03-04 python中的内嵌函数
2021-03-04 python中函数的闭包
2021-03-04 python中的内嵌函数
2021-03-04 python中函数的global关键字
2021-03-04 python中函数的局部变量
2021-03-04 python中函数的收集参数
2021-03-04 python中函数形式参数、实际参数、位置参数、关键字参数
点击右上角即可分享
微信分享提示