[英]How to use printf “%q ” in 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.
在上述說明的基礎上,我嘗試了以下代碼。
#!/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
結果如下,
a b\ c
我期望結果為
a 'b c'
這是對 print_augs 函數的原始擴充。
為什么輸出和原始增廣不同? 或者我可以按原樣打印出原始增強嗎?
非常感謝。
使用%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
請注意, arg3
周圍沒有引號。 Bash 不會傳遞它們。
當printf
打印出 args 時,它不知道bc
周圍有引號,因此它不會打印它們。 但它確實知道 'b' 和 'c' 之間的空格是一個特殊的 shell 字符,並將\\
放在前面以對其進行轉義。
這適用於所有 bash 函數/命令,因此請記住,當您調用print_augs
也會發生同樣的情況。
如果要在字符串周圍保留引號,則需要將它們雙引號,以便 Bash 不會解析它們:
function print_augs2() {
echo "$@" >> "${output_file}"
}
print_augs2 a "'b c'"
# Output: a 'b c'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.