Bash正则表达式在case语句中失败

问题描述:

我正在使用CIDR(/##或只是##)或点分十进制(###.###.###.###)表示法接受网络掩码的一段脚本。两者最终都是转换后的点分十进制符号,但我想给出进入CIDR的灵活性。我的正则表达式似乎没有工作,虽然:Bash正则表达式在case语句中失败

我所有的测试代码:

function cidr2mask() 
{ 
    # Number of args to shift, 255..255, first non-255 byte, zeroes 
    set -- $((5 - ($1/8))) 255 255 255 255 $(((255 << (8 - ($1 % 8))) & 255)) 0 0 0 
    [ $1 -gt 1 ] && shift $1 || shift 
    echo ${1-0}.${2-0}.${3-0}.${4-0} 
} 

function validate_netmask() { 
    echo $1 |grep -E -q '^(254|252|248|240|224|192|128)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)' && echo "Valid netmask" || echo "Invalid netmask" 
} 

while [[ -z $mask ]] 
do 
    read -p "Enter the netmask in either CIDR or dotted notation: " mask 
    echo "Netmask: $mask" #debugging 
    case $mask in 
    ^\/?[0-9][0-9]$) 
     cidr=$(echo $mask |sed 's/^///') 
     netmask=$(cidr2mask $cidr) 
     validate_netmask $netmask 
     break 
     ;; 
    ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$) 
     validate_netmask $mask 
     break 
     ;; 
    *) echo "Invalid netmask" 
     continue 
     ;; 
    esac 
done 

正如我所说,正则表达式不会出现工作。一切都下降到默认的case语句:

[[email protected] bin]$ bash scratch.sh 
Enter the netmask in either CIDR or dotted notation: 24 
Invalid netmask 
[[email protected] bin]$ bash scratch.sh 
Enter the netmask in either CIDR or dotted notation: /24 
Invalid netmask 
[[email protected] bin]$ bash scratch.sh 
Enter the netmask in either CIDR or dotted notation: 255.255.255.0 
Invalid netmask 

我试图读取$面具可变进case包括$mask"$mask"${mask}不同的方法。我也试过不逃避 CIDR符号(^/[0-9][0-9])。

我在做什么错?

+1

据我所知bash不支持case语句中的正则表达式。 – Mat

+2

'case'语句只支持(globbing-style)_patterns_,not _regular expressions_。 – mklement0

+0

那就是便便。 – theillien

每个评论下我的问题,bash的case不支持正则表达式;只有通配符。