MySelfBoy MySelfBoy - 25 days ago 7
Bash Question

How to get IP of a domain requested with wget?

I'm searching for a way to fetch IP address of the domain requested with

wget
command, when the command fails.

I can't use
ping
command for fetching the IP, because the address may change after the
wget
command is terminated.

I would like to perform this in a shell script.

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