使用 Bash 变量代替文件作为可执行文件的输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14840178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using a Bash variable in place of a file as input for an executable
提问by d3pd
I have an executable that is used in a way such as the following:
我有一个以如下方式使用的可执行文件:
executable -v -i inputFile.txt -o outputFile.eps
In order to be more efficient, I want to use a Bash variable in place of the input file. So, I want to do something like the following:
为了更高效,我想使用 Bash 变量代替输入文件。所以,我想做如下事情:
executable -v -i ["${inputData}"] -o outputFile.eps
Here, the square brackets represent some clever code.
这里,方括号代表一些巧妙的代码。
Do you know of some trick that would allow me to pipe information into the described executable in this way?
你知道有什么技巧可以让我以这种方式将信息传送到所描述的可执行文件中吗?
Many thanks for your assistance
非常感谢你的协助
回答by mikyra
You can use the construct
您可以使用构造
<(command)
to have bash create a fifo with commands output for you. So just try:
让bash为您创建一个带有命令输出的fifo。所以试试吧:
-i <(echo "$inputData")
回答by Eric
Echo is not safe to use for arbitrary input.
To correctly handle pathological cases like inputdata='\ntest'or inputdata='-e', you need
要正确处理像inputdata='\ntest'或这样的病理情况inputdata='-e',您需要
executable -v -i <(cat <<< "$inputData")
In zsh, the catis not necessary
在zsh,cat是没有必要的
Edit:even this adds a trailing newline. To output the exact variable contents byte-by-byte, you need
编辑:即使这会添加一个尾随换行符。要逐字节输出确切的变量内容,您需要
executable -v -i <(printf "%s" "$inputData")
回答by Tom Hale
Note: zsh only:
注意:仅 zsh:
To get a filename containing the contents of ${variable}, use:
要获取包含 内容的文件名${variable},请使用:
<(<<<${variable})
Note:
笔记:
<<<${variable}redirectsSTDINto come from${variable}<<<${variable}is equivalent to (but faster than)cat <<<${variable}
<<<${variable}重定向STDIN来自${variable}<<<${variable}相当于(但比)cat <<<${variable}
So for the OP's case:
所以对于 OP 的情况:
executable -v -i <(<<<${inputData}) -o outputFile.eps
回答by Andrey Gusakov
executable -v -i <<<"${inputData}" -o outputFile.eps
will do the trick in bash.
将在 bash 中做到这一点。

