如何使用printf";%q";在bash?
我想把函数的增广打印到文件中。 我被告知命令printf“%q”,其指令如下所示如何使用printf";%q";在bash?,bash,Bash,我想把函数的增广打印到文件中。 我被告知命令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. a b\ c 根据上面的说明,我尝试了以下代码 #!/bin/bash #
# 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.
a b\ c
根据上面的说明,我尝试了以下代码
#!/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}"
跑
bash print_out_function_augs.sh
结果如下:
# 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.
a b\ c
我期望结果是一样的
a 'b c'
这是原始的增强打印功能
为什么输出和原始增强不同?
或者我可以按原样打印出原始的增强内容吗
非常感谢。使用
%q
时请记住这一点:
参数的打印格式可以重用为shell输入,使用建议的POSIX$“”语法转义不可打印的字符
我的<只要输入可以在shell中重用,code>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
请注意,arg3
周围没有引号。Bash不会传递这些信息
当printf
打印参数时,它不知道在bc
周围有引号,所以它不会打印它们。但它确实知道“b”和“c”之间的空格是一个特殊的shell字符,并将\
放在前面以转义它
这适用于所有bash函数/命令,因此请记住,在调用print\u augs
时也会发生同样的情况
如果要在字符串周围保留引号,则需要对其进行双引号,以便Bash不会解析它们:
function print_augs2() {
echo "$@" >> "${output_file}"
}
print_augs2 a "'b c'"
# Output: a 'b c'
感谢您的详细解释和解决方案。我无法想象“b\c”中的“\”。是一个转义字符。