17

现在这会在标准输出上输出我需要的值。如何将其捕获到变量中,以便在脚本的其余部分中使用它?

要求:

  • 脚本需要全部在一个文件中。
  • 如果可能的话,我不想写任何临时文件。

.

#!/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
4

4 回答 4

13

cat ... |没有必要。

foo=$(sed 's/-/_/g' << EOF
1-2
3-4
EOF
)
于 2010-01-24T21:39:10.423 回答
13

这似乎有效(基于伊格纳西奥的回答)。通过使用子shell,here-document 被正确地通过管道传输到 xsltproc 中,同时仍然通过 tail 传递。

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
)
于 2010-01-24T21:57:37.090 回答
2

我已经玩heredocs了一两个星期了。这是我对Is there a way to get actual (uninterpreted) shell arguments in a function or script?回答的摘录?在 Unix Stack Exchange 上,这可能有助于说明它们对您的情况的使用:

... 摘录: ...

可能您注意到第二个示例中两个 heredocs 之间的区别。函数中的heredoc EOF终止符是不加引号的,而要读取的则用单引号引起来。通过这种方式,shell 被指示使用未加引号的终止符对heredoc 执行扩展,但在其终止符被引用时不这样做。在函数中扩展未引用的 heredoc 时它不会中断,因为它扩展的变量的值已经设置为带引号的字符串并且它不会对其进行两次解析。

可能您想要做的是将您的 Windows 路径从一个命令的输出动态传递到另一个命令的输入。heredoc 中的命令替换使这成为可能:

% _stupid_mspath_fix() { 
> sed -e 's@\\@/@g' -e 's@\(.\):\(.*\)@/drive/\1\2@' <<_EOF_
>> ${1}
>> _EOF_
> }
% read -r _stupid_mspath_arg <<'_EOF_'                    
> c:\some\stupid\windows\place
> _EOF_
% _stupid_mspath_fix ${_stupid_mspath_arg}
/drive/c/some/stupid/windows/place    
% read -r _second_stupid_mspath_arg <<_EOF_                    
> $(printf ${_stupid_mspath_arg})
> _EOF_
% _stupid_mspath_fix ${_second_stupid_mspath_arg}
/drive/c/some/stupid/windows/place

因此,基本上,如果您可以可靠地从某个应用程序输出反斜杠(我在上面使用 printf),然后在 $(...) 中运行该命令并将其包含在传递给另一个可以可靠地接受反斜杠作为输入的另一个应用程序的未引用的 heredoc 中(例如上面的 read 和 sed )将完全绕过 shell 对反斜杠的解析。应用程序是否可以将反斜杠作为输入/输出处理是您必须自己找出的。

-麦克风

于 2013-11-26T19:10:57.877 回答
0

您不需要tail -1通过添加omit-xml-declaration="yes"

VERSION=$(xsltproc - pom.xml << EOF
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mvn="http://maven.apache.org/POM/4.0.0">
<xsl:output method="text" omit-xml-declaration="yes"/>
<xsl:template match="/"><xsl:value-of select="mvn:project/mvn:version"/></xsl:template>
</xsl:stylesheet>
EOF
)
于 2022-02-11T23:57:45.103 回答