Bash – Using grep in conditional statement in bash

bashshell-scriptUbuntu

I'm still very new to scripting in bash, and just trying a few what I thought would be basic things. I want to run DDNS that updates from the my server running Ubuntu 14.04.

Borrowing some code from dnsimple, this is what I have so far:

#!/bin/bash

LOGIN="email"
TOKEN="token"
DOMAIN_ID="domain"
RECORD_ID="record"
IP=`curl -s http://icanhazip.com/`

OUTPUT=`
curl -H "Accept: application/json" \
     -H "Content-Type: application/json" \
     -H "X-DNSimple-Domain-Token: $TOKEN" \
     -X "PUT" \
     -i "https://api.dnsimple.com/v1/domains/$DOMAIN_ID/records/$RECORD_ID" \
     -d "{\"record\":{\"content\":\"$IP\"}}"`

if ! echo "$OUTPUT" | grep -q "(Status:\s200)"; then

echo "match"

$(echo "$OUTPUT" | grep -oP '(?<="message":")(.[^"]*)' >> /home/ddns/ddns.log)
$(echo "$OUTPUT"| grep -P '(Status:\s[0-9]{3}\s)' >> /home/ddns/ddns.log)

fi

The idea is that it runs every 5 minutes, which I have working using a cronjob. I then want to check the output of the curl to see if the status is "200" or other. If it is something else, then I want to save the output to a file.

What I can't get working is the if statement. As I understand it, the -q on the grep command will provide an exit code for the if statement. However I can't seem to get it work. Where have I gone wrong?

Best Answer

You're almost there. Just omit the exclamation mark:

OUTPUT='blah blah (Status: 200)'
if echo "$OUTPUT" | grep -q "(Status:\s200)"; then
    echo "MATCH"
fi

Result:

MATCH

The if condition is fulfilled if grep returns with exit code 0 (which means a match). The ! exclamation mark will negate this.

Related Question