linuxbashshellipwan

Country and External IP Bash script


I created a script based on what I could find on the INTERNET and some bash tutorials, that will show me my external IP and the country it's located in.

#

Script looks like this:

#!/bin/bash

wanip=$(dig +short myip.opendns.com @resolver1.opendns.com);
echo "$wanip" > /root/Documents/filewanip;
iplist="/root/Documents/filewanip"

while read IP;do
whois "$IP"
done < "$iplist" | grep "country" >geoloc
cat geoloc filewanip
rm filewanip geoloc
#

Output looks like this: country: Holland 183.64.132.80

#

Problem is that I don't want to use files to do this as file structure obviously changes from system to system. How can I make it in an elegant way so the check is made and stored into a variable(s) and then displayed directly into the shell?

John Connor


Solution

  • As I understand it, your goal is to eliminate the use of temporary files. In that case:

    #!/bin/bash
    wanip=$(dig +short myip.opendns.com @resolver1.opendns.com);
    echo "$wanip" | while read ip; do
        echo "$ip $(whois "$ip" | awk ' /[Cc]ountry/{print $2}')"
    done
    

    The above was written as if dig returns more than one address for your IP. If that is not the case, then the while loop is superfluous.

    If you are only expecting one IP, then:

    #!/bin/bash
    ip=$(dig +short myip.opendns.com @resolver1.opendns.com);
    echo "$ip $(whois "$ip" | awk ' /[Cc]ountry/{print $2}')"
    

    Notes: