问题原文
原帖链接 · Amandasaurus · CC BY-SA 4.0
I have a domain name in a bash variable ($TARGET), and I want to get the IPv4 (A record) address of it in my bash script (I also want to get the IPv6 AAAA record (if exists)), in a robust manner.
i.e. What bash/unix command will: (i) print the IP address (and only the IP address) of the DNS resolution (ii) print nothing to stdout (or non-zero exit) if there is no DNS record for that domain found (iii) allow me to choose to ask for A or AAAA record.
host "$TARGET" prints lots of human readable stuff, and I'm reluctant to parse that.
dig +short looked promising, but in some scenarios, it also prints other warning messages which I do not understand, or care about.
$ dig +short -t A "$TARGET"
;; Warning: Client COOKIE mismatch
1.2.3.4
Debian test/bookworm. Bash v5.2 (installed via apt)
社区高分解答
原帖链接 · JG7 · CC BY-SA 4.0
You are on the right track with dig. You can suppress that particular cookie related error (per the man page). Below, I am also choosing to redirect all errors to /dev/null just in case, as you wanted failures to be silent.
[jg7@comp1 ~]$ TARGET="google.com"
[jg7@comp1 ~]$ dig +short +nobadcookie -t A "$TARGET" @8.8.8.8 2>/dev/null
64.233.177.139
64.233.177.138
64.233.177.101
64.233.177.113
64.233.177.100
64.233.177.102
[jg7@comp1 ~]$ dig +short +nobadcookie -t AAAA "$TARGET" @8.8.8.8 2>/dev/null
2607:f8b0:4002:c08::65
2607:f8b0:4002:c08::8a
2607:f8b0:4002:c08::64
2607:f8b0:4002:c08::71
If this isn't what you are looking for, then let me know.
[EDIT] Used a bash variable so as to be closer to the original question.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
