Bash正则表达式比较操作符

Bash正则表达式比较操作符

从Bash3.0开始,Bash有了内部的正则表达式比较操作符,使用"=~"表示。大部分使用grep或者sed命令的正则表达式编写脚本的方法可以由"=~"操作符的Bash表达式处理。

如果一个表达式左边的变量匹配到右边的正则表达式,则返回状态码0,否则返回1。

如:

检查一个数是否为十进制


[root@rs1 test2]# cat digit.sh 
#!/bin/bash

digit=$1
if [[ $digit =~ [0-9] ]]
then
    echo "$digit is a digit."
    else
        echo "Oops!"
fi

执行脚本:


[root@rs1 test2]# bash digit.sh 3
3 is a digit.
[root@rs1 test2]# bash digit.sh a
Oops!

检查输入是否为一个数字

[root@rs1 test2]# cat num.sh 
#!/bin/bash

#读取用户输入,并存入变量num
read -p "Input a number,Please:" num

#如果变量num的值是一串数字,则执行if语句,否则执行else语句
if [[ $num =~ ^[0-9]+$ ]]
then
    echo "$num is a number."
else
    echo "$num is not a number."
fi

执行脚本:


[root@rs1 test2]# bash num.sh 
Input a number,Please:12
12 is a number.
[root@rs1 test2]# bash num.sh 
Input a number,Please:ad
ad is not a number.
[root@rs1 test2]# bash num.sh 
Input a number,Please:12ad
12ad is not a number.
[root@rs1 test2]# bash num.sh 
Input a number,Please:ad12
ad12 is not a number.

检查输入是否为email地址

[root@rs1 test2]# cat email.sh 
#!/bin/bash

#读取用户输入,将输入保存到变量email中
read -p "Please Input a email address:" email

#如果email符合if条件则是email地址,否则执行else语句
if [[ $email =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]]
then
    echo "$email is a email address."
else
    echo "$email is NOT a email address."
fi

^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}$是email格式。

执行脚本:


[root@rs1 test2]# bash email.sh 
Please Input a email address:[email protected]
[email protected] is a email address.
[root@rs1 test2]# bash email.sh 
Please Input a email address:[email protected]
[email protected] is a email address.
[root@rs1 test2]# bash email.sh
Please Input a email address:[email protected]
[email protected] is NOT a email address.

检查一个变量是否为IPV4地址


[root@rs1 test2]# cat ip_1.sh 
#!/bin/bash   

if [ $# != 1 ]
then
    echo "Usage : $0 address"
    exit 1
else
    IP=$1
fi

function check_ip() {   
    if [[ $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then   
        FIELD1=$(echo $IP|cut -d. -f1)   
        FIELD2=$(echo $IP|cut -d. -f2)   
        FIELD3=$(echo $IP|cut -d. -f3)   
        FIELD4=$(echo $IP|cut -d. -f4)   
        if [ $FIELD1 -le 255 -a $FIELD2 -le 255 -a $FIELD3 -le 255 -a $FIELD4 -le 255 ]
    then   
            echo "$IP is an ipv4 address."   
        else   
            echo "$IP looks like an ipv4 address BUT not!"   
        fi   
        else   
            echo "$IP is not an ipv4 address!"   
    fi
     } 

check_ip $1 

执行脚本:


[root@rs1 test2]# bash ip_1.sh 172.25.254.11
172.25.254.11 is an ipv4 address.
[root@rs1 test2]# bash ip_1.sh 172.25.254.1111
172.25.254.1111 is not an ipv4 address!
[root@rs1 test2]# bash ip_1.sh 172.25.254.256
172.25.254.256 looks like an ipv4 address BUT not!

这只是简单的测试是否为一个合法的IPV4地址,如果需要255.255.255.255应该为广播地址、应该对比本机IP地址获取单播地址并过滤出来,甚至子网掩码地址

你可能感兴趣的:(shell)