Skip to content

Instantly share code, notes, and snippets.

@a-nldisr
Created August 3, 2015 15:25
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 a-nldisr/28ef0f1a8a3af199fd2c to your computer and use it in GitHub Desktop.
Save a-nldisr/28ef0f1a8a3af199fd2c to your computer and use it in GitHub Desktop.
#!/bin/bash
# Test an IP address for validity:
# Usage:
# valid_ip IP_ADDRESS
# if [[ $? -eq 0 ]]; then echo good; else echo bad; fi
# OR
# if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
#
total=0
num=1
function valid_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
}
# If run directly, execute some tests.
if [[ "$(basename $0 .sh)" == 'valid_ip' ]]; then
ips='
8.8.8.8
INTERNAL IP 1
INTERNAL IP 2
'
for ip in $ips
do
if valid_ip $ip; then stat='good'; else stat='bad'; fi
if state='good'; then total=$(($total + $num)) ; fi
done
fi
if [[ $total == 3 ]]; then
echo "All is ok";
exit 0; else
echo "OOPS issues ongoing";
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment