2011-05-20 41 views
3

如何在保留引用的同時將shell參數存儲在文件中供以後使用?在保存引用時將shell參數存儲在文件中

要說清楚:我不想傳遞這些論據,可以使用"[email protected]"輕鬆完成。但實際上需要來將它們存儲在後面的文件中使用。

#!/bin/sh 
storeargs() { 
    : #-) 
} 
if "$1" 
then 
    # useargs is actuall 'git filter-branch' 
    useargs "[email protected]" 
    storeargs "[email protected]" 
else 
    # without args use those from previous invocation 
    eval useargs $(cat store) 
fi 

$ foo 'a "b"' "c 'd'" '\'' 'd 
e' 
$ foo # behave as if called with same arguments again 

問題可能歸結爲如何使用報價一般共同工具串(AWK,Perl中,...)。我寧願一個解決方案,不會使引用的字符串不可讀。 store的內容應該看起來或多或少像我在命令行中指定的內容。

問題很複雜,因爲要引用的參數/字符串可能已經包含任何類型的有效(shell)引用和/或任何類型的(顯着的)空格,所以無條件地在每個引號周圍放置單引號或雙引號參數或每行存儲一個參數將不起作用。

回答

5

爲什麼要舉重?

storeargs() { 
    while [ $# -gt 0 ] 
    do 
     printf "%q " "$1" 
     shift 
    done 
} 

現在,您可以

storeargs "some" "weird $1 \`bunch\` of" params > myparams.txt 
storeargs "some" 'weird $1 \`bunch\` of' params >> myparams.txt 
cat myparams.txt 

輸出

some weird\ \ \`bunch\`\ of params 
some weird\ \$1\ \\\`bunch\\\`\ of params 
+0

嗯。 %q非常好,但只適用於bash內建的printf。 – 2011-05-20 14:17:16

+0

用於提示'%q',簡單而有效。 – anubhava 2011-05-20 14:19:33

+0

謝謝,這對我很有用。不過,一個不需要bash的解決方案會更好。此外,輸出看起來不錯,但沒關係。 $'...'這種引用對我來說是新的。 – tarsius 2011-05-20 14:48:09

1

該版本每行存儲一個參數,所以在存儲方面可能有點難看。我懷疑,這完全是強大的,但它滿足您的例子(用於useargs(){因爲我在 「$ @」;做$回聲我;做;}):

 
storeargs() { printf "%q\n" "[email protected]"; } > store 

if test -n "$1"; then 
    useargs "[email protected]" 
    storeargs "[email protected]" 
else 
    eval useargs $args 
fi 

- 編輯 - 在printf中使用%q引用字符串(無恥地從sehe的答案中複製)。請注意,%q在bash內置的printf中可用,但在標準的printf中不可用。

+0

如此接近......取決於如何使用它,你會得到意想不到的變數,支架擴張過程subsitution,重定向。如果它不是評估版,而是像你說的那樣簡單地在'while read'中讀取,我認爲最糟糕的情況是包含換行符的文件名不再處理 – sehe 2011-05-20 14:00:15

+1

換行符肯定是一個問題。你用%q的解決方案是好的...我會偷獵它。 – 2011-05-20 14:09:39

+0

+1爲了避免循環 - 我去了bash manpage瞭解爲什麼單個'%q'很好:* [printf']中的格式根據需要被重用以消耗所有的參數* – marcin 2014-05-01 15:21:42