user2488578 user2488578 - 4 months ago 17
Bash Question

Wildcard expression comparison not working

I need to compare if the 2nd line of the input file contains the string

premium-world-check.xsd
. If it is present, I need not do anything.
If it is not present, I need to prepend to another file.

I have below input file,

<?xml version="1.0" encoding="UTF-8"?>
<records xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="premium-world-check.xsd">
<record category="INDIVIDUAL">
<tag1>
<tag2>
....
</tag2>
</tag1>


Below is my code,

xsdFlag=`sed -n '2p' ${myInputFile}`
if [ $xsdFlag == *"premium-world-check.xsd"* ]
then
echo "Prepending not required"
else
echo "<records xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="premium-world-check.xsd">" | cat - ${myInputFile} > wcTemp.xml && mv wcTemp.xml ${myInputFile}
echo "<?xml version="1.0" encoding="UTF-8"?>" | cat - ${myInputFile} > wcTemp.xml && mv wcTemp.xml ${myInputFile}
echo "PREPENDING:"
fi


I am getting unknown operator in my
if
condition.

Answer

Try it like this; I've made a couple of fixes.

xsdFlag=`sed -n '2p' "$myInputFile"`

if [[ "$xsdFlag" == *"premium-world-check.xsd"* ]]; then
    echo "Prepending not required"
else
    echo '<records xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="premium-world-check.xsd">' | cat - "$myInputFile" > wcTemp.xml && mv wcTemp.xml "$myInputFile"
    echo '<?xml version="1.0" encoding="UTF-8"?>' | cat - "$myInputFile" > wcTemp.xml && mv wcTemp.xml "$myInputFile"
    echo "PREPENDING:"
fi

One problem was using standard POSIX [ ... ] instead of Bash [[ ... ]], which you need to use wildcards.

The other problem was that you weren't escaping your quotation marks in your XML string. I changed the outer quotes from double quotes to single quotes to fix this.

You also weren't quoting your filenames, which is needed to prevent errors when they contain spaces.