这还不够吗?
#!/bin/bash
ipaddressused=$1
if grep -q -P "$ipaddressused" < <(dig +short sub.domain.com); then
echo "found"
exit 0
else
echo "not found"
exit 1
fi
你的脚本有什么问题?
线
ipaddresscurrent='dig +short sub.domain.com'
将字符串分配给dig +short sub.domain.com
变量ipaddresscurrent
。相反,您可能想将command的ipaddresscurrent
输出分配给变量。这可以使用旧的和已弃用的反引号来完成: dig +short sub.domain.com
ipaddresscurrent=`dig +short sub.domain.com`
(但请永远不要使用反引号!)或更现代、强大和可嵌套$(...)
的:
ipaddresscurrent=$(dig +short sub.domain.com)
grep -Pzo
并没有真正做到你所期望的。相反,您想安静地运行grep
(因此-q
标志)并检查其输出,因此以下内容将是有效的:
echo "$ipaddresscurrent" | grep -q -P "$ipaddressused" && echo "found" && exit 0 || echo "not found" && exit 1
由于您并不真正需要该变量ipaddresscurrent
,因此我更喜欢使用bash的进程替换来提供grep
。
此外,不要使用长链&& || &&
's,它很难阅读,并且可能会产生一些微妙的副作用。
如果你想坚持你的变量,你需要一个这里的字符串:
#!/bin/bash
ipaddressused=$1
ipaddresscurrent=$(dig +short sub.domain.com)
if grep -q -P "$ipaddressused" <<< "$ipaddresscurrent"; then
echo "found"
exit 0
else
echo "not found"
exit 1
fi
正如您在评论中指出的那样:
应该注意的是,如果提供的 $ipaddressused 是 111.222.333.4 并且 111.222.333.456 出现在列表中,那么也会发生匹配。这可能会导致问题。
我实际上并不知道这是否是一个请求的功能(因为脚本的参数是一个正则表达式,这实际上就是我留下-P
标志的原因)。如果你真的想完全匹配一个 IP,你可以这样做:
#!/bin/bash
if grep -q "^${1//./\.}$" < <(dig +short sub.domain.com); then
echo "found"
exit 0
else
echo "not found"
exit 1
fi
假设dig
使用这种方式将每行只输出一个 ip。