shell判斷變量是字符仍是數字

  ok,之後最好是天天一個shell小腳本吧,這樣之後工做時還能夠直接套用,嗯,比較不錯,順便還能夠帶給剛入門shell的朋友一些幫助,好了,廢話很少說,下面是我兩種判斷的實現方式:shell

  一、經過grep去篩選非數字,判斷其輸出狀態,如下兩種方式:bash

#!/bin/bash
read -p "please input a num: " num if echo $num | grep -q '[^0-9]' then echo "this is not a num,please input num" exit 1 fi
#!/bin/bash
read -p "please input a num: "  num
echo $num | grep -q '[^0-9]'
n1=$?
if [ $n1 -eq 0 ]
then
        echo "this is not a num,please input num"
        exit 1
fi

  二、經過用sed 's///g'替換的方式,把數字替換爲null,而後去判斷輸出是否爲null,若是不爲null,則說明有字符啦this

#!/bin/bash
read -p "please input a num: "  num
n1=`echo $num|sed 's/[0-9]//g'`
if [ ! -z $n1 ]
then
        echo "this is not a num,please input num"
        exit 1
fi
相關文章
相關標籤/搜索