Using grep in conditional statement in bash
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.
Since you're already using bash, you could keep it internal to bash:
if [[ $OUTPUT =~ (Status:[[:space:]]200) ]]; then
echo match
fi
Sample runs:
OUTPUT='something bogus'
[[ $OUTPUT =~ (Status:[[:space:]]200) ]] && echo match
OUTPUT='something good (Status: 200)'
[[ $OUTPUT =~ (Status:[[:space:]]200) ]] && echo match
match
This is not an answer to your question, but few suggestions from a fellow scripter:
- Use
$()
instead of backticks, don't use them both - Indent conditional
if
statements - Remove unnecessary usage of
$()
Consistentecy and simple rules will help you debug and maintain scripts in a long run ...
#!/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