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

Mark Renouf picture Mark Renouf · Jan 24, 2010 · Viewed 16.6k times · Source

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

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Jan 24, 2010

The cat ... | isn't necessary.

foo=$(sed 's/-/_/g' << EOF
1-2
3-4
EOF
)