From Cronjob to CLI: Create a Bash Tool That Sends Daily Weather SMS

From Cronjob to CLI: Create a Bash Tool That Sends Daily Weather SMS

From Cronjob to CLI: Create a Bash Tool That Sends Daily Weather SMS

 

Need a daily weather forecast texted straight to your phone? In this tutorial, we’ll show you how to write a Bash script that fetches weather data from an API and sends you a forecast every morning using Twilio. By integrating CLI tools, APIs, and automation with cron, you can eliminate the need to check your weather app every day.

1. Prerequisites: What You Need

Before writing any code, let’s make sure you have the following:

  • Bash – Any modern Unix-based system with shell scripting (Linux/macOS).
  • curl – To make HTTP requests.
  • jq – To parse JSON from the weather API.
  • A Weather API Key – We’ll use OpenWeatherMap (https://openweathermap.org/api).
  • A Twilio Account and API Credentials – To send SMS messages programmatically.

Once you have those, you’re ready to start scripting.

2. Fetching Weather Data from OpenWeatherMap

We’ll use the One Call API from OpenWeatherMap. First, sign up and get your API key. Here’s a minimal Bash function that fetches and parses the weather forecast:

#!/bin/bash

# Configuration
LAT="40.7128"  # New York City latitude
LON="-74.0060"  # New York City longitude
API_KEY="your_openweather_api_key"

# Function to fetch weather
get_weather_forecast() {
  response=$(curl -s "https://api.openweathermap.org/data/2.5/onecall?lat=$LAT&lon=$LON&exclude=hourly,minutely,alerts&units=metric&appid=$API_KEY")
  forecast=$(echo "$response" | jq -r '.daily[0] | "Weather: "+.weather[0].description+", Temp: "+(.temp.day|tostring)+"°C"')
  echo "$forecast"
}

This function makes a GET request and uses jq to extract a description and the daily temperature from the JSON response. You can modify LAT and LON for your own location.

3. Sending SMS via Twilio

Next, we’ll set up a function to send SMS using Twilio’s Messaging API. You’ll need your ACCOUNT_SID, AUTH_TOKEN, and Twilio phone number.

# Twilio credentials
ACCOUNT_SID="your_account_sid"
AUTH_TOKEN="your_auth_token"
FROM_PHONE="+1234567890"  # Your Twilio number
TO_PHONE="+1987654321"    # Your personal number

send_sms() {
  local message="$1"
  curl -s -X POST "https://api.twilio.com/2010-04-01/Accounts/$ACCOUNT_SID/Messages.json" \
    --data-urlencode "Body=$message" \
    --data-urlencode "From=$FROM_PHONE" \
    --data-urlencode "To=$TO_PHONE" \
    -u "$ACCOUNT_SID:$AUTH_TOKEN"
}

This function uses curl to post an SMS. It’s important to keep your credentials secure—consider using environment variables or a .env file.

4. Putting It All Together

Now let’s wire everything into one executable Bash script. Save this as daily_weather_sms.sh.

#!/bin/bash

# Configurations
LAT="40.7128"
LON="-74.0060"
API_KEY="your_openweather_api_key"
ACCOUNT_SID="your_account_sid"
AUTH_TOKEN="your_auth_token"
FROM_PHONE="+1234567890"
TO_PHONE="+1987654321"

get_weather_forecast() {
  forecast=$(curl -s "https://api.openweathermap.org/data/2.5/onecall?lat=$LAT&lon=$LON&exclude=hourly,minutely,alerts&units=metric&appid=$API_KEY" | \
    jq -r '.daily[0] | "Weather: "+.weather[0].description+", Temp: "+(.temp.day|tostring)+"°C"')
  echo "$forecast"
}

send_sms() {
  local message="$1"
  curl -s -X POST "https://api.twilio.com/2010-04-01/Accounts/$ACCOUNT_SID/Messages.json" \
    --data-urlencode "Body=$message" \
    --data-urlencode "From=$FROM_PHONE" \
    --data-urlencode "To=$TO_PHONE" \
    -u "$ACCOUNT_SID:$AUTH_TOKEN"
}

main() {
  forecast=$(get_weather_forecast)
  send_sms "$forecast"
  echo "SMS sent: $forecast"
}

main

Make it executable with:

chmod +x daily_weather_sms.sh

And run it with:

./daily_weather_sms.sh

You should receive a weather forecast on your phone!

5. Automating with Cron

We want this script to run automatically every morning. To do that, create a cronjob.

crontab -e

Add the following line to send an SMS every day at 7:00 AM:

0 7 * * * /path/to/daily_weather_sms.sh >> /tmp/weather_sms.log 2>&1

Make sure the file path is absolute. Redirecting output to a log file helps in debugging if something goes wrong.

6. Tips, Optimization, and Final Thoughts

  • Use environment variables or a .env file read with source .env to keep credentials secure and readable.
  • You can enhance the script to include multi-day forecasts or send alerts for rain/snow events.
  • Use crontab -l to list your current jobs, and crontab -r to remove all if needed (use cautiously).
  • Test your API limits. Free tiers often restrict request frequency.
  • Tweak message formatting for conciseness—SMS has a 160-character limit.

Congratulations! You’ve just turned the magical trio of Bash, APIs, and cron into a personal morning assist bot. This powerful pattern can be adapted for stock alerts, reminders, or custom cron-triggered reports.

 

Useful links: