In the world of DevOps, we’re always looking for ways to automate and streamline our tasks. Even something as simple as checking the weather can be made more efficient with a bit of scripting magic. So, I recently decided to build a command-line interface (CLI) tool using Bash that fetches the current weather for my location.

Why a CLI?

You might be wondering, “Why bother with a CLI when there are countless weather apps and websites?” Well, here are a few reasons why I prefer a CLI approach:

The Journey Begins

My initial attempt relied on the Dark Sky API, which unfortunately was discontinued. This presented a great opportunity to explore other weather APIs and improve my script.

Choosing the Right Tools

After some research, I selected the following:

Here is the code:

#!/usr/bin/env bash

# Get the user's external IP address using ipecho.net
EXTIP="$(curl -s https://ipecho.net/plain)" 

# Get location information (latitude and longitude) based on the IP address
LOCATION="$(curl -s http://ip-api.com/json/)"
LAT=$(echo "$LOCATION" | jq -r '.lat')
LON=$(echo "$LOCATION" | jq -r '.lon')

# Fetch weather data from Open-Meteo API using the latitude and longitude
WEATHER=$(curl -s "https://api.open-meteo.com/v1/forecast?latitude=$LAT&longitude=$LON&current_weather=true&daily=temperature_2m_max,temperature_2m_min,weathercode")

# Extract the current temperature in Celsius from the API response
TEMP=$(echo "$WEATHER" | jq -r '.current_weather.temperature')

# Convert the temperature to Fahrenheit
fahrenheit=$(echo "scale=2; ($TEMP * 9 / 5) + 32" | bc)

# Extract the city and country from the location data
city=$(echo "$LOCATION" | jq -r '.city')
country=$(echo "$LOCATION" | jq -r '.country')

# Display the weather information to the user
echo "Current weather in $city, $country:"
echo "Temperature: $TEMP°C ($fahrenheit°F)"

This script does the following:

  1. Retrieves the user’s external IP address.
  2. Uses the IP address to get the location (latitude and longitude).
  3. Fetches the current weather data from Open-Meteo.
  4. Extracts the temperature in Celsius and converts it to Fahrenheit.
  5. Displays the weather information in a user-friendly format.

Lessons Learned

Building this CLI tool was a valuable learning experience. I gained a better understanding of:

Next Steps

This is just the beginning! I plan to further improve this script by:

Stay tuned for future updates and enhancements to this project. You can find the complete code on my GitHub repository: by clicking here, or by visiting the Projects page of this site.

I hope this inspires you to build your own CLI tools and automate your daily tasks. Happy Coding!!

Leave a Reply

Your email address will not be published. Required fields are marked *