0

I would like the simplest solution for my pretty basic bash script:

#!/bin/bash

    # Weather API url format: http://api.wunderground.com/api/{api_key}/conditions/q/CA/{location}.json
    # http://api.wunderground.com/api/5e8747237f05d669/conditions/q/CA/tbilisi.json

        api_key=5e8747237f05d669
        location=tbilisi
        temp=c

        api=$(wget -qO- http://api.wunderground.com/api/$api_key/conditions/q/CA/$location.json)
        temp_c=$api | grep temp_c
        temp_f=$api | grep temp_f

        if [ $temp = "f" ]; then
            echo $temp_f
        else
            echo $temp_c
        fi

grep returns empty. This is my first bash script, I'm getting hold of syntax, so please point out obvious errors.

I also don't understand why I have $() for wget.

4
  • In your code, if condition is always false because nothing modifies $temp. It is always c Commented Mar 26, 2014 at 20:25
  • Hope my edit of the title is appropriate. I'm not a real hacker, so a list of choppy terms, nouns in a row, sort of gives me a headache. Apology available on request. Commented Mar 26, 2014 at 20:26
  • bash is the wrong tool to do json parsing. Perhaps consider python's or ruby's libraries Commented Mar 26, 2014 at 20:26
  • or the xml api and xmlstarlet Commented Mar 26, 2014 at 20:34

2 Answers 2

1

You can use:

temp_c=$(echo $api|awk '{print $2}' FS='temp_c":'|awk '{print $1}' FS=',')
temp_f=$(echo $api|awk '{print $2}' FS='temp_f":'|awk '{print $1}' FS=',')

Instead of:

temp_c=$api | grep temp_c
temp_f=$api | grep temp_f
Sign up to request clarification or add additional context in comments.

Comments

0

I am getting following JSON response from curl and storing in variable :

CURL_OUTPUT='{ "url": "protocol://xyz.net/9999" , "other_key": "other_value" }'

Question :I want to read the url key value and extract the id from that url:

Answer : _ID=$(echo $CURL_OUTPUT |awk '{print $2}' FS='url":' |awk '{print $1}' FS=',' | awk '{print $2}' FS='"'|awk '{print $4}' FS='/')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.