Helper Script: ip

Most of the time when we type ipconfig / ifconfig we are looking for a very simple information i.e. what’s the ip address and which interface is up and running.
So here is another simple script that i write in both shell script and batch file format to ensure that i can extract the basic information in quick turnaround.

Linux / Mac (Bash Version)

#!/bin/bash
if [ "$(uname)" == "Darwin" ]; then
    # Do something under Mac OS X platform
	for interface in `ifconfig | grep ": flags" | cut -f1 -d":"`; do
	        ip=$(ifconfig $interface | grep "inet " | cut -f2 -d" ")
	        if [ ! -z $ip ]; then
	            echo "$interface : $ip"
	        fi
	done
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
    # Do something under GNU/Linux platform
	for interface in `ifconfig | grep "Link " | cut -f1 -d" "`; do
	        ip=$(ifconfig $interface | tr -s " " | grep "inet" | cut -f2 -d":" | cut -f1 -d" ")
	        if [ ! -z $ip ]; then
	            echo "$interface : $ip"
	        fi
	done
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
    # Do something under Windows NT platform
    echo "Not implemented for Windows"
fi

Windows Batch Version

@echo off
if "%1"=="ip" GOTO Continue
ipconfig | find ":" | find /V "DNS" | find /v "Tunnel" | find /v "Media" | find /v "IPv6" | find /v "Subnet"
:Continue	
ipconfig | find "IPv4"

Both the version give you a concise view of what all interfaces are up and runing and which interface has an ip address attached to it.

And here is another script which uses a web service to get you public IP Address.

#!/bin/bash
curl https://api.ipify.org
echo ""

Do you like what you read, What to share it

Leave a Reply

Your email address will not be published. Required fields are marked *