I have heard that
printf is better than
echo and I can recall only one instance from my experience where I had to use
echo didn't work for feeding some text into some program on RHEL 5.8 and
printf did. But apparently, there are other differences and I would like to inquire what they are as well as if there are specific cases when to use one vs the other.
I have heard that
Basically, it's a portability (and reliability) issue.
Now, someone thought it would be nice if we could do things like
They then thought harder but instead of adding that functionality to the shell (like
David Korn realized the mistake and introduced a new form of shell quotes:
Now when a standard Unix
Other shells/Unix vendors chose to do it differently: they added a
Sven Mascheck has a nice page that shows the extent of the problem.
On some shells like
POSIX says: if the first argument is
Those specifications don't really come to the rescue here given that many implementations are not compliant.
All in all, you don't know what
So what that means is that you can't use
This is OK:
This is not:
(Though it will work OK with some (non Unix)
Will output the content of
Will output it without the trailing newline character.
Now, there also are differences between
But in the end, if you stick to the POSIX feature set of
But remember the first argument is the format, so shouldn't contain variable/uncontrolled data.
A more reliable
The fork can be avoided using
You might want to use
Example usage and capabilities:
One "advantage", if you want to call it that, would be that you don't have to tell it like
(NB: the last
|show 3 more comments|
Also printf is faster in primitive types with respect to the echo. this is because the the type of the data is specified in the code. the difference in the speed is not recognised as countable factor unless you are coding a driver.
printf enable you to format the text to display, while echo won't. Some of them are you can specify how many decimals should be shown for floating point numbers. But in