簡體   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