我想将函数的扩充打印到文件中.我被告知命令printf"%q",其指令如下,
# man printf
%q ARGUMENT is printed in a format that can be reused as shell input, escaping non-print?
able characters with the proposed POSIX $'' syntax.
Run Code Online (Sandbox Code Playgroud)
在上面的说明的基础上,我尝试了以下代码.
#!/bin/bash
# file name : print_out_function_augs.sh
output_file='output.txt'
function print_augs() {
printf "%q " "$@" >> "${output_file}"
echo >> "${output_file}"
}
print_augs a 'b c'
cat "${output_file}"
rm "${output_file}"
Run Code Online (Sandbox Code Playgroud)
并运行
bash print_out_function_augs.sh
Run Code Online (Sandbox Code Playgroud)
结果如下,
a b\ c
Run Code Online (Sandbox Code Playgroud)
我期待结果为
a 'b c'
Run Code Online (Sandbox Code Playgroud)
这是print_augs函数的原始扩充.
为什么输出和原始增量不同?或者我可以打印出原始增益吗?
非常感谢你.
Kar*_*oll 15
使用时请记住这一点%q:
ARGUMENT以可以作为shell输入重用的格式打印,使用建议的POSIX $''语法转义不可打印的字符.
强调我的.只要输入可以在shell中重用,就可以printf随意重新格式化参数.但是,这不是您的输入看起来像它的方式.
在Bash中,'字符是一个字符串分隔符,这就是你告诉bash"下面的字符串包含像空格这样的特殊字符,而这些特殊字符不应该被Bash解析"的方法.引号不会传递给被调用的命令.命令看到的是这样的:
Command:
printf "%q" a 'b c'
Received args:
printf::arg0: printf
printf::arg1: %q
printf::arg2: a
printf::arg3: b c
Run Code Online (Sandbox Code Playgroud)
请注意,arg3它没有引号.Bash没有传递它们.
当printf打出args时,它不知道周围有引号 b c,因此它不会打印它们.但它确实知道'b'和'c'之间的空间是一个特殊的shell字符,并将其\置于前面以逃避它.
对于所有bash函数/命令都是如此,因此请记住,当您调用时print_augs也会发生同样的情况.
如果你想在字符串周围保留引号,你需要对它们进行双引号,以便Bash不解析它们:
function print_augs2() {
echo "$@" >> "${output_file}"
}
print_augs2 a "'b c'"
# Output: a 'b c'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7107 次 |
| 最近记录: |