Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between printf and echo in Bash

Tags:

linux

bash

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

Why printf prints 5 and echo prints 6 characters?

like image 896
TheOneTeam Avatar asked Feb 24 '16 13:02

TheOneTeam


People also ask

What is the difference between echo and print in Linux?

They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.”

Is echo faster than printf?

print is faster than echo in the loops autobahn and hypertexts.

What is echo used for in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

What does printf mean in bash?

The bash printf command is a tool used for creating formatted output. It is a shell built-in, similar to the printf() function in C/C++, Java, PHP, and other programming languages. The command allows you to print formatted text and variables in standard output.


2 Answers

First sentence of entry for echo in the bash man page (emphasis mine):

Output the args, separated by spaces, followed by a newline.

First sentence of the man page entry for printf:

Write the formatted arguments to the standard output under the control of the format.

printf only prints what appears in the format; it does not append an implied newline.

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.

like image 62
chepner Avatar answered Oct 08 '22 22:10

chepner


Here is the difference ..

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

As you can see the additional char is newline \n

like image 28
riteshtch Avatar answered Oct 09 '22 00:10

riteshtch