Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
将子网掩码转换为前缀长度
#!/bin/bash
# date: 2018-03-03
# license: GPLv3 https://www.gnu.org/licenses/gpl-3.0.txt
# author: nanpuyue <nanpuyue@gmail.com> https://blog.nanpuyue.com
num=0
for n in ${1//./ };do
if (( $n < 128 )) && (( $n != 0 ));then
exit 1
elif [[ $(echo "obase=2;$n"|bc) =~ ^(1*)0*$ ]];then
if (( $(( $num % 8 )) == 0 ));then
num=$(( $num + ${#BASH_REMATCH[1]} ))
elif (( ${#BASH_REMATCH[1]} > 0 ));then
exit 1
fi
else
exit 1
fi
done
echo $num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment