如果$IP
输出等于任何 IP 地址则必须打印 1,否则必须打印 0。
#!/bin/sh
IP=$(/usr/local/bin/dig ns.ripe.net. a +short)
if [ $IP = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" ]; then
echo 1
elif [ $IP != $ANY_IP ]; then
echo 0
fi
我需要编写脚本,必须检查“/usr/local/bin/dig ns.ripe.net.a +short”输出是否返回任何IP地址,应该返回1,否则返回0。这个脚本的目的是检查dnssec。如何表示任意 IP 地址以进行比较?
答案1
按照准确度递增的顺序:
POSIX外壳
case $IP in *.*.*.*) echo "$IP contains at least 3 dots" ;; *) echo "$IP does not contain 3 dots" ;; esac
巴什
shopt -s extglob if [[ $IP == +([0-9]).+([0-9]).+([0-9]).+([0-9]) ]]; then echo "$IP contains digits separated by dots fi
巴什
looks_like_IP_address() { [[ $1 =~ ^([0-9]+)"."([0-9]+)"."([0-9]+)"."([0-9]+)$ ]] && (( 0 <= ${BASH_REMATCH[1]} && ${BASH_REMATCH[1]} <= 255 )) && (( 0 <= ${BASH_REMATCH[2]} && ${BASH_REMATCH[2]} <= 255 )) && (( 0 <= ${BASH_REMATCH[3]} && ${BASH_REMATCH[3]} <= 255 )) && (( 0 <= ${BASH_REMATCH[4]} && ${BASH_REMATCH[4]} <= 255 )) } if looks_like_IP_address "$IP"; then echo "$IP looks like an IP address" fi