Files
hpr_website/www/eps/hpr2679/hpr2679_bash13_ex2.sh

51 lines
1.1 KiB
Bash
Executable File

#!/bin/bash
# =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~
# IP Address parsing revisited
# =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~ =~
#
# An IP address looks like this:
# 192.168.0.5
# Four groups of 1-3 numbers in the range 0..255 separated by dots.
#
re='^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$'
#
# The address is expected as the only argument
#
if [[ $# -ne 1 ]]; then
echo "Usage: $0 IP_address"
exit 1
fi
#
# Validate against the regex
#
if [[ $1 =~ $re ]]; then
#
# Look at the components and check they are all in range
#
errs=0
problems=
for i in {1..4}; do
d="${BASH_REMATCH[$i]}"
if [[ $d -lt 0 || $d -gt 255 ]]; then
((errs++))
problems+="$d "
fi
done
#
# Report any problems found
#
if [[ $errs -gt 0 ]]; then
problems="${problems:0:-1}"
echo "$1 is not a valid IP address; contains ${problems// /, }"
exit 1
fi
echo "$1 is a valid IP address"
else
echo "$1 is not a valid IP address"
fi