[英]Bash: “printf %q $str” deletes spaces when in scripts. (Alternatives?)
[英]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..."
; 它不能(不應該)不加引號使用。
一些重要的參考資料:
eval
(上面討論的解決方法系列之一)所涉及的風險。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.