
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 … 😅
~
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!
To stay in the loop you can follow bramus on Bluesky or subscribe to the RSS feed.