1. 程式人生 > >Linux shell示例(三)

Linux shell示例(三)

\n str ons echo return NPU inux pre ech

example No. 1
作為shell編寫人員,要避免使用者輸入數據的格式不正確,也就是要在shell腳本發布前攔截可能的錯誤;本示例是對使用者輸入的數據(或位置變量)進行判斷是否可用,然後在符合條件時調用代碼塊;

#!/bin/bash
#shell name: shell_vaild.sh
#used:輸入密碼後判斷密碼是否是由數字和字母組成,判斷輸入的IP是否合法等
#author by woon
#定義函數
vaild_pass() 
{
    decide=$(echo $1 | sed -e "s/[^[:alnum:]]//g")
    if [ "$decide" != "$pass" ];then
        return 1
    else
        return 0
    fi
}

#
read -t 10 -p "Please input IP address:" ipaddr
read -s -p "Please input the password:" pass
echo
#判斷輸入是否為空;空退出程序
if [ -z $ipaddr] || [ -z $pass ];then
    echo "輸入錯誤\n"
    exit 2
fi
if  ! vaild_pass "$pass";then
    echo "Your inpur must consist of only letters and numbers.">&2
else
    echo "Your password is vaild!"
fi

yn=$(echo $ipaddr|awk -F "." ‘{if($1<255&&$2<255&&$3<255&&$4<255){print "0"}else{print "1"}}‘)
    if [ $yn == "0" ];then
        echo "Your Ipaddr is vaild"
    else
        echo "Your IPADDR is not vaild."
        exit 1
    fi

Linux shell示例(三)