45

I am trying to echo the content of key and certificate files encoded with base64 so that I can then copy the output into other places.

I found this thread: Redirecting the content of a file to the command echo? which shows how to echo the file content and also found ways to keep the newline characters for encoding. However when I add the | base64 this breaks the output into multiple lines, and trying to add a second echo just replaces the newlines with white spaces.

$ echo "$(cat test.key)" | base64
LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUpRZ0lCQURBTkJna3Foa2lHOXcwQkFRRUZB
QVNDQ1N3d2dna29BZ0VBQW9JQ0FRRFF4Tkh0aHZvcEp1Z0EKOHBsSUNUUU1pOGMwMzRERlR6Z1E5
ME5tcE5zN2hRczNQZ0QwU2JuSFcyVGxqTS9oM1F1QVE0Q1dqaHRiV1ZUbgpSREcveGxWRFBESVVV
MzB1UHJnK0N6dlhOUkhzQkE9PQotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==

$ echo $(echo "$(cat test.key)" | base64)
LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUpRZ0lCQURBTkJna3Foa2lHOXcwQkFRRUZB QVNDQ1N3d2dna29BZ0VBQW9JQ0FRRFF4Tkh0aHZvcEp1Z0EKOHBsSUNUUU1pOGMwMzRERlR6Z1E5 ME5tcE5zN2hRczNQZ0QwU2JuSFcyVGxqTS9oM1F1QVE0Q1dqaHRiV1ZUbgpSREcveGxWRFBESVVV MzB1UHJnK0N6dlhOUkhzQkE9PQotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==

The desired output would be:

LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUpRZ0lCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQ1N3d2dna29BZ0VBQW9JQ0FRRFF4Tkh0aHZvcEp1Z0EKOHBsSUNUUU1pOGMwMzRERlR6Z1E5ME5tcE5zN2hRczNQZ0QwU2JuSFcyVGxqTS9oM1F1QVE0Q1dqaHRiV1ZUbgpSREcveGxWRFBESVVVMzB1UHJnK0N6dlhOUkhzQkE9PQotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==

How can I achieve this output?

2

3 Answers 3

73

Use the -w option (line wrapping) of base64 like this:

... | base64 -w 0

A value of 0 will disable line wrapping.

1

Not all versions of base64 support the -w 0 flag (OSX), but the same effect of the -w 0 option is created by using:

cat test.key | base64  

The output can be used for gitlab variables etc.

0

As mentioned before, not all versions of base64 support -w flag (https://www.fourmilab.ch/webtools/base64/).

That works for me:

base64 -e test.key | tr -d '\n\r'
2
  • You can tell echo to not add a new line to the end of the printed string: echo -n "some_string" | base64
    – M. Usatai
    Commented Oct 30, 2022 at 13:20
  • 1
    Yes, of course. But it's base64 that adds line breaks to the output.
    – Patrick
    Commented Nov 3, 2022 at 12:53

You must log in to answer this question.

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