2

This script should alert me in case of an error response.

Issue: Even when it executes successfully I am getting the email.

Bash script

#!/bin/bash

DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1\&par=2)
IFS=\" read __ KEY __ MESSAGE __ <<< "$DATA"
if [[ $KEY == Success ]]; then
    echo something
else
    send email on failure
fi

Response on

Failure:  {"ErrorCode":"11","ErrorMessage":"random message as per error code"}
Sucess:   {"ErrorCode":"000","ErrorMessage":"Success"}

This worked finally -

 #!/bin/bash
    DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1\&par=2)
    MESSAGE=$(jq '.ErrorMessage' <<< "$DATA")
if [[ "$MESSAGE" == '"Success"' ]] ;  then
echo something
else
send email
fi
Arsh Dhillon
  • 101
  • 1
  • 9
  • Are you sure the variable `$KEY` is equal to the string `Success` ? try putting `echo "$KEY"` right before your `if` test – Aserre Oct 24 '17 at 10:54
  • No, $KEY = ErrorCode. What variable will be for 11 and 000 ? – Arsh Dhillon Oct 24 '17 at 11:00
  • Then that's the cause of your error : you are not reading the good json field. On the other hand, to extract data from a properly fromated json message, `jq` would be the right tool – Aserre Oct 24 '17 at 11:01

2 Answers2

4

A proper tool to address your issue would be jq :

#!/bin/bash
DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1\&par=2)
KEY=$(jq -r '.ErrorCode' <<< "$DATA")
MESSAGE=$(jq -r '.ErrorMessage' <<< "$DATA")
if [[ "$KEY" = "000" ]]
then 
    echo success
else
    echo fail
fi

Note : the -r flag for jq removes the double quotes

Aserre
  • 4,916
  • 5
  • 33
  • 56
0
#!/bin/bash
DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1\&par=2)
KEY=$(echo "$DATA" | grep -oP '"ErrorCode":"\K(\d+)"')
MESSAGE=$(echo "$DATA" | grep -oP '"ErrorMessage":"\K(.+?)(?=")')
((KEY == 0)) && echo success || echo "$MESSAGE"
Darby_Crash
  • 446
  • 3
  • 6
  • 1
    Analyzing data with tools that are not context aware for structured languages (xml, html, json, yaml, ...) is usually considered [a bad practice](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) and can lead to security flaws when ecountering non specific input – Aserre Oct 24 '17 at 12:13
  • 1
    This is just a code sample. The actual api may be more complex. What if there are several, nested error codes ? – Aserre Oct 24 '17 at 12:18
  • 1
    This is the output of the api posted by OP: {"ErrorCode":"7","ErrorMessage":"Invalid username / password or Api Key","JobId":null,"MessageData":null} and my code can't fail on it. – Darby_Crash Oct 24 '17 at 12:26