[英]Using printf %q to pass arguments with spaces
Suppose I have a script that prints out the number of arguments passed to it: 假设我有一个脚本,可以打印出传递给它的参数数量:
# file: num_args
echo "Number of arguments: $#"
Now my question pertains to the following invocations: 现在,我的问题与以下调用有关:
> ./num_args a b c
> Number of arguments: 3 # As I would expect.
> ./num_args "a b c"
> Number of arguments: 1 # As I would expect.
> ./num_args a\ b\ c
> Number of arguments: 1 # As I would expect.
> printf "%q\n" "a b c"
> a\ b\ c # As I would expect.
> ./num_args $(printf "%q" "a b c")
> Number of arguments: 3 # NOT as I would expect.
Given that the printf
man page states that 鉴于
printf
手册页指出
%q ARGUMENT is printed in a format that can be reused as shell input, escaping non-printable characters with the proposed POSIX $'' syntax.
I am not sure what happens in the last case above. 我不确定在上述最后一种情况下会发生什么。
printf %q
output is escaped correctly to be parsed as source code by a shell interpreter . printf %q
输出已正确转义以由Shell解释器解析为源代码 。
However, unquoted expansions aren't parsed as source code; 但是,未引用的扩展名不会被解析为源代码。 they go only through string-splitting and glob-expansion phases.
它们仅经历字符串拆分和glob扩展阶段。 (This is a Good Thing: Otherwise handling untrusted filenames or other potentially-dangerous content in shell scripts would be nearly impossible).
(这是一件好事:否则,几乎不可能在shell脚本中处理不可信的文件名或其他潜在危险的内容)。
You can substitute this output into a shell command, as in sh -c "...$foo..."
or eval "...$foo..."
or ssh somehost "...$foo..."
; 您可以将此输出替换为shell命令,如
sh -c "...$foo..."
或eval "...$foo..."
或ssh somehost "...$foo..."
; it can't (shouldn't) just be used unquoted. 它不能(不应该)不加引号使用。
Some important references: 一些重要的参考资料:
eval
(one of the families of workarounds discussed above). eval
(上面讨论的解决方法系列之一)所涉及的风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.