Linux – What’s the safest, most portable way to invoke the echo binary

coreutilsecholinuxportability

The echo in coreutils seems to be ubiquitous, but not every system will have it in the same place (usually /bin/echo). What's the safest way to invoke this echo without knowing where it is?

I'm comfortable with the command failing if the coreutils echo binary doesn't exist on the system — that's better than echo'ing something different than I want.

Note: The motivation here is to find the echo binary, not to find a set of arguments where every shell's echo builtin is consistent. There doesn't seem to be a way to safely print just a hyphen via the echo builtin, for example, without knowing if you're in zsh or bash.

Best Answer

Note that coreutils is a software bundle developed by the GNU project to provide a set of Unix basic utilities to GNU systems. You'll only find coreutils echo out of the box on GNU systems (Debian, trisquel, Cygwin, Fedora, CentOS...). On other systems, you'll find a different (generally with different behaviour as echo is one of the least portable applications) implementation. FreeBSD will have FreeBSD echo, most Linux-based systems will have busybox echo, AIX will have AIX echo...

Some systems will even have more than one (like /bin/echo and /usr/ucb/echo on Solaris (the latter one being part of package that is now optional in later versions of Solaris like the for GNU utilities package from which you'd get a /usr/gnu/bin/echo) all with different CLIs).

GNU coreutils has been ported to most Unix-like (and even non-Unix-like such as MS Windows) systems, so you would be able to compile coreutils' echo on most systems, but that's probably not what you're looking for.

Also note that you'll find incompatibilities between versions of coreutils echo (for instance it used not to recognise \x41 sequences with -e) and that its behaviour can be affected by the environment (POSIXLY_CORRECT variable).

Now, to run the echo from the file system (found by a look-up of $PATH), like for every other builtin, the typical way is with env:

env echo this is not the builtin echo

In zsh (when not emulating other shells), you can also do:

command echo ...

without having to execute an extra env command.

But I hope the text above makes it clear that it's not going to help with regards to portability. For portability and reliability, use printf instead.

Related Question