代码之家  ›  专栏  ›  技术社区  ›  itsadok

如何通过命令传递here文档并将结果捕获到变量中?

  •  15
  • itsadok  · 技术社区  · 16 年前

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

    • 脚本需要全部放在一个文件中。

    .

    #!/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
    
    3 回复  |  直到 15 年前
        1
  •  13
  •   Ignacio Vazquez-Abrams    16 年前

    这个 cat ... | 没有必要。

    foo=$(sed 's/-/_/g' << EOF
    1-2
    3-4
    EOF
    )
    
        2
  •  13
  •   itsadok    16 年前

    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
    )
    
        3
  •  2
  •   Community Mohan Dere    9 年前

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

    摘录:

    在第二个例子中,你可能注意到了两个遗传基因之间的差异。埃雷多克 函数中的终止符不带引号,而要读取的终止符带单引号。通过这种方式,shell被指示使用一个不带引号的终止符在herdoc上执行扩展,但在其终止符带引号时不执行扩展。在函数中展开未加引号的herdeoc时,它不会中断,因为它展开的变量的值已设置为带引号的字符串,并且不会对其进行两次解析。

    可能您想要做的是将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),然后在$(…)内运行该命令,并将其包含在传递给另一个可以可靠地接受反斜杠作为输入的应用程序(如上面的read和sed)的未加引号的heredoc中,将完全绕过shell对反斜杠的解析。应用程序是否可以将反斜杠作为输入/输出来处理,这是您必须亲自了解的。

    -迈克

    推荐文章