35

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?

AdminBee
  • 21,637
  • 21
  • 47
  • 71
Kajsa
  • 453
  • 1
  • 4
  • 5
  • [*Why does the base64 of a string contain “\n”?*](https://superuser.com/q/1225134/432690) and [*What is wrong with `echo $(stuff)`?*](https://superuser.com/q/1352850/432690) – Kamil Maciorowski Feb 25 '20 at 09:16
  • 1
    Also "useless use of `cat`". Consider `base64 -w 0 test.key` or `base64 -w 0 test.key; echo`. – Kamil Maciorowski Feb 25 '20 at 09:22

3 Answers3

56

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

... | base64 -w 0

A value of 0 will disable line wrapping.

John Hawthorne
  • 708
  • 6
  • 7
0

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.

AdminBee
  • 21,637
  • 21
  • 47
  • 71
Wxll
  • 101
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'
Patrick
  • 101
  • 1