Beware when base64-encoding on the CLI using echo

Recently I needed to base64-encode a string. To do this I turned to the CLI and piped the output of echo to base64.

# Don't use! Correct command further down this post.
$ echo 'test' | base64
dGVzdAo=

Although the output looks quite good, things didn’t quite work out when using the string: it failed when used in an implementation.

Tracking down the issue I worked my way back and decided to double check the base64-encoded string (dGVzdAo=) for its correctness. Using PHP I re-encoded the input and voila:

$ php -r "echo base64_encode('test');"
dGVzdA==

That’s different output … and it’s also to correct result. But how come? Is base64 on the CLI wrong?

~

Don’t worry, base64 on the CLI works fine. The problem we’re having here is further upstream, namely with the use of echo. By default echo will append a newline to its output, and that’s why base64 is returning an unexpected result.

Thankfully echo has a -n switch to suppress the trailing newline. By using that, things work as expected:

# Add -n to echo to prevent it from adding a newline
$ echo -n 'test' | base64
dGVzdA==

Let this post act as a note to my future self … πŸ˜…

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would always put a smile on my face. Thanks!

β˜•οΈ Buy me a Coffee (€3)

About the Author

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.