BASH Script – How to Test for IP Address

bashifconfigshell

Is there an elegant way to test an IP address in a BASH script? I could do ifconfig and narrow down the IP using sed/awk, but I think there is a simpler solution.

My application is basically using SSH/SCP scripts when I'm in my intranet and while I'm not. So, I want this type of flow

if IP=192.168.1.1
      then do this
 else
      then do that

Best Answer

Something fairly simple that you can modify to suit your needs:

ip addr show dev eth0 | fgrep -q 'inet 192.168.1.1'
if [ $? -eq 0 ]; then
   echo 'IP found'
else
   echo 'IP not found'
fi

EDIT: forgot the fgrep :)