Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check content of XML in bash

I am unable to wrap my head around this issue and hope for your help.

In a bash script I use a curl command which should get data from a server. The curl response is being put into a bash variable, because I want to check the response.

The response looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body><dp:response xmlns:dp="http://www.datapower.com/schemas/management">
    <dp:timestamp>2018-02-28T13:31:36+01:00</dp:timestamp>
    <dp:result> OK </dp:result>
    </dp:response>
  </env:Body>
</env:Envelope>

The important part is:

<dp:result> OK </dp:result>

How can I check within my bash script whether this exact string is in the variable (or not)? I tried several approaches with different kind of escapes, however, failed miserably so far (always ending up with an issue with one of the special characters).

Thank you for your help!

like image 579
scheuri Avatar asked Feb 28 '18 12:02

scheuri


1 Answers

Try this, using the proper tool for the right job :

Command :

curl ..... | xmllint --xpath '//*[local-name()="result"]/text()' 

or

xmllint --xpath '//*[local-name()="result"]/text()' http://domain.tld/path

or

curl ..... | xmlstarlet sel -t -v '//*[local-name()="result"]/text()'

Output:

OK

Finally :

#!/bin/bash

result="$(chosen_command)"

if [[ $result == *OK* ]]; then
    echo "OK"
else
    echo >&2 "ERROR"
    exit 1
fi

(replace chosen_command by... your chosen command)

like image 77
Gilles Quenot Avatar answered Sep 24 '22 03:09

Gilles Quenot