rgamber
rgamber

Reputation: 5849

Escape newline character while encoding in base64

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?

Upvotes: 1

Views: 3470

Answers (3)

Alamo D. Oscar
Alamo D. Oscar

Reputation: 1

Here I propose a simpler solution than the one given by Barmar.

You have to keep in mind that the echo command will add a new line character by default. So the encoded value will have a new character when you decode it.

My solution would be to encode it using the -n argument for echo command and the --wrap=0 for base64:

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

This way you won't have any new line character.

Upvotes: 0

chepner
chepner

Reputation: 531838

As added incentive to use jq, it can do the base64 encoding for you:

jq -n --arg u "$USER" '{auths: {auth: ($u | @base64)}}' > ~/.docker/config.json

(And as far as I can tell, @base64 is working on the original value, not the JSON-encode value, of $USER.)

Upvotes: 2

Barmar
Barmar

Reputation: 781751

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)

Upvotes: 1

Related Questions