+ 2

shell bash: echo vs printf. What is the best option to maximize compatibility?

hello I'm learning to code shell scriptings and I doubt what command use to output things echo or printf I've read that "echo" is not plenty native and give some some problems attending at platform/subsystem implementation. Also with some flags like -n or -e The major of examplex I can see is using echo. So I doubt. But also reading a bit about "printf"... I see a table where appear at some point later than echo. https://www.in-ulm.de/~mascheck/various/echo+printf/ echo -ne "text" is similar to printf "text" in the most of cases. Then.... what is the standard if you want maximize compatibility support between all systems. BSD, Debian, Fedora....

5th Sep 2021, 1:41 PM
David Ordás
David Ordás - avatar
7 Antworten
+ 1
David Ordás Sorry, I meant "standard" --> "stable", it was my corrector. echo command implementations are different in many shells, so many things as parameters to this command differs with evey implementation, which means that on some implementations, parameters as "-n" or "-e" or "-E" for example, exists, and on other they doesn't. That's why printf command is a better option for more portability. But here an exception, old systems doesn't support printf command, so you make sure that when you're trying to provide more portability for old systems, use echo, but without parameters..
6th Sep 2021, 7:55 PM
Hacker-KR4636
Hacker-KR4636 - avatar
+ 2
"printf" is better because it also helps in string format
5th Sep 2021, 1:59 PM
Patel
+ 1
Martin, thanks for GNU reference So is indifferent use one or other to simply output text? You can also format using with variable expansion At least the shellcheck linter doesn't warn me about it
6th Sep 2021, 6:17 PM
David Ordás
David Ordás - avatar
+ 1
Hi bro, "echo" is not a stable, it is most a Bash command. For more compatibilities wiyh other shells, you should use "printf". "echo" doesn't exists in many other shells. And there are some notable differences between, but the most important is that "printf" formates the string to be outputed, while "echo" does't. "printf" works in the same way as programming language C "printf" function (The original one).
6th Sep 2021, 6:43 PM
Hacker-KR4636
Hacker-KR4636 - avatar
0
then.... something is wrong. GNU builtins page or your appreciated opinion where is the standard??
6th Sep 2021, 7:09 PM
David Ordás
David Ordás - avatar