For displaying message and print data there are two command available printf
and echo
.
Then how differently they used? Which is more preferable?
For displaying message and print data there are two command available printf
and echo
.
Then how differently they used? Which is more preferable?
Preferable and most widely used is not the same thing. While
printf
is better for many reasons, most people still useecho
because the syntax is simpler.The main reasons why you should prefer
printf
are:echo
is not standardized, it will behave differently on different systems.It is hard to predict what you're actually running when you
echo foo
. To illustrate, on my Debian system:As you can see, there are two different
echo
commands, one is a shell (bash in this case) builtin and another is a separate binary. Note thatbash
also has aprintf
builtin but its behavior is more standardized so it is less of an issue (thanks to @ RaduRădeanu for pointing it out).Since some (but not all) implementations of
echo
support command line switches, it is hard to print a string that starts with a-
. While many programs support--
to signify the end of switches and the beginning of arguments (for example,grep -- -a file
will find lines infile
that contain-a
),echo
does not. So, how do you haveecho
print-n
?printf
can do this easily:For more information than you ever wanted to know on why
printf
is better thanecho
, see this answer to a similar question on http://unix.stackexchange.com:https://unix.stackexchange.com/a/65819/22222
To ask which is preferable is itself incomplete.
If all one wishes to do is emit one or more lines of text terminated by newlines, then echo suffices. If anything more clever is intended, specifically including a "partial line" that does not have the newline, then printf is best for that purpose.