繁体   English   中英

使用printf%q传递带空格的参数

[英]Using printf %q to pass arguments with spaces

假设我有一个脚本,可以打印出传递给它的参数数量:

# file: num_args

echo "Number of arguments: $#"

现在,我的问题与以下调用有关:


> ./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.

鉴于printf手册页指出

 %q     ARGUMENT is printed in a format that can be reused as shell input, escaping non-printable characters with the proposed POSIX $'' syntax.

我不确定在上述最后一种情况下会发生什么。

printf %q输出已正确转义以由Shell解释器解析为源代码

但是,未引用的扩展名不会被解析为源代码。 它们仅经历字符串拆分和glob扩展阶段。 (这是一件好事:否则,几乎不可能在shell脚本中处理不可信的文件名或其他潜在危险的内容)。

您可以将此输出替换为shell命令,如sh -c "...$foo..."eval "...$foo..."ssh somehost "...$foo..." ; 它不能(不应该)不加引号使用。


一些重要的参考资料:

  • BashFAQ#50解释了为什么不能通过扩展包含引号的字符串来使用包含源代码的字符串。
  • BashFAQ#48解释了使用eval (上面讨论的解决方法系列之一)所涉及的风险。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM