Jer*_*ska 0 bash stdout printf
当我试图了解如何工作时,我编写了以下脚本printf:
#!/usr/bin/bash
printf "Give me your three preferences.?
"
read p1
read p2
read p3
printf "%s\n" "${p1}" "${p2}" "${p3}"
printf "Just the same as this, \n"
printf "%s\n%s\n%s\n" "${p1}" "${p2}" "${p3}"
printf "I've found this way to be the easiest, ${p1}\n ${p2}\n ${p3}\n"
Run Code Online (Sandbox Code Playgroud)
通过反复试验,我发现第三种方法是有效的 - 尽管没有指定这个学习资源。我printf最常使用这种方式,因为它echo类似于 -。是否存在这种打印值的方式stdout不起作用的变量情况或值?为什么我想避免这种使用方式printf?
为什么我想避免这种使用 printf 的方式?
正如 FelixJN 提到的,printf您的最后一个格式仅包含用户提供的数据。尝试您的脚本并输入类似“我的第一选择是 %s”之类的内容。在你的最后一种情况下,它不会打印%s而是将其解释为缺少参数的格式说明符(因此%s替换为任何内容):
$ p1="%s"
$ printf "I've found this way to be the easiest, ${p1}\n"
I've found this way to be the easiest,
Run Code Online (Sandbox Code Playgroud)
在其他语言中,例如 C,这甚至可以被视为安全漏洞,因为它处理错误格式的字符串不像 Bash 那样宽松。称为“格式字符串漏洞”或“不受控制的格式字符串”。
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |