简体   繁体   English

Bash中printf和echo的区别

[英]Difference between printf and echo in Bash

$ printf 'apple' | wc -m
       5
$ echo 'apple' | wc -m
       6

Why printf prints 5 and echo prints 6 characters? 为什么printf可打印5个字符,而echo可打印6个字符?

First sentence of entry for echo in the bash man page (emphasis mine): bash手册页中第一条echo的输入句子(强调我的意思):

Output the args, separated by spaces, followed by a newline . 输出args,以空格分隔, 后跟换行符

First sentence of the man page entry for printf : printf手册页条目的第一句:

Write the formatted arguments to the standard output under the control of the format. 在格式的控制下,将格式化的参数写入标准输出。

printf only prints what appears in the format; printf只打印格式显示的内容; it does not append an implied newline. 它不附加隐含的换行符。

There may be other difference between echo "foo" and printf "foo" , depending on what exactly foo is. echo "foo"printf "foo"之间可能还有其他区别,具体取决于foo是什么。 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. POSIX规范在实现echo为实现提供了广泛的自由裁量权,可能是避免从各种历史实现中选择一种作为标准。 Use printf when you rely on the precise output. 当您依靠精确的输出时,请使用printf

Here is the difference .. 这是区别..

$printf 'abcd'
abcd$ echo 'abcd'
abcd
$

As you can see the additional char is newline \\n 如您所见,其他字符是换行符\\n

Echo command adds "\\n" characters to the end of the string. Echo命令在字符串的末尾添加“ \\ n”字符。 That is, when we print something with the echo command, it automatically pass to the new line. 也就是说,当我们使用echo命令打印内容时,它会自动传递到新行。 But printf does not do this. 但是printf不会这样做。

echo "string" equal to "string\\n"and print "string" equal to "string" . 回显“ string”等于“ string \\ n”,并打印“ string”等于“ string”

so the output of "wc -m" command is different. 因此,“ wc -m”命令的输出是不同的。

Printf does not give new line after execution of command but echo gives new linw after the execution of command. 在执行命令后,Printf不提供新行,但在执行命令后,echo提供新的行。 Please see the bewlow code output. 请参阅以下代码输出。

Use of Printf: 使用Printf:

!/bin/sh !/ bin / sh

a=0 a = 0

while [ $a -lt 10 ] do printf $aa= expr $a + 1 done 而[$ a -lt 10]执行printf $ aa = expr $a + 1完成

o/p: 0123456789 o / p:0123456789

Use of Echo: 回声的使用:

!/bin/sh !/ bin / sh

a=0 a = 0

while [ $a -lt 10 ] do echo $aa= expr $a + 1 done 而[$ a -lt 10]做echo $ aa = expr $a + 1 done

o/p: It will print in a column wise as this window not taking as a column wise please try to execute this code it will give better understanding. o / p: 它将以列方式打印,因为此窗口不以列方式打印,请尝试执行此代码,它将更好地理解。

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

you can remove the new line in echo by giving the bewlow command echo -n $a 您可以通过给出以下命令echo -n $ a来删除echo中的新行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM