7

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!

6
  • 4
    Is % really there? Jan 17, 2021 at 11:50
  • It is. I was going to add a P.S. on my question to get some insight into why, but neglected to do so. Might you know why? Jan 17, 2021 at 11:55
  • 14
    Probably you're using zsh. It informs you this way there is no newline character at the end of the output. Other shells would not care, they would straightforwardly print their prompt. In effect the prompt would be in the same line, concatenated with 2021-01-13.zip. Jan 17, 2021 at 11:57
  • 1
    Yep - that's right. Tested this by dropping into a bash shell and what you thought is what manifested. Good to know! Jan 17, 2021 at 12:00
  • 1
    So your tag should be zsh instead of bash, shouldn't it?
    – Ruslan
    Jan 18, 2021 at 17:46

2 Answers 2

28

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
27

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=

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .