2016-11-07 28 views
-1

我正在使用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

回答

0

每個評論下我的問題,bash的case不支持正則表達式;只有通配符。