Weather Shell Function

Posted on Sat 12 December 2015 in misc

Here's the weather function I use when I'm too lazy to look out the window. The only configuration is a free forecast.io API key. The main selling point is that it geolocates so you don't have to remember where you are. Though this has drawbacks if you're running it on remote servers far from your location. If that's a problem then go get one of those silly weather() functions that doesn't know where it is unless you tell it.

weather() {
    # Geolocates on public IP.
    source ~/.forecast.io # Provides API_KEY
    local coordinates=$(curl -s ip-api.com/csv | awk -F',' '{print $8","$9}')
    echo $(curl -s https://api.forecast.io/forecast/$API_KEY/$coordinates | \
        grep -Eo 'apparentTemperature":[0-9\.]+|summary":"[A-Za-z\ ]+' | \
        head -n2 | \
        sed 's/summary":"//g' | \
        sed 's/apparentTemperature\"://g' | \
        xargs)F
}

Breaking It Down

The Forecast API needs your latitude and longitude coordinates which we can get from ip-api.com.

$ curl -s ip-api.com/csv | awk -F',' '{print $8","$9}'
38.XXXX,-76.XXXX

Now we can use curl to get the latest weather data.

$ . ~/.forecast.io
$ coordinates=$(curl -s ip-api.com/csv | awk -F',' '{print $8","$9}';)
$ curl -s https://api.forecast.io/forecast/$API_KEY/$coordinates

Assuming you've got your API_KEY setup properly in ~/.forecast.io you should see a big block of JSON. Doing proper parsing in the shell is ill-advised most of the time, but we're just looking for a specific piece of information so the Linux gods will probably give us a pass this time.

All we're interested in is the first instance of apparentTemperature and the accompanying summary, which we get using head -n2. We're using our special knowledge that the first instance of those variables happens to be in the currently section. If they ever change that we'll have to get creative.

Next we just use sed to remove the names, pipe it through xargs to put everything on one line, then append "F" to the end because I'm a dirty American.

$ . ~/.bashrc
$ weather
Partly Cloudy 45F

Well, There It Is