bashshellheredoc

How to pipe a here-document through a command and capture the result into a variable?


Right now this outputs the value I need on stdout. How can I capture it into a variable so I can use it in the rest of the script?

Requirements:

  • The script needs to be all in one file.
  • I'd prefer not to write any temp files, if possible.

.

#!/bin/bash

cat << EOF | xsltproc - ../pom.xml | tail -1
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/"><xsl:value-of select="/project/version"/></xsl:template>
</xsl:stylesheet>
EOF

Solution

  • This seems to work (based on Ignacio's answer). By using a subshell the here-document is correctly piped into xsltproc while still being passed through tail after.

    VERSION=$((xsltproc - ../pom.xml | tail -1) << EOF
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/"><xsl:value-of select="/project/version"/></xsl:template>
    </xsl:stylesheet>
    EOF
    )