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 surely put a smile on my face. Thanks!

BuymeaCoffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. 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 …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

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.