这是我的简单脚本,用于查找服务器的 IP 并检查它是否可以从服务器解析:
read domain_name
echo domain is: $domain_name
def_ip="ip route get 8.8.8.8 | head -1 | cut -d ' ' -f 7"
if ( dig +short @8.8.8.8 $domain_name == $def_ip )
then
echo $domain_name resolves from $def_ip
else
echo $domain_name does not resolve from $def_ip, please check
fi
这是运行之后的错误:
google.com
domain is: google.com
setup_libs()
setup_system()
create_search_list()
ndots is 1.
get_server_list()
make_server(8.8.8.8)
make_server(127.0.0.53)
dig_query_setup
parse_args()
making new lookup
make_empty_lookup()
digrc (open)
main parsing +short
main parsing @8.8.8.8
make_server(8.8.8.8)
main parsing google.com
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up google.com
main parsing ==
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up ==
main parsing ip
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up ip
main parsing route
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up route
main parsing get
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up get
main parsing 8.8.8.8
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up |
main parsing head
clone_lookup()
make_empty_lookup()
clone_server_list()
make_server(8.8.8.8)
looking up head
main parsing -1
Invalid option: -1
Usage: dig [@global-server] [domain] [q-type] [q-class] {q-opt}
{global-d-opt} host [@local-server] {local-d-opt}
[ host [@local-server] {local-d-opt} [...]]
Use "dig -h" (or "dig -h | more") for complete list of options
echo google.com does not resolve from ip route get 8.8.8.8 | head -1 | cut -d ' ' -f 7, please check
如果我改为echo $domain_name does not resolve from $def_ip
,eval $domain_name ...
则错误是google.com
未找到命令。
我进行了搜索,根据结果我认为我应该同时使用两者echo
,eval
但没有找到合适的方法来做到这一点。
是吗?如果不是,最佳做法是什么?
答案1
要捕获命令的输出,您需要命令替换$( ... )
。
def_ip=$(ip route get 8.8.8.8 | head -1 | cut -d ' ' -f 7)
要比较两个值,您不能使用( ... )
,它只会在后台运行命令。使用[ ... ]
或[[ ... ]]
:
if [ "$(dig +short @8.8.8.8 "$domain_name")" = "$def_ip" ] ; then
#or
if [[ $(dig +short @8.8.8.8 "$domain_name") = "$def_ip" ]] ; then
你注意到我们再次使用了命令替换吗?
使用 时[[ ... ]]
,比较的左侧不需要双引号。但右侧可能仍需要双引号,以防止将其解释为模式。
答案2
尝试类似
IPLOCAL=$(ip route get 8.8.8.8 | head -1 | cut -d ' ' -f 7)
IPDNS=$(dig +short @8.8.8.8 "$domain")
if [[ "$IPLOCAL" == "IPDNS" ]] ; then ...