I have a shell function for validating IPv4 address strings:
is_ipv4_addr() {
IFS='.'
declare -a octets=( ${1:-} )
if [ "${#octets[*]}" -eq 4 ]; then
for octet in "${octets[@]}"; do
if [[ ! "$octet" =~ ^[0-9]+$ ]] || [ "$octet" -lt 0 ] || [ "$octet" -gt 255 ]; then
return 2
fi
done
return 0
fi
return 1
}
However, shellcheck
complains about the unquoted ${1:-}
and adding quotes around it would break splitting the string at dots. I know I could just disable this particular check with a comment, but that always seems like an ugly workaround to me, so I decided to use mapfile
instead:
is_ipv4_addr() {
mapfile -d. -t octets <<<"${1:-}"
if [ "${#octets[*]}" -eq 4 ]; then
for octet in "${octets[@]}"; do
if [[ ! "$octet" =~ ^[0-9]+$ ]] || [ "$octet" -lt 0 ] || [ "$octet" -gt 255 ]; then
return 2
fi
done
return 0
fi
return 1
}
But now validation always fails, even for valid IPv4 addresses like 8.8.8.8
. The returned status code is 2, so the function thinks that one of the octets is incorrect. Why?