自分なりに作ってみた。
単体コード
#!/bin/bash # check IPv4 address string is correct Command=`basename $0` # usage function usage() { cat << EOP usage: ${Command} IPv4-address EOP } if [ $# -ne 1 ] then echo "Failed." usage exit 1 fi # get VPN Gate server address IP=$1 ## check IP # count dots NumDot=`echo -n $IP | sed -e 's@[^.]@@g' | wc -c` if [ ${NumDot} -ne 3 ]; then echo "Number of dot in IP-address is not 3." exit 1 fi # check number and digit of number TmpIP=${IP} LengthTmpIP=${#TmpIP} while [ ${LengthTmpIP} -gt 0 ] do # get top strings before 1st dot StrIPpart=`echo ${TmpIP} | grep -oP '^[0-9]*'` if [ ${#StrIPpart} -lt 1 ] then echo "No number in some area in IP-address." exit 1 fi # store IPtmp for next loop TmpIP=`echo ${TmpIP} | sed -e "s/^${StrIPpart}//"` # if head of TmpIP is ".", remove "." HeadLetter=`echo ${TmpIP:0:1}` if [[ $HeadLetter = "." ]] then TmpIP=${TmpIP#.} # if TmpIP has no letter, then finish loop if [ ${#TmpIP} -lt 1 ] then break fi fi # check StrIPpart is number expr $StrIPpart + 1 >/dev/null 2>&1 if [ $? -gt 1 ] then echo "Non-number-letters are included in IP-address." exit 1 fi # check StarIPpart is 0-255 if [[ $StrIPpart -lt 0 || $StrIPpart -gt 255 ]] then echo "Number of IP-address is out of range[0-255]." exit 1 fi LengthTmpIP=${#TmpIP} done exit 0
プログラム中で関数として利用
function checkIPstr() { local IP=$1 local NumDot=`echo -n $IP | sed -e 's@[^.]@@g' | wc -c` local TmpIP=${IP} local LengthTmpIP=${#TmpIP} local StrIPpart="" local HeadLetter="" ## check IP # count dots if [ ${NumDot} -ne 3 ]; then echo "Number of dot in IP-address is not 3." return 1 fi if [ $LengthTmpIP -lt 8 ] then echo "Too few address-letters." return 1 fi # check number and digit of number while [ ${LengthTmpIP} -gt 0 ] do # get top strings before 1st dot StrIPpart=`echo ${TmpIP} | grep -oP '^[0-9]*'` if [ ${#StrIPpart} -lt 1 ] then echo "No number in some area in IP-address." return 1 fi # store IPtmp for next loop TmpIP=`echo ${TmpIP} | sed -e "s/^${StrIPpart}//"` # if head of TmpIP is ".", remove "." HeadLetter=`echo ${TmpIP:0:1}` if [[ $HeadLetter = "." ]] then TmpIP=${TmpIP#.} # if TmpIP has no letter, then finish loop if [ ${#TmpIP} -lt 1 ] then break fi fi # check StrIPpart is number expr $StrIPpart + 1 >/dev/null 2>&1 if [ $? -gt 1 ] then echo "Non-number-letters are included in IP-address." return 1 fi # check StarIPpart is 0-255 if [[ $StrIPpart -lt 0 || $StrIPpart -gt 255 ]] then echo "Number of IP-address is out of range[0-255]." return 1 fi LengthTmpIP=${#TmpIP} done return 0 } ############## #### main #### ############## # get IP-address IP=$1 ## check IP-address-string RetCheckIPstr=`checkIPstr $IP` if [ $? -gt 0 ] then echo $RetCheckIPstr exit 1 fi exit 0