How to check if a IP (ipv4) address is valid in pure Bash
Here is a small bash function to check if a IP is valid (4 octets, each octet < 256). I find it somewhat elegant since instead of using a lot of case/if/then constructs or a crazy long regex it splits the IP into each octet (and stores them in an array, and then uses a combination of regex and bit shifting to check each octet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | is_valid_ipv4() { local -a octets=( ${1//\./ } ) local RETURNVALUE=0 # return an error if the IP doesn't have exactly 4 octets [[ ${#octets[@]} -ne 4 ]] && return 1 for octet in ${octets[@]} do if [[ ${octet} =~ ^[0-9]{1,3}$ ]] then # shift number by 8 bits, anything larger than 255 will be > 0 ((RETURNVALUE += octet>>8 )) else # octet wasn't numeric, return error return 1 fi done return ${RETURNVALUE} } |
The function will return 0 if the IP is valid, and 1 or higher if it encountered an error (you can check with the $? variable directly after calling the function)
Example:
1 2 3 4 5 6 7 | is_valid_ipv4 ${ip} if [[ $? -gt 0 ]] then echo "invalid IP" else echo "valid IP" fi |