Daksh Kaushal
Daksh Kaushal

Reputation: 23

Get IP from hostname or FQDN using shell scripting

I want to extract IP from Hostname or FQDN using a shell script. If I Ping using the hostname it gives me the IP in the output but how do I extract that from the output to use in my shell script.

Upvotes: 0

Views: 7306

Answers (3)

Daksh Kaushal
Daksh Kaushal

Reputation: 23

This worked for me:

IP1=$(ping -c 1 "$IP" | grep PING | awk -F'(' '{print $2}'| awk -F')' '{print $1}') &> /dev/null

IP being the FQDN

Upvotes: 0

user666N
user666N

Reputation: 171

 ip=`nslookup <fqdn> | grep -m2 Address | tail -n1 | cut -d : -f 2`
  1. First performs a nslookup.
  2. Greps for the first 2 occurrences of the word "Address" - we need any Address after the first since the first one shows the DNS server address used for the lookup.
  3. Uses the last one from the grepped output.
  4. Splits the line by using the delimiter ":" and extracts the second value.

eg.

$ ip=`nslookup stackoverflow.com | grep -m2 Address | tail -n1 | cut -d : -f 2` && echo $ip
151.101.1.69 

Upvotes: 0

marekful
marekful

Reputation: 15351

Several ways to do that. Check here.

You may want to use the VARIABLE=$(command) bash syntax. E.g.

IP=$(dig +short index.hu)
echo $IP

Upvotes: 2

Related Questions