John Connor John Connor - 2 months ago 12x
Bash Question

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:


wanip=$(dig +short;
echo "$wanip" > /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


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


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

wanip=$(dig +short;
echo "$wanip" | while read ip; do
    echo "$ip $(whois "$ip" | awk ' /[Cc]ountry/{print $2}')"

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:

ip=$(dig +short;
echo "$ip $(whois "$ip" | awk ' /[Cc]ountry/{print $2}')"


  • I converted IP to ip because it is best practices to use lower or mixed case names for your shell variables.

  • My whois returns a line with Country, not country. So, I made the search for country case insensitive.