MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell Bash Scripting: Assignment & Excercise – 15

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 blockPurpose
#!/usr/bin/env bashFinds bash on the user's PATH, so the script also works where Bash is not installed at /bin/bash.
command -v jqPrints 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 -sSends a GET request to http://ip-api.com/json/<ip>. -s hides the progress meter.
jq '.status' -rReads 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, .countryPull 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)
  1. Save the gist as WhereIP.sh.
  2. Make it executable: chmod +x WhereIP.sh.
  3. Run it with one IP address: ./WhereIP.sh 8.8.8.8.
  4. 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's message field, which explains the failure, is never shown.
  • Unquoted variables. echo $data and curl $link are 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 -s alone hides network errors and still returns success on HTTP errors such as 429 Too Many Requests. Use -sS --fail together with a timeout.
  • curl is not checked. Only jq is 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. jq runs three times on the same data. One jq call with string interpolation is enough.
  • Typo. The comment slient should read silent.

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 pipefail stops 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 fields query parameter asks the API for only the fields you need, which keeps the response small.
  • --fail makes curl exit non-zero on HTTP 4xx/5xx responses, and --max-time 10 stops the script from hanging on a slow network.
  • <<<"$data" (a here-string) passes the JSON to jq without an extra echo and keeps it quoted.
  • jq string interpolation (\(.field)) formats the whole output line in a single call.
  • .message // "unknown error" uses jq's alternative operator in case message is missing.

Testing success and failure cases

Test more than the happy path. These are the results to expect from the improved script:

CommandExpected resultExit code
./whereip.sh 8.8.8.88.8.8.8: <city>, <region> in <country> (ISP: ...)0
./whereip.sh 192.168.1.10Error: lookup failed for 192.168.1.10: private range1
./whereip.sh 127.0.0.1Error: lookup failed ...: reserved range1
./whereip.sh not-a-hostError: lookup failed ...: invalid query1
./whereip.sh 'a b'Error: invalid input: a b1
./whereip.shUsage message on stderr2

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-Rl response header shows how many requests remain, and X-Ttl shows 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 -j flag 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 -u and 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals

Related Posts

Shell Scripting Tutorials: Conditional statatement using if

Bash makes decisions with if, if-else, if-elif-else, nested if and case. Each one runs a command or test and branches on its exit status. Below the original…

Read More

How to set Static IP Address in Ubuntu?

On current Ubuntu Server releases, you set a static IP address in a Netplan YAML file under /etc/netplan/, then apply it with sudo netplan apply. The example…

Read More

Shell Bash Scripting: Assignment & Excercise – 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution…

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x