Bash中printf和echo的区别 [英] Difference between printf and echo in Bash
问题描述
$ printf 'apple' | wc -m
5
$ echo 'apple' | wc -m
6
为什么printf可打印5个字符,而echo则可打印6个字符?
Why printf prints 5 and echo prints 6 characters?
推荐答案
bash
手册页(重点是我的内容)中echo
的第一句话:
First sentence of entry for echo
in the bash
man page (emphasis mine):
输出以空格分隔的args,后跟换行符.
printf
手册页条目的第一句:
First sentence of the man page entry for printf
:
在格式的控制下将格式化的参数写入标准输出.
Write the formatted arguments to the standard output under the control of the format.
printf
仅打印格式显示的内容;它不会附加隐含的换行符.
printf
only prints what appears in the format; it does not append an implied newline.
echo "foo"
和printf "foo"
之间可能还有其他差异,具体取决于foo
的确切含义. POSIX规范在如何实现echo
方面为实现提供了广泛的自由裁量权,可能是避免从各种历史实现中选择一种作为标准.依靠精确的输出时,请使用printf
.
There may be other difference between echo "foo"
and printf "foo"
, depending on what exactly foo
is. The POSIX specification gives implementations broad discretion in how it implements echo
, probably to avoid choosing from among the diverse historical implementations as the standard. Use printf
when you rely on the precise output.
这篇关于Bash中printf和echo的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!