echo vs printf


In bash, or generally the family of shell languages, echo and printf are often used to output messages to the screen (or terminal, or tty, or stdout, to earn a few more geek points…). It mostly doesn’t matter when to use which. In fact, most of the time, echo is used.

But here is a case that will bite if one doesn’t understand a little more about the details.

When preparing a Kubernetes secret yaml file, the secret data itself needs to be base64ed. E.g. the password value in the below yaml snippet.

apiVersion: v1

kind: Secret


  name: mysql-pass


  password: bWFnaWNfcGFzc3dvcmQ=

To generate this base64 string, one often does this in a shell: echo "magic_password" | base64 -, then copy the output to the yaml file. Guess what, soon after applying this yaml to the cluster, one would be into long hours of investigation of authentication failures.

How could the heck the password be bad? S/he asked while scratching her/his head.

The devil is in the details. Notice the differences between these two commands:

> echo "magic_password"
> echo -n "magic_password"

The % in the second command output means that it’s a partial line. In another word, it’s ending with no newline character. It also means that the first command ended with one which would contribute to the downstream base64 command. Now you see where the problem is? An invisible newline char finds its way into the password by echo. No wonder why all those password errors.

So the -n switch solves the problem? Yes, but not really recommended. The -n behavior is not always consistent across different systems. The true way of doing this correctly is, printf "magic_password". printf never outputs an extra newline without being forced to by an explicit format like printf "hello\n".


echo vs printf