Saturday, January 27, 2024

[SOLVED] Escape newline character while encoding in base64

Issue

I have a situation where in my BASH script, I need to encode an environment variable to base64 and write it to a json file, which is then picked up by docker.

I have the below code for this:

USER64=$(echo $USER | base64)
echo '{"auths": {"auth": "'"$USER64"'}}' > ~/.docker/config.json

This works, but the problem is the encoded value of $USER contains a \n so the echo writes it into the config file as 2 lines. How can I escape all the \n while encoding the $USER and write it to the config file?


Solution

You can use the substitution operator in shell parameter expansion.

echo '{"auths": {"auth": "'"${USER64/$'\n'/\\\n}"'}}' > ~/.docker/config.json

But you can also use an option to base64 to prevent it from putting newlines into the encoding in the first place.

USER64=$(echo $USER | base64 --wrap=0)


Answered By - Barmar
Answer Checked By - Dawn Plyler (WPSolving Volunteer)