问题描述
如何检查Shell脚本中IP地址的有效性,该IP地址在0.0.0.0
到255.255.255.255
的范围内?
How do I check the validity of an IP address in a shell script, that is within the range 0.0.0.0
to 255.255.255.255
?
推荐答案
如果您使用的是bash,则可以对模式进行简单的正则表达式匹配,而无需验证四边形:
If you're using bash, you can do a simple regex match for the pattern, without validating the quads:
#!/usr/bin/env bash
ip=1.2.3.4
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "success"
else
echo "fail"
fi
如果您坚持使用POSIX shell,则可以使用expr
来做基本相同的事情,使用BRE而不是ERE:
If you're stuck with a POSIX shell, then you can use expr
to do basically the same thing, using BRE instead of ERE:
#!/bin/sh
ip=1.2.3.4
if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
echo "success"
else
echo "fail"
fi
请注意,expr
假定您的正则表达式已锚定在字符串的左侧,因此不需要开头的^
.
Note that expr
assumes that your regex is anchored to the left-hand-side of the string, so the initial ^
is unnecessary.
如果重要的是验证每个四边形是否小于256,显然您将需要更多代码:
If it's important to verify that each quad is less than 256, you'll obviously require more code:
#!/bin/sh
ip=${1:-1.2.3.4}
if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
for i in 1 2 3 4; do
if [ $(echo "$ip" | cut -d. -f$i) -gt 255 ]; then
echo "fail ($ip)"
exit 1
fi
done
echo "success ($ip)"
exit 0
else
echo "fail ($ip)"
exit 1
fi
或者甚至更少的管道:
#!/bin/sh
ip=${1:-1.2.3.4}
if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
IFS=.
set $ip
for quad in 1 2 3 4; do
if eval [ \$$quad -gt 255 ]; then
echo "fail ($ip)"
exit 1
fi
done
echo "success ($ip)"
exit 0
else
echo "fail ($ip)"
exit 1
fi
或者再次,如果您的shell是bash,那么您可以在不喜欢算术的情况下使用繁琐的正则表达式进行四边形验证:
Or again, if your shell is bash, you could use a cumbersome regular expression for quad validation if you're not fond of arithmetic:
#!/usr/bin/env bash
ip=${1:-1.2.3.4}
re='^(0*(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}'
re+='0*(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))$'
if [[ $ip =~ $re ]]; then
echo "success"
else
echo "fail"
fi
这也可以用BRE表示,但这比我的手指输入要多.
This could also be expressed in BRE, but that's more typing than I have in my fingers.
最后,如果您喜欢将此功能...放入功能中的想法:
And lastly, if you like the idea of putting this functionality ... in a function:
#!/usr/bin/env bash
ip=${1:-1.2.3.4}
ipvalid() {
# Set up local variables
local ip=${1:-1.2.3.4}
local IFS=.; local -a a=($ip)
# Start with a regex format test
[[ $ip =~ ^[0-9]+(\.[0-9]+){3}$ ]] || return 1
# Test values of quads
local quad
for quad in {0..3}; do
[[ "${a[$quad]}" -gt 255 ]] && return 1
done
return 0
}
if ipvalid "$ip"; then
echo "success ($ip)"
exit 0
else
echo "fail ($ip)"
exit 1
fi
您可以通过多种方式执行此操作.我只给你看了几个.
There are many ways you could do this. I've shown you just a few.
这篇关于检查IP有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!