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


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

  1、通過grep去篩選非數字,判斷其輸出狀態,以下兩種方式:

#!/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

  2、通過用sed 's///g'替換的方式,把數字替換為null,然后去判斷輸出是否為null,如果不為null,則說明有字符啦

#!/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

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM