zsh:命令替换和正确引用 [英] zsh: Command substitution and proper quoting
问题描述
我有一个脚本 P
接受文件名作为参数:
I have a script P
which accepts file names as parameters:
P file1 file2 file3 ....
我还有一个脚本 G
,它生成一个文件名(通常是短列表),每行一个文件名.在我想用 zsh 编写的主脚本中,我想使用 G
生成要由 P
处理的文件名.天真的尝试是这样的:
I also have a script G
which generates a (typically short list) of file names, one file name per line. In a master script which I would like to write in zsh, I want to use G
to generate the file names to be processed by P
. The naive attempt goes like this:
P $(G)
这几乎很好用,只是我生活在一个恶意的人喜欢创建带有嵌入空间的文件的世界.如果 G
会生成这样的文件列表:
This works nearly well, only that I'm living in a world where malicious people enjoy creating files with embedded spaces. If G
would generate the list of files like this:
one_file
a file with spaces
P
将被称为
P one_file a file with spaces
代替
P 'one_file' 'a file with spaces'
一个明显的解决方案是将 G
和 P
粘合在一起,而不是通过命令替换,而是通过某种语言(Ruby、Perl、Python、Algol68、....),它执行 P
的 exec 并将参数传递给从 stdin 读取.
One obvious solution would be to glue G
and P
together not by command substitution, but by a small program in some language (Ruby, Perl, Python, Algol68,....), which does an exec of P
and passes the parameters to a read from stdin.
编写起来很简单,甚至可以重复使用.但是,我想知道 zsh 是否没有内置的解决方案来解决这个问题?
This would be trivial to write and could even be made reusable. However, I wonder, whether zsh with its grabbag of goodies would not have a solution for this problem builtin?
推荐答案
这可以通过:
P ${(f)"$(G)"}
将调用 P
as
P 'one_file' 'a file with spaces'
如果G
的输出是
one_file
a file with spaces
说明:
$(G)
周围的双引号告诉 zsh 将 G
的输出作为一个词(在 shell 的意义上)字字).
The double quotes around $(G)
tell zsh to take the output of G
as one word (in the shell sense of the word word).
所以就打电话
P "$(G)"
相当于
P 'one_file
a file with spaces'
这是参数扩展标志 f
发挥作用的地方.${(f)SOMEVAR}
告诉 zsh 在换行符处将 $SOMEVAR
拆分成单词.除了参数(如 SOMEVAR
),还可以在 ${...}
中使用命令替换(此处为 $(G)
)键入参数表达式,这会导致命令 P ${(f)"$(G)"}
.
This is where the Parameter Expansion Flag f
comes into play. ${(f)SOMEVAR}
tells zsh to split $SOMEVAR
into words at newlines. Instead of a parameter (like SOMEVAR
) one can also use a command substitution (here $(G)
) inside ${...}
type parmeter expressions, which leads to the the command P ${(f)"$(G)"}
.
这篇关于zsh:命令替换和正确引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!