2010-01-24 14 views
14

現在這輸出我需要在標準輸出值。我如何將它捕獲到一個變量中,以便在腳本的其餘部分使用它?如何通過命令來管道這裏的文件並將結果捕獲到變量中?

要求:

  • 腳本必須在同一個文件中。
  • 如果可能,我不想寫任何臨時文件。

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

回答

12

這似乎工作(基於伊格納西奧的回答)。通過使用子shell,here-document被正確地傳送到xsltproc中,同時仍然通過尾部傳遞。

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 
) 
10

cat ... |是沒有必要的。

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

那麼我只需要輸出的最後一行。如何還包括一個「|尾-1」? – 2010-01-24 21:48:43

+4

'sed's/-/_/g'<< EOF |尾巴-1' – 2011-02-28 14:36:56

2

我一直玩heredocs一兩個星期。下面是我的回答Is there a way to get actual (uninterpreted) shell arguments in a function or script?在Unix的堆棧交易所的摘錄,這可能有助於闡明它們的使用有點爲你的情況:

... 摘錄: ...

也許你注意到的區別第二個例子中的兩個heredocs。該函數內的終止符是不加引號的,而用於讀取的一個引用單引號。通過這種方式,shell被指示在heredoc上用一個不帶引號的終止符執行擴展,但是當它的終止符被引用時不會這樣做。它在擴展函數中未加引號的heredoc時不會中斷,因爲它擴展的變量的值已經設置爲帶引號的字符串,並且不會解析兩次。

可能你想要做的事情包括從一個命令的輸出將你的Windows路徑管道輸入到另一個命令的輸入中。定界符文本中的命令替換使之成爲可能:

% _stupid_mspath_fix() { 
> sed -e '[email protected]\\@/@g' -e '[email protected]\(.\):\(.*\)@/drive/\1\[email protected]' <<_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的反斜槓解析。無論應用程序是否可以處理反斜槓作爲輸入/輸出,您都必須自己找出。

-Mike

相關問題