amanada.williams amanada.williams - 2 months ago 23
Linux Question

How to get the IP address of a server using bash

GOAL:
Pull the IP address from the server. However, the issue comes into play that dedicated and VPS are very different. What is the best or most ideal way to pull and do a check and print the IP Address?

I guess I could do a check with the following?

root@host]# /sbin/ifconfig venet0:0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
IP IS HERE
root@host]# /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
eth0: error fetching interface information: Device not found

Answer Source

To get the IP address of your server whether it be a VPS or not you can do the following:

#!/bin/bash

a="`netstat -i | cut -d' ' -f1 | grep eth0`";
b="`netstat -i | cut -d' ' -f1 | grep venet0:0`";

if [ "$a" == "eth0" ]; then
  echo "eth0 found"
  ip="`/sbin/ifconfig eth0 | awk -F':| +' '/inet addr/{print $4}'`";
elif [ "$b" == "venet0:0" ]; then
  echo "venet found"
  ip="`/sbin/ifconfig venet0:0 | awk -F':| +' '/inet addr/{print $4}'`"; 
fi

echo $ip;

Hope this helps.

Hat tip to jwpat7 for providing the awk command that is more succinct than the grep, cut, awk.