Odd results on base64 operations
I am having weird output on base64 operations. I have something I want to programmatically download, and found that the links contains base64 encoded data ({date}.zip
. This is evidenced by the following:
> echo "MjAyMS0wMS0xMy56aXA=" | base64 --decode
2021-01-13.zip%
If I pipe that back into base64
, I get the same result back:
> echo "MjAyMS0wMS0xMy56aXA=" | base64 --decode | base64
MjAyMS0wMS0xMy56aXA=
However, if I pass the decoded string directly to base64, I get a different result:
> echo "2021-01-13.zip" | base64
MjAyMS0wMS0xMy56aXAK
Curious as to why this is happening, and how I can resolve.
Thanks!
Solution 1:
Compare the output of these two commands:
echo "MjAyMS0wMS0xMy56aXA=" | base64 --decode | od -c
echo "2021-01-13.zip" | od -c
You will see there is no newline character in what base64 --decode
prints (because the string you start with apparently does not encode a newline character). There is a newline character in what echo
prints (because this is how echo
works). Now try this:
echo -n "2021-01-13.zip" | base64
Or better:
printf '%s' "2021-01-13.zip" | base64
Solution 2:
Echo adds by default a trailing end of line character.
Try without adding the end of line:
> echo -n "2021-01-13.zip" | base64
MjAyMS0wMS0xMy56aXA=