Both echo
and printf
are built-in commands (printf
is Bash built-in since v2.0.2, 1998). echo
always exits with a 0 status, and simply prints arguments followed by an end of line character on the standard output, while printf
allows for definition of a formatting string and gives a non-zero exit status code upon failure.
printf
has more control over the output format. It can be used to specify the field width to use for item, as well as various formatting choices for numbers (such as what output base to use, whether to print an exponent, whether to print a sign, and how many digits to print after the decimal point). This is done by supplying the format string, that controls how and where to print the other arguments and has the same syntax as C language (%03d
, %e
, %+d
,...). This means that you must escape the percent symbol when not talking about format (%%
).
Probably, if you add the newline character that echo
uses by default (except when using -n
option) you'll get the same effect.
printf "blah\n" >/dev/udp/localhost/8125
Concerning performance, I always had in mind that echo
was faster than printf
because the latter has to read the string and format it. But testing them with time
(also built-in) the results say otherwise:
$ time for i in {1..999999}; do echo "$i" >/dev/null; done
real 0m10.191s
user 0m4.940s
sys 0m1.710s
$ time for i in {1..999999}; do printf "$i" >/dev/null; done
real 0m9.073s
user 0m4.690s
sys 0m1.310s
Telling printf
to add newline characters, just as echo
does by default:
$ time for i in {1..999999}; do printf "$i\n" >/dev/null; done
real 0m8.940s
user 0m4.230s
sys 0m1.460s
that is obviously slower than without printing the \n
, but yet faster than echo
.
echo "blah"
andprintf "blah"
isecho
will output an extra newline. Does that matter to the server? Does the order when receiving several commands in a row matter? EOF is not something you send or even a character - it's a condition you receive when there is nothing left to read. – jw013 Dec 12 '12 at 19:11lo
and not rely on the server printing stuff. There is always iptables ... – Bananguin Dec 12 '12 at 21:44