16

I'm currently writing a bash testing framework, which requires to be as portable as possible.

So, at one point, I had to print a leading newline followed by some text which contains several expanded variables. This is the solution I've used.

echo -e "\n$number_of_specs ${units}, $number_of_specs_failed failed"

This seems okay but I'm not sure how portable that is compared to printing out the line using e.g. printf?

Any ideas or hints where I could find some references?

Jens
  • 69,818
  • 15
  • 125
  • 179
helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 3
    By 'portable', do you mean portable between various shells (which means not bash) or between various bash versions? – Michał Górny Jul 17 '12 at 20:29
  • 1
    Not clear how a bash testing framework needs to be compatible with anything but bash. I guess maybe your point is that some OS's don't have printf, and as such is really not part of bash, but provides incompatibilites? Have you looked at how much work compatibility costs in the implementation of autoconf and ./configure? Why not just some tests at top, `if [[ ! -f /bin/printf ]] ; echo -e "please have printf installed before running the rest of this script" ; fi ` ?? Good luck. – shellter Jul 17 '12 at 20:31
  • 3
    I believe `printf` is technically still more portable because the default `xpg_echo` behavior can vary between platforms even within Bash (so you can set it explicitly if you really wanted.) – ormaaj Jul 17 '12 at 20:47

2 Answers2

22

printf is more portable. It should always be preferred over echo -e. If targeting bash/zsh/ksh specifically, echo $'...' is also ok. If targeting zsh or ksh specifically, print is ok.

POSIX (last link) also discusses echo -n problems, which should also be avoided. Basically, never use options to echo, and for portability, use printf.)

ormaaj
  • 6,201
  • 29
  • 34
1

The most portable (in terms of portability to ancient systems without printf) solution for leading newlines is obviously

echo
echo "$number_of_specs ${units}, $number_of_specs_failed failed"
Jens
  • 69,818
  • 15
  • 125
  • 179