Skip to content

Instantly share code, notes, and snippets.

@ceving
Created September 7, 2016 14:09
Show Gist options
  • Save ceving/71e27b301e520310d5ce2af7177c2ef8 to your computer and use it in GitHub Desktop.
Save ceving/71e27b301e520310d5ce2af7177c2ef8 to your computer and use it in GitHub Desktop.
Check if the arguments are IPv4 addresses.
#! /bin/bash
set -eu
#set -x
# Check if the arguments are IPv4 addresses.
is-ip ()
{
local -a ip # Array for IP address
local x # Octet input. No -i, because read converts non
# numeric input to 0!
local -i i # Octet index
local a # Function argument
for a; do
# Read an IP address, which consists of four octets, three of
# which are dot delimited.
ip=()
{ i=3
while ((--i >= 0)); do
read -d. x; ip+=($x)
done
read x; ip+=($x)
} <<<"$a"
# Check the range 0..255 for every octet.
i=4
while ((--i >= 0)); do
# The arithmetic expansion fails also for non numeric octets.
if ! ((ip[i] >= 0 && ip[i] <= 255)) 2>/dev/null; then
return 1
fi
done
done
}
is-ip "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment