MySelfBoy MySelfBoy - 24 days ago 5
Bash Question

How to get the IP when "wget" request through the domain name?

I want to get the IP when I use wget command to request a domain name.
If a request fails.I will record the IP of the request this time.
I can't use "ping" command get the IP,because the IP maybe different every time.

I want to use Shell Script to do this.

Answer

When wget fails, it terminates with non-zero exit status, and the errors are written to the standard error descriptor (2).

So you can check the exit code ($? variable), and parse the strings written to the standard error:

url='http://stackoverflow.com/users/edit/1646322'

output=$( wget "$url" 2>&1 )
if [[ $? -ne 0 ]]; then
  printf '%s' "$output" | \
    perl -ne '/^Connecting to .*\|([^\|]+)\|/ and print $1'
fi

Sample Output

151.101.129.69