This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the city, region and country. Below the original script you'll find a line-by-line explanation, fixes for its weak spots, a hardened version that you can run, and ideas for extending the exercise.
Write a Shell Bash Script for Get location of an IP address.
How the script above works
The script is short, but it covers several core shell scripting patterns: checking dependencies, validating arguments, calling a REST API and parsing JSON. Here is what each part does.
| Line or block | Purpose |
|---|---|
#!/usr/bin/env bash | Finds bash on the user's PATH, so the script also works where Bash is not installed at /bin/bash. |
command -v jq | Prints the path of jq if it is installed. [ -x ... ] checks that the path is executable, and the script exits if it isn't. |
[[ $# -ne 1 ]] | $# is the number of arguments. The script needs exactly one: the IP address. |
curl $link -s | Sends a GET request to http://ip-api.com/json/<ip>. -s hides the progress meter. |
jq '.status' -r | Reads the status field. -r prints raw strings without the JSON quotes. |
if [[ $status == "success" ]] | ip-api.com returns "status":"success" or "status":"fail" in the response body. |
jq '.city', .regionName, .country | Pull out the three location fields and print them on one line. |
A successful response from ip-api.com is a flat JSON object. Besides the fields the script uses, it includes countryCode, region, zip, lat, lon, timezone, isp, org, as and query (the address that was looked up).
Prerequisites and running the script
You need Bash, curl, jq and outbound HTTP access to ip-api.com. Install the tools with your package manager:
# Debian / Ubuntu
sudo apt-get install -y curl jq
# RHEL / Rocky / Fedora
sudo dnf install -y curl jq
# macOS (Homebrew)
brew install jqCode language: PHP (php)
- Save the gist as
WhereIP.sh. - Make it executable:
chmod +x WhereIP.sh. - Run it with one IP address:
./WhereIP.sh 8.8.8.8. - Check the output. It should look similar to
Ashburn, Virginia in United States.The exact location depends on the provider's current data.
Note: The error message in the original points to the old jq website. The jq project has since moved to the jqlang organisation on GitHub. Installing jq from your OS package manager is the simplest option.
Problems in the original script
The script works for the happy path, but it has several issues that matter once you use it in real automation:
- Silent failure. If the lookup fails, for example for a private address like
192.168.1.10, the script prints nothing and exits with status 0. The API'smessagefield, which explains the failure, is never shown. - Unquoted variables.
echo $dataandcurl $linkare subject to word splitting and glob expansion. Always quote expansions:"$data". - No input validation. The argument goes straight into the URL, so input such as
1.1.1.1?fields=...changes the request. Allow only characters that are valid in IPs and hostnames. - HTTP errors are hidden.
curl -salone hides network errors and still returns success on HTTP errors such as429 Too Many Requests. Use-sS --failtogether with a timeout. curlis not checked. Onlyjqis tested, but the script needs both tools.- Errors go to stdout. Error and usage messages should go to stderr (
>&2), so they don't mix with real output in pipelines. - Inefficient parsing.
jqruns three times on the same data. Onejqcall with string interpolation is enough. - Typo. The comment
slientshould readsilent.
Improved version of the script
#!/usr/bin/env bash
# whereip.sh - print the approximate location of an IP address or hostname
# Usage: ./whereip.sh 8.8.8.8
set -euo pipefail
API="http://ip-api.com/json"
FIELDS="status,message,query,city,regionName,country,isp"
die() { echo "Error: $*" >&2; exit 1; }
for cmd in curl jq; do
command -v "$cmd" >/dev/null 2>&1 || die "$cmd is not installed."
done
if [[ $# -ne 1 ]]; then
echo "Usage: $(basename "$0") <ip-address|hostname>" >&2
exit 2
fi
target=$1
# Only allow characters valid in IPv4, IPv6 and hostnames
[[ $target =~ ^[A-Za-z0-9.:-]+$ ]] || die "invalid input: $target"
data=$(curl -sS --fail --max-time 10 "${API}/${target}?fields=${FIELDS}") \
|| die "request to ip-api.com failed (network error or rate limit)"
status=$(jq -r '.status' <<<"$data" 2>/dev/null) \
|| die "unexpected response: $data"
if [[ $status == "success" ]]; then
jq -r '"\(.query): \(.city), \(.regionName) in \(.country) (ISP: \(.isp))"' <<<"$data"
else
die "lookup failed for $target: $(jq -r '.message // "unknown error"' <<<"$data")"
fiCode language: PHP (php)
set -euo pipefailstops the script when a command fails, when it uses an undefined variable, or when any command in a pipeline fails.die()sends errors to stderr and exits with a non-zero code, so callers and CI jobs can detect a failure.- The
fieldsquery parameter asks the API for only the fields you need, which keeps the response small. --failmakescurlexit non-zero on HTTP 4xx/5xx responses, and--max-time 10stops the script from hanging on a slow network.<<<"$data"(a here-string) passes the JSON tojqwithout an extraechoand keeps it quoted.jqstring interpolation (\(.field)) formats the whole output line in a single call..message // "unknown error"uses jq's alternative operator in casemessageis missing.
Testing success and failure cases
Test more than the happy path. These are the results to expect from the improved script:
| Command | Expected result | Exit code |
|---|---|---|
./whereip.sh 8.8.8.8 | 8.8.8.8: <city>, <region> in <country> (ISP: ...) | 0 |
./whereip.sh 192.168.1.10 | Error: lookup failed for 192.168.1.10: private range | 1 |
./whereip.sh 127.0.0.1 | Error: lookup failed ...: reserved range | 1 |
./whereip.sh not-a-host | Error: lookup failed ...: invalid query | 1 |
./whereip.sh 'a b' | Error: invalid input: a b | 1 |
./whereip.sh | Usage message on stderr | 2 |
Use echo $? right after each run to check the exit code. Scripts that return correct exit codes can be chained safely with && and ||.
Rate limits, HTTPS and privacy
- The free ip-api.com endpoint is limited to about 45 requests per minute from each client IP. Above that limit it returns HTTP 429. The
X-Rlresponse header shows how many requests remain, andX-Ttlshows the seconds until the limit resets. - The free tier supports only plain HTTP and is meant for non-commercial use. HTTPS and commercial use require a paid key. Check the provider's current terms before you use it at work.
- Every address you look up is sent to a third party over an unencrypted connection. Don't send internal or customer IP data without approval.
- IP geolocation is approximate. VPNs, proxies, mobile carriers and cloud providers often resolve to a data centre or a regional hub, not to the user's real location.
Note: Run curl -sI http://ip-api.com/json/8.8.8.8 to see the rate-limit headers without the response body.
Extend the exercise
Once the basic script works, try these extensions. The first one looks up a list of IPs from a file and slows down to stay within the free rate limit:
#!/usr/bin/env bash
# bulk-whereip.sh - look up every IP listed in a file (one per line)
set -uo pipefail
file=${1:?Usage: $0 <file-with-ips>}
while IFS= read -r ip; do
[[ -z $ip || $ip == \#* ]] && continue # skip blank lines and comments
./whereip.sh "$ip" || true # keep going if one lookup fails
sleep 1.5 # ~40 requests/minute
done < "$file"Code language: PHP (php)
- If no argument is given, look up the caller's own public IP. Requesting
http://ip-api.com/json/with no address returns details for your own IP. - Add a
-jflag that prints the raw JSON for use in other tools. - Extract the source IPs from a web server access log with
awk '{print $1}' access.log | sort -uand pass them to the bulk script. - Cache results in a local file so the same IP is not looked up twice.
- Validate IPv4 addresses strictly, checking that each octet is between 0 and 255, before calling the API.
For more practice, try the other exercises in this series, such as Assignment & Exercise – 3 and Assignment & Exercise – 7.
Frequently asked questions
How do I find the location of an IP address from the Linux command line?
Query a geolocation API with curl and parse the result with jq, for example curl -s http://ip-api.com/json/8.8.8.8 | jq -r '.city, .country'. The script on this page wraps that command in validation and error handling.
Why does the script print nothing for 192.168.x.x addresses?
Private and reserved addresses have no public geolocation, so the API returns status: fail with a message such as private range. The original script ignores failures. The improved version prints the message and exits with code 1.
Is ip-api.com free to use in scripts?
Its free endpoint is meant for non-commercial use, is limited to roughly 45 requests per minute and works only over plain HTTP. HTTPS and commercial use require a paid plan, so check the provider's current terms.
Why should variables like $data be quoted in Bash?
Unquoted expansions are split on whitespace and expanded as glob patterns, which can corrupt data or change how arguments are passed. Quoting them ("$data") keeps the value exactly as it is.
How accurate is IP geolocation?
It is usually reliable at country level and only approximate at city level. VPNs, proxies, mobile networks and cloud hosting often show a provider's data-centre location instead of the user's real location.
Related tutorials
- More Shell Scripting tutorials
- What is Bash and use cases of Bash?
- Shell Bash Scripting Interview Questions and Answer – Part 4
- Shell Bash Scripting: Assignment & Excercise – 3
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals