代码改变世界

shell 判断变量类型的几种方法

2020-05-26 10:09  方斌  阅读(5787)  评论(0编辑  收藏  举报

shell 判断变量类型的几种方法

方法一

脚本如下

#!/usr/bin/env bash

function check(){
    local a="$1"
    printf "%d" "$a" &>/dev/null && echo "integer" && return
    printf "%d" "$(echo $a|sed 's/^[+-]\?0\+//')" &>/dev/null && echo "integer" && return
    printf "%f" "$a" &>/dev/null && echo "number" && return
    [ ${#a} -eq 1 ] && echo "char" && return
    echo "string"
}

echo ". is" $(check ".")
echo "1 is" $(check "1")
echo ".1 is" $(check ".1")
echo "1. is" $(check "1.")
echo "1234 is" $(check "1234")
echo "1.234 is" $(check "1.234")
echo "1.2.3.4 is" $(check "1.2.3.4")
echo "a1234 is" $(check "a1234")
echo "abc is" $(check "abc")
echo "a is" $(check "a")
echo "1e+2" $(check "1e+2")
echo "1.e+2" $(check "1e+2")
echo ".1e+2" $(check "1e+2")
echo "-1" $(check "-1")
echo "-1.2" $(check "-1.2")
echo "-a" $(check "-a")
echo "0x1f" $(check "0x1f")
echo "0x1H" $(check "0x1H")
echo "0333" $(check "0333")
echo "0999" $(check "0999")
echo "+003" $(check "+003")
echo "+003.3" $(check "+003.3")

输出结果如下:

. is char
1 is integer
.1 is number
1. is number
1234 is integer
1.234 is number
1.2.3.4 is string
a1234 is string
abc is string
a is char
1e+2 number
1.e+2 number
.1e+2 number
-1 integer
-1.2 number
-a string
0x1f integer
0x1H string
0333 integer
0999 number
+003 integer
+003.3 number

方法二

#!/bin/bash
#

echo $a|grep [a-zA-Z]>/dev/null
if [ $? -eq 0 ];then
echo "string"
else
echo "data"
fi

方法三

#!/bin/bash
#

if [[ $a != *[^0-9]* ]]&&[[ $a != 0* ]]
then
echo $a is data
else
echo $a is string
fi

————————————————
版权声明:本文为CSDN博主「qq_17528659」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_17528659/java/article/details/87183363