Get my country by IP in bash

You can get somewhat close by querying the public whois database. It'll likely be somewhat difficult to "productify" to handle every possible case, but a reasonable approximation might be:

$ whois a.b.c.d | grep -iE ^country:

where a.b.c.d is the IP address in question.

whois is often installed by default, so this meets a reasonable interpretation of your "I prefer not to install any package for doing this" read as "I don't want to install additional software".

To print only the value of the country field and force it to upper case only (to make comparisons easier, for example), you can do something like:

$ whois a.b.c.d | awk -F':[ \t]+' 'tolower($1) ~ /^country$/ { print toupper($2) }'

Use another IP locator than ifconfig.me that provides with that information like:

Not available anymore as of 2015-03-09

curl -s 'http://geoiplookup.net/geoapi.php?output=countrycode'

or:

curl -s 'http://geoiplookup.net/geoapi.php?output=country'

(see the API for details)

or:

curl -s http://whatismycountry.com/ |
  sed -n 's|.*,\(.*\)</h3>|\1|p'

or:

curl -s http://whatismycountry.com/ |
  sed -n 's|.*> *\(.*\)</h3>|\1|p'

for more precision, or:

curl -s http://whatismycountry.com/ |
  sed -n 's/.*Coordinates \(.*\)<.*/\1/p'

for the coordinates.

That makes assumptions on the HTML formatting of the page. So it may stop working if they decide to change that format in the future.


ipinfo.io has nice JSON API for using from command line:

$ curl ipinfo.io
{
  "ip": "X.X.X.X",
  "hostname": "No Hostname",
  "city": "Hanoi",
  "region": "Ha Noi",
  "country": "VN",
  "loc": "21.0333,105.8500",
  "org": "AS18403 The Corporation for Financing & Promoting Technology"
}