如何转义 bash printf 中的一系列反斜杠?

How do I escape a series of backslashes in a bash printf?

以下脚本产生了意外的输出:

printf "escaped slash: \ \n"
printf "2 escaped slashes: \\ \n"
printf "3 escaped slashes: \\\ \n"
printf "4 escaped slashes: \\\\ \n"

运行 作为 Ubuntu 14 下的 bash 脚本,我看到:

escaped slash: \
2 escaped slashes: \ 
3 escaped slashes: \ 
4 escaped slashes: \

呃.. 什么?

printf 是一个 bash 内置函数。看看help printf:

printf [-v var] format [arguments]
      Formats and prints ARGUMENTS under control of the FORMAT.

您应该传递格式和参数。所以在参数前加上格式"%s\n"

printf "%s\n" "escaped slash: \"
printf "%s\n" "2 escaped slashes: \\"
printf "%s\n" "3 escaped slashes: \\\"
printf "%s\n" "4 escaped slashes: \\\\"

输出:

escaped slash: \ 
2 escaped slashes: \ 
3 escaped slashes: \\ 
4 escaped slashes: \\ 

假设 printf FORMAT 字符串被双引号括起来,与例如echo(都是 shell 内置命令)。

您对 printf 的期望实际上可以使用单引号实现:

printf '1 escaped slash:   \ \n'
printf '2 escaped slashes: \\ \n'
printf '3 escaped slashes: \\\ \n'
printf '4 escaped slashes: \\\\ \n'

输出:

1 escaped slash:   \
2 escaped slashes: \
3 escaped slashes: \\
4 escaped slashes: \\

关于赛勒斯所说内容的补充说明:

如果你用单引号引用printfARGUMENT,你应该省去很多反斜杠。例如,

printf "%s\n" 'escaped slash: \'
printf "%s\n" '2 escaped slashes: \'
printf "%s\n" '3 escaped slashes: \\'
printf "%s\n" '4 escaped slashes: \\'

产出

1 escaped slash:   \
2 escaped slashes: \
3 escaped slashes: \\
4 escaped slashes: \\