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 @ 2024-03-04 12:16  小鲨鱼2018  阅读(102)  评论(0编辑  收藏  举报