Created
December 24, 2019 02:33
-
-
Save islander/14d0f0011fa9f815ca5b582b848f5ee9 to your computer and use it in GitHub Desktop.
Bash function for validating IPv4 address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
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 | |
IFS='.' read -ra ip <<< "$ip" | |
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ | |
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] | |
stat=$? | |
fi | |
return $stat | |
} | |
# testing | |
valid_ip 127.0.0.1 && echo valid | |
valid_ip 327.0.0.1 || echo invalid | |
valid_ip 1270.0.1 || echo invalid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment