So please use echo -n to remove the line break before redirecting to base64; and use base64 -w 0 to prevent base64 itself to add line break into the output.
me@host:~
$ echo -n mypassword | base64 -w 0
bXlwYXNzd29yZA==me@host:~ # <<<<<<<<<<<<<<< notice that no line break added after "==" due to '-w 0'; so me@host is on the same line
$ echo -n 'mypassword' | base64 -w 0
bXlwYXNzd29yZA==me@host:~ # <<<<<<<<<<<<<<<<<< notice adding single quotes does not affect output, so you can use values containing spaces freely
A good way to verify is using od -c to show the actual chars.
me@host:~
$ echo -n bXlwYXNzd29yZA== | base64 -d | od -c
0000000 m y p a s s w o r d
0000012
You see no "\n" is added. But if you use "echo" without "-n", od will show "\n":
me@host:~
$ echo mypassword | base64 -w 0
bXlwYXNzd29yZAo=me@host:~
$ echo bXlwYXNzd29yZAo= | base64 -d | od -c
0000000 m y p a s s w o r d \n
0000013
At last, create a function will help you in the future:
base64-encode() {
if [ -z "$@" ]; then
echo "Encode string with base64; echoing without line break, and base64 does not print line break neither, to not introducing extra chars while redirecting. Provide the string to encode. "
return 1
fi
echo -n "$@" | base64 -w 0 # here I suppose string if containing space is already quoted
}
java.util.Base64implements it. – Tiina Jul 04 '17 at 06:23\ns in the input? (I hope not, but who knows...) – marcelm Jul 04 '17 at 21:19\n, decoder throwsjava.lang.IllegalArgumentException: Illegal base64 character a– Tiina Jul 05 '17 at 00:48java.util.Base64.getMime{Encoder,Decoder}()respectively adds linebreaks (CRLF) and accepts/removes them – dave_thompson_085 Nov 18 '22 at 04:08