這不夠嗎?
#!/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
。相反,您可能希望將變量ipaddresscurrent
的輸出分配給命令dig +short sub.domain.com
。
ipaddresscurrent=`dig +short sub.domain.com`
(!但請千萬不要使用反引號)或更現代,更穩健和嵌套$(...)
爲:
ipaddresscurrent=$(dig +short sub.domain.com)
grep -Pzo
沒有按這是使用舊的和過時反引號無論做真的不能做你期望的事情。相反,你要運行grep
quiently(因此-q
標誌),並檢查它的輸出,所以下面將是有效的:
echo "$ipaddresscurrent" | grep -q -P "$ipaddressused" && echo "found" && exit 0 || echo "not found" && exit 1
既然你不真正需要的變量ipaddresscurrent
,我優選使用bash的process substitution以供給grep
。
此外,不要使用&& || &&
的長鏈,它很難閱讀,並可能有一些微妙的副作用。
如果要堅持你的變量,你需要一個here-string像這樣:
#!/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
假設用這樣的方式將僅輸出每行一個IP地址。
謝謝!如果你不介意解釋爲什麼這個作品和前一個我不會感激它。 – Gaia
應該注意,如果提供的$ ipaddressused是111.222.333.4,111.222.333.456是dig中的有效結果,則也會發生匹配。這可能會導致問題。 – Gaia
@Gaia再次編輯! –