Skip to content

Instantly share code, notes, and snippets.

@itxx00
Last active April 27, 2017 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itxx00/f6cea321448794e1715643344222f726 to your computer and use it in GitHub Desktop.
Save itxx00/f6cea321448794e1715643344222f726 to your computer and use it in GitHub Desktop.
common.sh
function is_ip() {
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# usage: is_ipv4_ip <ip>
is_ipv4_ip() {
# test variable is an ip address or not
# true: return 0
# false: return 2
[ "$1" = "" ] && return 2
if ! echo "$1" | grep -q "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$"; then
return 2
fi
part1=$(echo $1|cut -d"." -f1)
part2=$(echo $1|cut -d"." -f2)
part3=$(echo $1|cut -d"." -f3)
part4=$(echo $1|cut -d"." -f4)
if [ $part1 -ge 0 -a $part1 -le 255 ] && \
[ $part2 -ge 0 -a $part2 -le 255 ] && \
[ $part3 -ge 0 -a $part3 -le 255 ] && \
[ $part4 -ge 0 -a $part4 -le 255 ]; then
return 0
else
return 2
fi
}
# usage: is_priv_ipv4_ip <ip>
is_priv_ipv4_ip() {
# test variable is an private ip address or not
# true: return 0
# false: return 1
# bad ip: retrun 2
is_ipv4_ip $1 || return $?
convip() {
re=$(echo $1 | awk -F. '{printf "%d",$1*256^3+$2*256^2+$3*256+$4}')
echo "$re"
}
ip=$(convip $1)
# 10.0.0.0 -- 10.255.255.255 (167772160 -- 184549375)
# 127.0.0.0 -- 127.255.255.255 (2130706432 -- 2147483647)
# 172.16.0.0 -- 172.31.255.255 (2886729728 -- 2887778303)
# 192.168.0.0 -- 192.168.255.255 (3232235520 -- 3232301055)
if [ $ip -ge 167772160 -a $ip -le 184549375 -o \
$ip -ge 2130706432 -a $ip -le 2147483647 -o \
$ip -ge 2886729728 -a $ip -le 2887778303 -o \
$ip -ge 3232235520 -a $ip -le 3232301055 ]; then
return 0
else
return 1
fi
}
# escape spical chars
# usage: ere_quote string
ere_quote() {
echo "$*" | sed 's/[]\.|$(){}?+*^]/\\&/g'
}
is_abs_path() {
local path="$1"
if [[ "$path" =~ ^/[-_./a-zA-Z0-9]+$ ]]; then
if echo "$path" |grep -q -e "/\.\{1,\}/\{1\}" -e "/\{2,\}"; then
return 1
fi
return 0
fi
return 1
}
is_url() {
local url="$1"
if [ "${#url}" -gt 100 ]; then
return 1
fi
echo "$url" |grep -qi "^https\{0,1\}://\([0-9a-zA-Z-]\{1,\}\.\)\{1,\}[a-zA-Z]\{1,\}\(/.*\)\{0,\}$"
if [ "$?" -eq 0 ]; then
return 0
else
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment