Skip to content

Instantly share code, notes, and snippets.

@islander
Created December 24, 2019 02:33
Show Gist options
  • Save islander/14d0f0011fa9f815ca5b582b848f5ee9 to your computer and use it in GitHub Desktop.
Save islander/14d0f0011fa9f815ca5b582b848f5ee9 to your computer and use it in GitHub Desktop.
Bash function for validating IPv4 address
#!/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