====== BASH - Functions - IP Validity ====== #!/usr/bin/env bash ip=${1:-1.2.3.4} ip_valid() { # Set up local variables local ip=${1:-1.2.3.4} local IFS=.; local -a a=($ip) # Start with a regex format test [[ $ip =~ ^[0-9]+(\.[0-9]+){3}$ ]] || return 1 # Test values of quads local quad for quad in {0..3}; do [[ "${a[$quad]}" -gt 255 ]] && return 1 done return 0 } if ip_valid "$ip"; then echo "success ($ip)" exit 0 else echo "fail ($ip)" exit 1 fi **NOTE:** Alternative regex is to change: [[ $ip =~ ^[0-9]+(\.[0-9]+){3}$ ]] || return 1 to [[ $ip =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1 or ^[1-9][0-9]{,2}(\.[1-9][0-9]{,2}){3}$ to avoid leading zeroes in a quad.