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