Recently I needed to
base64-encode a string. To do this I turned to the CLI and piped the output of
# 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?
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.
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 or follow @bramusblog on Twitter.